instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
sequencelengths
1
4.94k
PASS_TO_PASS
sequencelengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
SpikeInterface__spikeinterface-2716
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e6a67cb80..6b8d2f9b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,7 +6,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black - rev: 24.3.0 + rev: 24.4.0 hooks: - id: black files: ^src/ diff --git a/examples/modules_gallery/core/plot_4_sorting_analyzer.py b/examples/modules_gallery/core/plot_4_sorting_analyzer.py index b41109bf6..f38746bbb 100644 --- a/examples/modules_gallery/core/plot_4_sorting_analyzer.py +++ b/examples/modules_gallery/core/plot_4_sorting_analyzer.py @@ -72,7 +72,12 @@ print(analyzer) # when using format="binary_folder" or format="zarr" folder = "analyzer_folder" -analyzer = create_sorting_analyzer(sorting=sorting, recording=recording, format="binary_folder", folder=folder) +analyzer = create_sorting_analyzer(sorting=sorting, + recording=recording, + format="binary_folder", + return_scaled=True, # this is the default to attempt to return scaled + folder=folder + ) print(analyzer) # then it can be loaded back @@ -90,7 +95,7 @@ analyzer.compute( method="uniform", max_spikes_per_unit=500, ) -analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0, return_scaled=True) +analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0) analyzer.compute("templates", operators=["average", "median", "std"]) print(analyzer) @@ -100,12 +105,12 @@ print(analyzer) # using parallel processing (recommended!). Like this analyzer.compute( - "waveforms", ms_before=1.0, ms_after=2.0, return_scaled=True, n_jobs=8, chunk_duration="1s", progress_bar=True + "waveforms", ms_before=1.0, ms_after=2.0, n_jobs=8, chunk_duration="1s", progress_bar=True ) # which is equivalent to this: job_kwargs = dict(n_jobs=8, chunk_duration="1s", progress_bar=True) -analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0, return_scaled=True, **job_kwargs) +analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0, **job_kwargs) ################################################################################# # Because certain extensions rely on others (e.g. we need waveforms to calculate diff --git a/src/spikeinterface/core/template.py b/src/spikeinterface/core/template.py index d85faa751..51688709b 100644 --- a/src/spikeinterface/core/template.py +++ b/src/spikeinterface/core/template.py @@ -108,6 +108,23 @@ class Templates: if not self._are_passed_templates_sparse(): raise ValueError("Sparsity mask passed but the templates are not sparse") + def __repr__(self): + sampling_frequency_khz = self.sampling_frequency / 1000 + repr_str = ( + f"Templates: {self.num_units} units - {self.num_samples} samples - {self.num_channels} channels \n" + f"sampling_frequency={sampling_frequency_khz:.2f} kHz - " + f"ms_before={self.ms_before:.2f} ms - " + f"ms_after={self.ms_after:.2f} ms" + ) + + if self.probe is not None: + repr_str += f"\n{self.probe.__repr__()}" + + if self.sparsity is not None: + repr_str += f"\n{self.sparsity.__repr__()}" + + return repr_str + def to_sparse(self, sparsity): # Turn a dense representation of templates into a sparse one, given some sparsity. # Note that nothing prevent Templates tobe empty after sparsification if the sparse mask have no channels for some units diff --git a/src/spikeinterface/curation/remove_excess_spikes.py b/src/spikeinterface/curation/remove_excess_spikes.py index b9f00212e..52653d684 100644 --- a/src/spikeinterface/curation/remove_excess_spikes.py +++ b/src/spikeinterface/curation/remove_excess_spikes.py @@ -79,8 +79,9 @@ class RemoveExcessSpikesSortingSegment(BaseSortingSegment): ) -> np.ndarray: spike_train = self._parent_segment.get_unit_spike_train(unit_id, start_frame=start_frame, end_frame=end_frame) max_spike = np.searchsorted(spike_train, self._num_samples, side="left") + min_spike = np.searchsorted(spike_train, 0, side="left") - return spike_train[:max_spike] + return spike_train[min_spike:max_spike] def remove_excess_spikes(sorting, recording):
SpikeInterface/spikeinterface
482bd7406b790528800d0c6eed99617ee6efff9d
diff --git a/src/spikeinterface/curation/tests/test_remove_excess_spikes.py b/src/spikeinterface/curation/tests/test_remove_excess_spikes.py index f99c408c2..7175e0a61 100644 --- a/src/spikeinterface/curation/tests/test_remove_excess_spikes.py +++ b/src/spikeinterface/curation/tests/test_remove_excess_spikes.py @@ -14,6 +14,7 @@ def test_remove_excess_spikes(): num_spikes = 100 num_num_samples_spikes_per_segment = 5 num_excess_spikes_per_segment = 5 + num_neg_spike_times_per_segment = 2 times = [] labels = [] for segment_index in range(recording.get_num_segments()): @@ -21,12 +22,15 @@ def test_remove_excess_spikes(): times_segment = np.array([], dtype=int) labels_segment = np.array([], dtype=int) for unit in range(num_units): + neg_spike_times = np.random.randint(-50, 0, num_neg_spike_times_per_segment) spike_times = np.random.randint(0, num_samples, num_spikes) last_samples_spikes = (num_samples - 1) * np.ones(num_num_samples_spikes_per_segment, dtype=int) num_samples_spike_times = num_samples * np.ones(num_num_samples_spikes_per_segment, dtype=int) excess_spikes = np.random.randint(num_samples, num_samples + 100, num_excess_spikes_per_segment) spike_times = np.sort( - np.concatenate((spike_times, last_samples_spikes, num_samples_spike_times, excess_spikes)) + np.concatenate( + (neg_spike_times, spike_times, last_samples_spikes, num_samples_spike_times, excess_spikes) + ) ) spike_labels = unit * np.ones_like(spike_times) times_segment = np.concatenate((times_segment, spike_times)) @@ -47,7 +51,10 @@ def test_remove_excess_spikes(): assert ( len(spike_train_corrected) - == len(spike_train_excess) - num_num_samples_spikes_per_segment - num_excess_spikes_per_segment + == len(spike_train_excess) + - num_num_samples_spikes_per_segment + - num_excess_spikes_per_segment + - num_neg_spike_times_per_segment )
Unable to open kilosort4 results with phy Dear, I'm using `spikeinterface==0.100.5` and `kilosort4== .4.0.3`, on 64 channel 6 shanks probe. The phy output is works perfectly with the `ironclust ` generated results. However, I have encountered some issues when open the kilosort4 phy output folder. And I saw there are some silimer reports, and I tried the following things: 1. Before waveform extraction `sorting.remove_empty_units()` and `sc.remove_excess_spikes(sorting_no_empty,rec_corrected1)` 2. Set `sparse=True` or `sparse=False` or `sparse=True, method="by_property",by_property="group"` in the `si.extract_waveforms()` 3. `sparsity=None` or `sparsity=True` in the `sexp.export_to_phy()` None of above was works, and the phy is giving me the error message as below. I'm wondering if there any solution or any parameter I can adjust? Error message: ```bash 19:51:55.272 [E] __init__:62 An error has occurred (AssertionError): Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Scripts\phy.exe\__main__.py", line 7, in <module> sys.exit(phycli()) ^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\click\decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\phy\apps\__init__.py", line 159, in cli_template_gui template_gui(params_path, **kwargs) File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\phy\apps\template\gui.py", line 209, in template_gui model = load_model(params_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\phylib\io\model.py", line 1433, in load_model return TemplateModel(**get_template_params(params_path)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\phylib\io\model.py", line 339, in __init__ self._load_data() File "C:\Users\sachur\AppData\Local\anaconda3\envs\phy2\Lib\site-packages\phylib\io\model.py", line 358, in _load_data assert self.amplitudes.shape == (ns,) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError QWidget: Must construct a QApplication before a QWidget ```
0.0
482bd7406b790528800d0c6eed99617ee6efff9d
[ "src/spikeinterface/curation/tests/test_remove_excess_spikes.py::test_remove_excess_spikes" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-12 14:58:47+00:00
mit
716
SpikeInterface__spikeinterface-961
diff --git a/spikeinterface/core/base.py b/spikeinterface/core/base.py index 7775dfae9..c210cc4c5 100644 --- a/spikeinterface/core/base.py +++ b/spikeinterface/core/base.py @@ -24,6 +24,8 @@ class BaseExtractor: """ + default_missing_property_values = {"f": np.nan, "O": None, "S": "", "U": ""} + # This replaces the old key_properties # These are annotations/properties/features that always need to be # dumped (for instance locations, groups, is_fileterd, etc.) @@ -174,7 +176,6 @@ class BaseExtractor: it specifies the how the missing values should be filled, by default None. The missing_value has to be specified for types int and unsigned int. """ - default_missing_values = {"f": np.nan, "O": None, "S": "", "U": ""} if values is None: if key in self._properties: @@ -200,12 +201,12 @@ class BaseExtractor: if missing_value is None: - if dtype_kind not in default_missing_values.keys(): - raise Exception("For values dtypes other than float, string or unicode, the missing value " + if dtype_kind not in self.default_missing_property_values.keys(): + raise Exception("For values dtypes other than float, string, object or unicode, the missing value " "cannot be automatically inferred. Please specify it with the 'missing_value' " "argument.") else: - missing_value = default_missing_values[dtype_kind] + missing_value = self.default_missing_property_values[dtype_kind] else: assert dtype_kind == np.array(missing_value).dtype.kind, ("Mismatch between values and " "missing_value types. Provide a " diff --git a/spikeinterface/core/unitsaggregationsorting.py b/spikeinterface/core/unitsaggregationsorting.py index d36409145..c91bcafb9 100644 --- a/spikeinterface/core/unitsaggregationsorting.py +++ b/spikeinterface/core/unitsaggregationsorting.py @@ -3,6 +3,7 @@ import warnings import numpy as np from .core_tools import define_function_from_class +from .base import BaseExtractor from .basesorting import BaseSorting, BaseSortingSegment @@ -51,23 +52,48 @@ class UnitsAggregationSorting(BaseSorting): BaseSorting.__init__(self, sampling_frequency, unit_ids) - property_keys = sorting_list[0].get_property_keys() + annotation_keys = sorting_list[0].get_annotation_keys() + for annotation_name in annotation_keys: + if not all([annotation_name in sort.get_annotation_keys() for sort in sorting_list]): + continue + + annotations = np.array([sort.get_annotation(annotation_name, copy=False) for sort in sorting_list]) + if np.all(annotations == annotations[0]): + self.set_annotation(annotation_name, sorting_list[0].get_annotation(annotation_name)) + + property_keys = {} property_dict = {} + deleted_keys = [] + for sort in sorting_list: + for prop_name in sort.get_property_keys(): + if prop_name in deleted_keys: + continue + if prop_name in property_keys: + if property_keys[prop_name] != sort.get_property(prop_name).dtype: + print(f"Skipping property '{prop_name}: difference in dtype between sortings'") + del property_keys[prop_name] + deleted_keys.append(prop_name) + else: + property_keys[prop_name] = sort.get_property(prop_name).dtype for prop_name in property_keys: - if all([prop_name in sort.get_property_keys() for sort in sorting_list]): - for i_s, sort in enumerate(sorting_list): - prop_value = sort.get_property(prop_name) - if i_s == 0: - property_dict[prop_name] = prop_value - else: - try: - property_dict[prop_name] = np.concatenate((property_dict[prop_name], - sort.get_property(prop_name))) - except Exception as e: - print(f"Skipping property '{prop_name}' for shape inconsistency") - del property_dict[prop_name] - break - + dtype = property_keys[prop_name] + property_dict[prop_name] = np.array([], dtype=dtype) + + for sort in sorting_list: + if prop_name in sort.get_property_keys(): + values = sort.get_property(prop_name) + else: + if dtype.kind not in BaseExtractor.default_missing_property_values: + del property_dict[prop_name] + break + values = np.full(sort.get_num_units(), BaseExtractor.default_missing_property_values[dtype.kind], dtype=dtype) + + try: + property_dict[prop_name] = np.concatenate((property_dict[prop_name], values)) + except Exception as e: + print(f"Skipping property '{prop_name}' for shape inconsistency") + del property_dict[prop_name] + break for prop_name, prop_values in property_dict.items(): self.set_property(key=prop_name, values=prop_values)
SpikeInterface/spikeinterface
9d7823d620386b634c56fbc8d4686f824690ccde
diff --git a/spikeinterface/core/tests/test_unitsaggregationsorting.py b/spikeinterface/core/tests/test_unitsaggregationsorting.py index 77a97665d..aad533366 100644 --- a/spikeinterface/core/tests/test_unitsaggregationsorting.py +++ b/spikeinterface/core/tests/test_unitsaggregationsorting.py @@ -55,6 +55,27 @@ def test_unitsaggregationsorting(): assert all( unit in renamed_unit_ids for unit in sorting_agg_renamed.get_unit_ids()) + # test annotations + + # matching annotation + sorting1.annotate(organ="brain") + sorting2.annotate(organ="brain") + sorting3.annotate(organ="brain") + + # not matching annotation + sorting1.annotate(area="CA1") + sorting2.annotate(area="CA2") + sorting3.annotate(area="CA3") + + # incomplete annotation + sorting1.annotate(date="2022-10-13") + sorting2.annotate(date="2022-10-13") + + sorting_agg_prop = aggregate_units([sorting1, sorting2, sorting3]) + assert sorting_agg_prop.get_annotation('organ') == "brain" + assert "area" not in sorting_agg_prop.get_annotation_keys() + assert "date" not in sorting_agg_prop.get_annotation_keys() + # test properties # complete property @@ -67,13 +88,18 @@ def test_unitsaggregationsorting(): sorting1.set_property("template", np.zeros((num_units, 20, 50))) sorting1.set_property("template", np.zeros((num_units, 2, 10))) - # incomplete property + # incomplete property (str can't be propagated) sorting1.set_property("quality", ["good"]*num_units) sorting2.set_property("quality", ["bad"]*num_units) + # incomplete property (object can be propagated) + sorting1.set_property("rand", np.random.rand(num_units)) + sorting2.set_property("rand", np.random.rand(num_units)) + sorting_agg_prop = aggregate_units([sorting1, sorting2, sorting3]) assert "brain_area" in sorting_agg_prop.get_property_keys() assert "quality" not in sorting_agg_prop.get_property_keys() + assert "rand" in sorting_agg_prop.get_property_keys() print(sorting_agg_prop.get_property("brain_area"))
UnitsAggregationSorting fails to inherit property Hi, I saw in the `UnitsAggregationSorting` code that there is a copying of properties if they are consistent over all sortings. However, look at the following code: ```python sorting.annotate(name="Bonjour") sorting.get_annotation("name") > 'Bonjour' sorting1 = sorting.select_units([0, 1]) sorting1.get_annotation("name") > 'Bonjour' sorting2 = sorting.select_units([unit_id for unit_id in sorting.unit_ids if unit_id != 0 and unit_id != 1]) sorting2.get_annotation("name") > 'Bonjour' new_sorting = si.UnitsAggregationSorting([sorting1, sorting2]) new_sorting.get_annotation("name") > None ``` I believe the property should be inherited in this case. Thanks, Aurélien W.
0.0
9d7823d620386b634c56fbc8d4686f824690ccde
[ "spikeinterface/core/tests/test_unitsaggregationsorting.py::test_unitsaggregationsorting" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-26 09:01:21+00:00
mit
717
SteadBytes__aocpy-13
diff --git a/README.md b/README.md index 7ffb74a..ccb3a6a 100644 --- a/README.md +++ b/README.md @@ -73,12 +73,12 @@ AoC puzzle inputs differ by user, requiring a browser cookie to determine the cu - `$ aocpy begin -c <1234mycookie>` - Configuration file: - Paste the cookie into a file at `~/.config/aocpy/token` - ``` - # ~/.config/aocpy/token - <1234mycookie> - ``` + ``` + # ~/.config/aocpy/token + <1234mycookie> + ``` + - or set it via cli `aocpy set-cookie <1234mycookie>` - Environment variable: - - `$ export AOC_SESSION_COOKIE=<1234mycookie>` ### Finding Your Session Cookie diff --git a/aocpy/cli.py b/aocpy/cli.py index a0b4ea8..762b841 100644 --- a/aocpy/cli.py +++ b/aocpy/cli.py @@ -14,7 +14,7 @@ from aocpy.puzzle import ( check_submission_response_text, get_puzzle_input, ) -from aocpy.utils import current_day, current_year, get_session_cookie +from aocpy.utils import current_day, current_year, get_session_cookie, get_config_dir, get_token_file def begin_day(session: web.AuthSession, p: Puzzle): @@ -74,5 +74,13 @@ def submit(answer, level, year, day, session_cookie): click.echo(err) [email protected]() [email protected]("cookie") +def set_cookie(cookie): + get_config_dir().mkdir(exist_ok=True, parents=True) + get_token_file().write_text(cookie) + click.echo(f"Saved cookie in {get_token_file()}") + + if __name__ == "__main__": cli() diff --git a/aocpy/utils.py b/aocpy/utils.py index df5a897..fca69fe 100644 --- a/aocpy/utils.py +++ b/aocpy/utils.py @@ -1,5 +1,6 @@ import os from datetime import datetime +from pathlib import Path import pytz @@ -9,6 +10,14 @@ AOC_TZ = pytz.timezone("America/New_York") CONFIG_DIRNAME = "~/.config/aocpy" +def get_config_dir(): + return Path(os.path.expanduser(CONFIG_DIRNAME)) + + +def get_token_file(): + return get_config_dir() / 'token' + + def current_year(): """ Returns the most recent AOC year available """ @@ -36,7 +45,7 @@ def get_session_cookie(): if cookie is not None: return cookie try: - with open(os.path.join(os.path.expanduser(CONFIG_DIRNAME), "token")) as f: + with get_token_file().open() as f: cookie = f.read().strip() except (OSError, IOError): pass
SteadBytes/aocpy
7dc93d4ba672699aba83918ebe9b1f5f3ff0e175
diff --git a/tests/test_cli.py b/tests/test_cli.py index 06431e8..0fef984 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,16 +1,15 @@ import contextlib from datetime import datetime +from pathlib import Path import pytest import pytz from click.testing import CliRunner from freezegun import freeze_time +from hypothesis import strategies as st, given from aocpy.cli import cli -from pathlib import Path -from hypothesis import strategies as st, given - class Runner(CliRunner): @contextlib.contextmanager @@ -33,6 +32,13 @@ def home_dir(tmp_path): @pytest.fixture def config_dir(home_dir): + d = home_dir / ".config/aocpy" + d.mkdir(parents=True) + return d + + [email protected] +def cache_dir(home_dir): d = home_dir / ".config/aocd" d.mkdir(parents=True) return d @@ -44,7 +50,7 @@ def runner(home_dir): @freeze_time(datetime(2019, 12, 10, hour=1, tzinfo=pytz.timezone("America/New_York"))) -def test_begin(webbrowser_open, runner, config_dir, responses): +def test_begin(webbrowser_open, runner, cache_dir, responses): puzzle_url = "https://adventofcode.com/2019/day/10" puzzle_input = "some text" responses.add(responses.GET, puzzle_url + "/input", body=puzzle_input) @@ -56,13 +62,23 @@ def test_begin(webbrowser_open, runner, config_dir, responses): assert (p / "10/input.txt").exists() assert (p / "10/solution.py").exists() # Input is cached - assert (config_dir / cookie / "2019/10.txt").exists() + assert (cache_dir / cookie / "2019/10.txt").exists() # Browser opened to today's puzzle URL webbrowser_open.assert_called_once_with(puzzle_url) +def test_set_cookie(runner, config_dir): + cookie = "12345" + with runner.isolated_filesystem() as p: + result = runner.invoke(cli, ["set-cookie", cookie]) + assert result.exit_code == 0 + # Token file generated and contains new value + assert (config_dir / "token").exists() + assert (config_dir / "token").read_text() == cookie + + @pytest.mark.parametrize("day", range(26, 32)) -def test_begin_uses_day_25_as_max(day, webbrowser_open, runner, config_dir, responses): +def test_begin_uses_day_25_as_max(day, webbrowser_open, runner, cache_dir, responses): puzzle_url = "https://adventofcode.com/2019/day/25" puzzle_input = "some text" responses.add(responses.GET, puzzle_url + "/input", body=puzzle_input) @@ -75,7 +91,7 @@ def test_begin_uses_day_25_as_max(day, webbrowser_open, runner, config_dir, resp assert (p / "25/input.txt").exists() assert (p / "25/solution.py").exists() # Input is cached - assert (config_dir / cookie / "2019/25.txt").exists() + assert (cache_dir / cookie / "2019/25.txt").exists() # Browser opened to today's puzzle URL webbrowser_open.assert_called_once_with(puzzle_url) @@ -93,7 +109,7 @@ def test_begin_fails_if_not_december( @freeze_time(datetime(2019, 12, 25, hour=1, tzinfo=pytz.timezone("America/New_York"))) @pytest.mark.parametrize("day", range(1, 25)) -def test_begin_specify_day(day, webbrowser_open, runner, config_dir, responses): +def test_begin_specify_day(day, webbrowser_open, runner, cache_dir, responses): puzzle_url = f"https://adventofcode.com/2019/day/{day}" puzzle_input = "some text" responses.add(responses.GET, puzzle_url + "/input", body=puzzle_input) @@ -105,7 +121,7 @@ def test_begin_specify_day(day, webbrowser_open, runner, config_dir, responses): assert (p / f"{day:02}/input.txt").exists() assert (p / f"{day:02}/solution.py").exists() # Input is cached - assert (config_dir / cookie / f"2019/{day:02}.txt").exists() + assert (cache_dir / cookie / f"2019/{day:02}.txt").exists() # Browser opened to today's puzzle URL webbrowser_open.assert_called_once_with(puzzle_url) @@ -113,7 +129,7 @@ def test_begin_specify_day(day, webbrowser_open, runner, config_dir, responses): @freeze_time(datetime(2019, 12, 25, hour=1, tzinfo=pytz.timezone("America/New_York"))) @given(st.integers().filter(lambda x: not (1 <= x <= 25))) def test_begin_specify_fails_if_out_of_range( - webbrowser_open, runner, config_dir, day + webbrowser_open, runner, config_dir, day ): cookie = "12345" with runner.isolated_filesystem(): @@ -123,7 +139,7 @@ def test_begin_specify_fails_if_out_of_range( @freeze_time(datetime(2019, 12, 10, hour=1, tzinfo=pytz.timezone("America/New_York"))) @pytest.mark.parametrize("year", range(2015, 2019)) -def test_begin_specify_year(year, webbrowser_open, runner, config_dir, responses): +def test_begin_specify_year(year, webbrowser_open, runner, cache_dir, responses): day = 10 # matches frozen datetime puzzle_url = f"https://adventofcode.com/{year}/day/{day}" puzzle_input = "some text" @@ -136,7 +152,7 @@ def test_begin_specify_year(year, webbrowser_open, runner, config_dir, responses assert (p / f"{day:02}/input.txt").exists() assert (p / f"{day:02}/solution.py").exists() # Input is cached - assert (config_dir / cookie / f"{year}/{day:02}.txt").exists() + assert (cache_dir / cookie / f"{year}/{day:02}.txt").exists() # Browser opened to today's puzzle URL webbrowser_open.assert_called_once_with(puzzle_url) @@ -144,7 +160,7 @@ def test_begin_specify_year(year, webbrowser_open, runner, config_dir, responses @pytest.mark.parametrize("day", range(1, 25)) @pytest.mark.parametrize("year", range(2015, 2019)) def test_begin_specify_day_and_year( - year, day, webbrowser_open, runner, config_dir, responses + year, day, webbrowser_open, runner, cache_dir, responses ): puzzle_url = f"https://adventofcode.com/{year}/day/{day}" puzzle_input = "some text" @@ -157,13 +173,13 @@ def test_begin_specify_day_and_year( assert (p / f"{day:02}/input.txt").exists() assert (p / f"{day:02}/solution.py").exists() # Input is cached - assert (config_dir / cookie / f"{year}/{day:02}.txt").exists() + assert (cache_dir / cookie / f"{year}/{day:02}.txt").exists() # Browser opened to today's puzzle URL webbrowser_open.assert_called_once_with(puzzle_url) @freeze_time(datetime(2019, 12, 10, hour=1, tzinfo=pytz.timezone("America/New_York"))) -def test_begin_cached_input(webbrowser_open, runner, config_dir, responses): +def test_begin_cached_input(webbrowser_open, runner, cache_dir, responses): """ Puzzle input should not be fetched from https://adventofcode.com if it has been cached locally. Here, the `responses` fixture will raise an exception if @@ -171,9 +187,9 @@ def test_begin_cached_input(webbrowser_open, runner, config_dir, responses): """ puzzle_url = "https://adventofcode.com/2019/day/10" cookie = "12345" - cache_dir = config_dir / cookie / "2019" - cache_dir.mkdir(parents=True) - with (cache_dir / "10.txt").open("w") as f: + year_cache_dir = cache_dir / cookie / "2019" + year_cache_dir.mkdir(parents=True) + with (year_cache_dir / "10.txt").open("w") as f: f.write("some text") with runner.isolated_filesystem() as p: result = runner.invoke(cli, ["begin", "-c", cookie])
Add CLI option to set cookie in `~/.config/aocpy/token` As a user, I want to set the cookie using cli command So that I do not have to create the folders and token file myself. Proposal: `aocpy set-cookie <cookie>` - Creates folders if they do not exists - write `<cookie>` to token file
0.0
7dc93d4ba672699aba83918ebe9b1f5f3ff0e175
[ "tests/test_cli.py::test_set_cookie" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-02 06:48:44+00:00
mit
718
StellarCN__py-stellar-base-817
diff --git a/stellar_sdk/scval.py b/stellar_sdk/scval.py index 418a6d5e..2a3c9dbb 100644 --- a/stellar_sdk/scval.py +++ b/stellar_sdk/scval.py @@ -624,8 +624,11 @@ def to_struct(data: Dict[str, stellar_xdr.SCVal]) -> stellar_xdr.SCVal: :param data: The dict value to convert. :return: A new :class:`stellar_sdk.xdr.SCVal` XDR object. """ + # sort the dict by key to ensure the order of the fields. + # see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0046-01.md#validity + sorted_data = dict(sorted(data.items())) v = dict() - for key, val in data.items(): + for key, val in sorted_data.items(): v[to_symbol(key)] = val return to_map(v)
StellarCN/py-stellar-base
300dc1f6c2be64b8354dc8582f1ff5a2cbb4bb17
diff --git a/tests/test_scval.py b/tests/test_scval.py index 73c15508..a091c7aa 100644 --- a/tests/test_scval.py +++ b/tests/test_scval.py @@ -315,14 +315,14 @@ def test_tuple_struct(): def test_struct(): v = { - "data1": to_int32(1), - "data2": to_int256(23423432), - "data3": to_string("world"), - "data4": to_vec([to_int32(1), to_int256(23423432), to_string("world")]), - "data5": to_struct( + "simpleData": to_int32(1), + "a": to_int256(23423432), + "data": to_string("world"), + "a1": to_vec([to_int32(1), to_int256(23423432), to_string("world")]), + "A": to_struct( { - "inner_data1": to_int32(1), - "inner_data2": to_int256(23423432), + "inner_data2": to_int32(1), + "inner_data1": to_int256(23423432), } ), } @@ -331,22 +331,22 @@ def test_struct(): stellar_xdr.SCValType.SCV_MAP, map=xdr.SCMap( [ - xdr.SCMapEntry(to_symbol("data1"), to_int32(1)), - xdr.SCMapEntry(to_symbol("data2"), to_int256(23423432)), - xdr.SCMapEntry(to_symbol("data3"), to_string("world")), xdr.SCMapEntry( - to_symbol("data4"), - to_vec([to_int32(1), to_int256(23423432), to_string("world")]), - ), - xdr.SCMapEntry( - to_symbol("data5"), + to_symbol("A"), to_map( { - to_symbol("inner_data1"): to_int32(1), - to_symbol("inner_data2"): to_int256(23423432), + to_symbol("inner_data1"): to_int256(23423432), + to_symbol("inner_data2"): to_int32(1), } ), ), + xdr.SCMapEntry(to_symbol("a"), to_int256(23423432)), + xdr.SCMapEntry( + to_symbol("a1"), + to_vec([to_int32(1), to_int256(23423432), to_string("world")]), + ), + xdr.SCMapEntry(to_symbol("data"), to_string("world")), + xdr.SCMapEntry(to_symbol("simpleData"), to_int32(1)), ] ), )
Soroban - Failing to invoke function with struct parameter ``` stellar-sdk==9.0.0b0 ``` I deployed [this contract](https://github.com/bp-ventures/lightecho-stellar-oracle/blob/328e897bb69ea194d642540584bb4c94362bbc8e/oracle-onchain/sep40/contract/src/contract.rs) which has this function inside it: ``` fn add_prices(env: Env, prices: Vec<Price>); ``` When [invoking the function via Rust](https://github.com/bp-ventures/lightecho-stellar-oracle/blob/328e897bb69ea194d642540584bb4c94362bbc8e/oracle-onchain/sep40/contract/src/test.rs#L578), it works as expected. But when invoking it from Python, I get this error: ``` 0: [Diagnostic Event] topics:[error, Error(Value, InternalError)], data:"failed to convert ScVal to host value ``` ## How to reproduce `test.py`: ``` from stellar_sdk import scval, xdr as stellar_xdr from stellar_sdk.soroban_server import SorobanServer from stellar_sdk import TransactionBuilder, Keypair import time from stellar_sdk.exceptions import PrepareTransactionException from stellar_sdk.soroban_rpc import GetTransactionStatus, SendTransactionStatus SOURCE_SECRET = "SDFWYGBNP5TW4MS7RY5D4FILT65R2IEPWGL34NY2TLSU4DC4BJNXUAMU" CONTRACT_ID = "CA3BDS2ME2F4SFMRWWHITPQXQL5DDA35SEVOETK7BDDEJRAJQJDFUSDO" NETWORK_PASSPHRASE = "Test SDF Network ; September 2015" RPC_URL = "https://soroban-testnet.stellar.org:443/" BASE_FEE = 300000 price_list = [] price_struct = scval.to_struct( { "source": scval.to_uint32(999), "asset": scval.to_enum("Other", scval.to_symbol("TEST")), "price": scval.to_int128(1), "timestamp": scval.to_uint64(1699779449), } ) price_list.append(price_struct) price_vec = scval.to_vec(price_list) parameters = [price_vec] server = SorobanServer(RPC_URL) source_kp = Keypair.from_secret(SOURCE_SECRET) source_account = server.load_account(source_kp.public_key) tx = ( TransactionBuilder( source_account, NETWORK_PASSPHRASE, base_fee=BASE_FEE, ) .set_timeout(30) .append_invoke_contract_function_op( CONTRACT_ID, "add_prices", parameters, ) .build() ) try: tx = server.prepare_transaction(tx) except PrepareTransactionException as e: print(e.simulate_transaction_response) raise tx.sign(source_kp) send_transaction_data = server.send_transaction(tx) if send_transaction_data.status != SendTransactionStatus.PENDING: raise RuntimeError(f"Failed to send transaction: {send_transaction_data}") tx_hash = send_transaction_data.hash while True: get_transaction_data = server.get_transaction(tx_hash) if get_transaction_data.status != GetTransactionStatus.NOT_FOUND: break time.sleep(3) tx_data = get_transaction_data if tx_data.status != GetTransactionStatus.SUCCESS: raise RuntimeError(f"Failed to send transaction: {tx_data}") print(tx_data) ``` ``` python test.py ``` ``` preparing xdr: AAAAAgAAAADc5Y9UXuU88Ks7OirvJZTwjhMZOQhkC4Y6+CTwK5Sw1gAEk+AAGSgAAAAABwAAAAEAAAAAAAAAAAAAAABlUJoIAAAAAAAAAAEAAAAAAAAAGAAAAAAAAAABNhHLTCaLyRWRtY6JvheC+jGDfZEq4k1fCMZExAmCRloAAAAKYWRkX3ByaWNlcwAAAAAAAQAAABAAAAABAAAAAQAAABEAAAABAAAABAAAAA8AAAAGc291cmNlAAAAAAADAAAD5wAAAA8AAAAFYXNzZXQAAAAAAAAQAAAAAQAAAAIAAAAPAAAABU90aGVyAAAAAAAADwAAAARURVNUAAAADwAAAAVwcmljZQAAAAAAAAoAAAAAAAAAAAAAAAAAAAABAAAADwAAAAl0aW1lc3RhbXAAAAAAAAAFAAAAAGVQk3kAAAAAAAAAAAAAAAA= error='host invocation failed\n\nCaused by:\n HostError: Error(Value, InternalError)\n \n Event log (newest first):\n 0: [Diagnostic Event] topics:[error, Error(Value, InternalError)], data:"failed to convert ScVal to host value"\n 1: [Diagnostic Event] topics:[error, Error(Value, InternalError)], data:"failed to convert ScVal to host value"\n \n Backtrace (newest first):\n 0: <core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::try_fold\n 1: <alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter\n 2: soroban_env_host::host::metered_clone::MeteredIterator::metered_collect\n 3: soroban_env_host::host::frame::<impl soroban_env_host::host::Host>::invoke_function\n 4: preflight::preflight::preflight_invoke_hf_op\n 5: preflight::preflight_invoke_hf_op::{{closure}}\n 6: core::ops::function::FnOnce::call_once{{vtable.shim}}\n 7: preflight::catch_preflight_panic\n 8: _cgo_0b49d6ed4a0b_Cfunc_preflight_invoke_hf_op\n at tmp/go-build/cgo-gcc-prolog:103:11\n 9: runtime.asmcgocall\n at ./runtime/asm_amd64.s:848\n \n ' transaction_data=None min_resource_fee=None events=['AAAAAAAAAAAAAAAAAAAAAgAAAAAAAAACAAAADwAAAAVlcnJvcgAAAAAAAAIAAAAIAAAABwAAAA4AAAAlZmFpbGVkIHRvIGNvbnZlcnQgU2NWYWwgdG8gaG9zdCB2YWx1ZQAAAA==', 'AAAAAAAAAAAAAAAAAAAAAgAAAAAAAAACAAAADwAAAAVlcnJvcgAAAAAAAAIAAAAIAAAABwAAAA4AAAAlZmFpbGVkIHRvIGNvbnZlcnQgU2NWYWwgdG8gaG9zdCB2YWx1ZQAAAA=='] results=None cost=SimulateTransactionCost(cpu_insns=0, mem_bytes=0) restore_preamble=None latest_ledger=2481914 Traceback (most recent call last): File "/home/yuri/test.py", line 47, in <module> tx = server.prepare_transaction(tx) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/yuri/.cache/pypoetry/virtualenvs/cli-sOWdBO30-py3.11/lib/python3.11/site-packages/stellar_sdk/soroban_server.py", line 310, in prepare_transaction raise PrepareTransactionException( stellar_sdk.exceptions.PrepareTransactionException: Simulation transaction failed, the response contains error information. ``` I looked into the XDR and it looks correct, the parameter is a ScVec and each item is a ScMap, which should get converted into Struct but I guess that is the part that's broken. Not sure if the issue is coming from Soroban or the Python SDK.
0.0
300dc1f6c2be64b8354dc8582f1ff5a2cbb4bb17
[ "tests/test_scval.py::test_struct" ]
[ "tests/test_scval.py::test_address", "tests/test_scval.py::test_bool", "tests/test_scval.py::test_bytes", "tests/test_scval.py::test_duration[18446744073709551615]", "tests/test_scval.py::test_duration[0]", "tests/test_scval.py::test_duration_out_of_range_raise[18446744073709551616]", "tests/test_scval.py::test_duration_out_of_range_raise[-1]", "tests/test_scval.py::test_int32[2147483647]", "tests/test_scval.py::test_int32[-2147483648]", "tests/test_scval.py::test_int32_out_of_range_raise[2147483648]", "tests/test_scval.py::test_int32_out_of_range_raise[-2147483649]", "tests/test_scval.py::test_int64[9223372036854775807]", "tests/test_scval.py::test_int64[-9223372036854775808]", "tests/test_scval.py::test_int64_out_of_range_raise[9223372036854775808]", "tests/test_scval.py::test_int64_out_of_range_raise[-9223372036854775809]", "tests/test_scval.py::test_int128[0-AAAACgAAAAAAAAAAAAAAAAAAAAA=]", "tests/test_scval.py::test_int128[1-AAAACgAAAAAAAAAAAAAAAAAAAAE=]", "tests/test_scval.py::test_int128[-1-AAAACv////////////////////8=]", "tests/test_scval.py::test_int128[18446744073709551616-AAAACgAAAAAAAAABAAAAAAAAAAA=]", "tests/test_scval.py::test_int128[-18446744073709551616-AAAACv//////////AAAAAAAAAAA=]", "tests/test_scval.py::test_int128[170141183460469231731687303715884105727-AAAACn////////////////////8=]", "tests/test_scval.py::test_int128[-170141183460469231731687303715884105728-AAAACoAAAAAAAAAAAAAAAAAAAAA=]", "tests/test_scval.py::test_int128_out_of_range_raise[170141183460469231731687303715884105728]", "tests/test_scval.py::test_int128_out_of_range_raise[-170141183460469231731687303715884105729]", "tests/test_scval.py::test_int256[0-AAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256[1-AAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB]", "tests/test_scval.py::test_int256[-1-AAAADP//////////////////////////////////////////]", "tests/test_scval.py::test_int256[18446744073709551616-AAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAA]", "tests/test_scval.py::test_int256[-18446744073709551616-AAAADP///////////////////////////////wAAAAAAAAAA]", "tests/test_scval.py::test_int256[340282366920938463463374607431768211456-AAAADAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256[-340282366920938463463374607431768211456-AAAADP////////////////////8AAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256[6277101735386680763835789423207666416102355444464034512896-AAAADAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256[-6277101735386680763835789423207666416102355444464034512896-AAAADP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256[57896044618658097711785492504343953926634992332820282019728792003956564819967-AAAADH//////////////////////////////////////////]", "tests/test_scval.py::test_int256[-57896044618658097711785492504343953926634992332820282019728792003956564819968-AAAADIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_int256_out_of_range_raise[57896044618658097711785492504343953926634992332820282019728792003956564819968]", "tests/test_scval.py::test_int256_out_of_range_raise[-57896044618658097711785492504343953926634992332820282019728792003956564819969]", "tests/test_scval.py::test_map", "tests/test_scval.py::test_string[hello]", "tests/test_scval.py::test_string[world]", "tests/test_scval.py::test_symbol", "tests/test_scval.py::test_timepoint", "tests/test_scval.py::test_timepoint_out_of_range_raise[18446744073709551616]", "tests/test_scval.py::test_timepoint_out_of_range_raise[-1]", "tests/test_scval.py::test_uint32[4294967295]", "tests/test_scval.py::test_uint32[0]", "tests/test_scval.py::test_uint32_out_of_range_raise[4294967296]", "tests/test_scval.py::test_uint32_out_of_range_raise[-1]", "tests/test_scval.py::test_uint64[18446744073709551615]", "tests/test_scval.py::test_uint64[0]", "tests/test_scval.py::test_uint64_out_of_range_raise[18446744073709551616]", "tests/test_scval.py::test_uint64_out_of_range_raise[-1]", "tests/test_scval.py::test_uint128[0-AAAACQAAAAAAAAAAAAAAAAAAAAA=]", "tests/test_scval.py::test_uint128[1-AAAACQAAAAAAAAAAAAAAAAAAAAE=]", "tests/test_scval.py::test_uint128[18446744073709551616-AAAACQAAAAAAAAABAAAAAAAAAAA=]", "tests/test_scval.py::test_uint128[340282366920938463463374607431768211455-AAAACf////////////////////8=]", "tests/test_scval.py::test_uint128_out_of_range_raise[-1]", "tests/test_scval.py::test_uint128_out_of_range_raise[340282366920938463463374607431768211456]", "tests/test_scval.py::test_uint256[0-AAAACwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_uint256[1-AAAACwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB]", "tests/test_scval.py::test_uint256[18446744073709551616-AAAACwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAA]", "tests/test_scval.py::test_uint256[340282366920938463463374607431768211456-AAAACwAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_uint256[6277101735386680763835789423207666416102355444464034512896-AAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA]", "tests/test_scval.py::test_uint256[115792089237316195423570985008687907853269984665640564039457584007913129639935-AAAAC///////////////////////////////////////////]", "tests/test_scval.py::test_uint256_out_of_range_raise[-1]", "tests/test_scval.py::test_uint256_out_of_range_raise[115792089237316195423570985008687907853269984665640564039457584007913129639936]", "tests/test_scval.py::test_vec", "tests/test_scval.py::test_enum_with_value", "tests/test_scval.py::test_enum_without_value", "tests/test_scval.py::test_tuple_struct" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-11-13 02:30:52+00:00
apache-2.0
719
StevenLooman__async_upnp_client-62
diff --git a/CHANGES.rst b/CHANGES.rst index 91ef03d..e023450 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,6 +4,7 @@ Changes 0.16.1 (unreleased) - Don't double-unescape action responses (#50) +- Add `UpnpDevice.service_id()` to get service by service_id. (@bazwilliams) 0.16.0 (2021-03-30) diff --git a/async_upnp_client/client.py b/async_upnp_client/client.py index fc77560..2d548a4 100644 --- a/async_upnp_client/client.py +++ b/async_upnp_client/client.py @@ -217,6 +217,13 @@ class UpnpDevice: """Get service by service_type.""" return self.services[service_type] + def service_id(self, service_id: str) -> Optional["UpnpService"]: + """Get service by service_id.""" + for service in self.services.values(): + if service.service_id == service_id: + return service + return None + async def async_ping(self) -> None: """Ping the device.""" await self.requester.async_http_request("GET", self.device_url)
StevenLooman/async_upnp_client
e76f7f3296c8351106625b6d013e0620fdf16f7e
diff --git a/tests/test_upnp_client.py b/tests/test_upnp_client.py index 2864da1..ec11311 100644 --- a/tests/test_upnp_client.py +++ b/tests/test_upnp_client.py @@ -32,6 +32,9 @@ class TestUpnpStateVariable: service = device.service("urn:schemas-upnp-org:service:RenderingControl:1") assert service + service_by_id = device.service_id("urn:upnp-org:serviceId:RenderingControl") + assert service_by_id == service + state_var = service.state_variable("Volume") assert state_var
Ability to get `UpnpService` by id rather than type? On Linn devices, the manufacturer may increase the service version in their description document. For example the service description on a recent firmware for the volume service is: ```xml <service> <serviceType>urn:av-openhome-org:service:Volume:4</serviceType> <serviceId>urn:av-openhome-org:serviceId:Volume</serviceId> <SCPDURL>/4c494e4e-1234-ab12-abcd-01234567819f/Upnp/av.openhome.org-Volume-4/service.xml</SCPDURL> <controlURL>/4c494e4e-1234-ab12-abcd-01234567819f/av.openhome.org-Volume-4/control</controlURL> <eventSubURL>/4c494e4e-1234-ab12-abcd-01234567819f/av.openhome.org-Volume-4/event</eventSubURL> </service> ``` However on an older version or software open home player, the service description is: ```xml <service> <serviceType>urn:av-openhome-org:service:Volume:1</serviceType> <serviceId>urn:av-openhome-org:serviceId:Volume</serviceId> <SCPDURL>/4c494e4e-1234-ab12-abcd-01234567819f/Upnp/av.openhome.org-Volume-1/service.xml</SCPDURL> <controlURL>/4c494e4e-1234-ab12-abcd-01234567819f/av.openhome.org-Volume-1/control</controlURL> <eventSubURL>/4c494e4e-1234-ab12-abcd-01234567819f/av.openhome.org-Volume-1/event</eventSubURL> </service> ``` Would it be possible to add a facility to fetch the service from a client by using the `serviceId` field in addition to `serviceType`? I'm using your library in an `openhome` integration for HomeAssistant (homeassistant.io) and to support all potential iterations of the volume and product services on supported products I need to attempt all potential versions of a service (https://github.com/bazwilliams/openhomedevice/blob/rewrite-unit-tests/openhomedevice/Device.py#L32) this also means should Linn bring out a newer version of their firmware with a newer service, this integration would be partially unavailable despite the newer service being backwards compatible. I'm happy to propose a PR if you'd like?
0.0
e76f7f3296c8351106625b6d013e0620fdf16f7e
[ "tests/test_upnp_client.py::TestUpnpStateVariable::test_init" ]
[ "tests/test_upnp_client.py::TestUpnpStateVariable::test_init_xml", "tests/test_upnp_client.py::TestUpnpStateVariable::test_set_value_volume", "tests/test_upnp_client.py::TestUpnpStateVariable::test_set_value_mute", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_min_max", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_min_max_validation_disable", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_allowed_value", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_upnp_value_error", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_date_time", "tests/test_upnp_client.py::TestUpnpStateVariable::test_value_date_time_tz", "tests/test_upnp_client.py::TestUpnpStateVariable::test_send_events", "tests/test_upnp_client.py::TestUpnpAction::test_init", "tests/test_upnp_client.py::TestUpnpAction::test_valid_arguments", "tests/test_upnp_client.py::TestUpnpAction::test_format_request", "tests/test_upnp_client.py::TestUpnpAction::test_format_request_escape", "tests/test_upnp_client.py::TestUpnpAction::test_parse_response", "tests/test_upnp_client.py::TestUpnpAction::test_parse_response_empty", "tests/test_upnp_client.py::TestUpnpAction::test_parse_response_error", "tests/test_upnp_client.py::TestUpnpAction::test_parse_response_escape", "tests/test_upnp_client.py::TestUpnpAction::test_unknown_out_argument", "tests/test_upnp_client.py::TestUpnpService::test_init", "tests/test_upnp_client.py::TestUpnpService::test_state_variables_actions", "tests/test_upnp_client.py::TestUpnpService::test_call_action", "tests/test_upnp_client.py::TestUpnpEventHandler::test_subscribe", "tests/test_upnp_client.py::TestUpnpEventHandler::test_subscribe_renew", "tests/test_upnp_client.py::TestUpnpEventHandler::test_unsubscribe", "tests/test_upnp_client.py::TestUpnpEventHandler::test_on_notify_upnp_event" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-04-15 20:25:45+00:00
apache-2.0
720
Stewori__pytypes-98
diff --git a/pytypes/typechecker.py b/pytypes/typechecker.py index a0cd92b..b6b4342 100644 --- a/pytypes/typechecker.py +++ b/pytypes/typechecker.py @@ -964,15 +964,19 @@ def typechecked_module(md, force_recursive = False): """ if not pytypes.checking_enabled: return md + # Save input to return original string if input was a string. + md_arg = md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: - return md + return md_arg elif md in _pending_modules: # if import is pending, we just store this call for later _pending_modules[md].append(lambda t: typechecked_module(t, True)) - return md + return md_arg + else: + raise KeyError('Found no module {!r} to typecheck'.format(md)) assert(ismodule(md)) if md.__name__ in _pending_modules: # if import is pending, we just store this call for later @@ -981,7 +985,7 @@ def typechecked_module(md, force_recursive = False): # todo: Issue warning here that not the whole module might be covered yet if md.__name__ in _fully_typechecked_modules and \ _fully_typechecked_modules[md.__name__] == len(md.__dict__): - return md + return md_arg # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. @@ -997,7 +1001,7 @@ def typechecked_module(md, force_recursive = False): typechecked_class(memb, force_recursive, force_recursive) if not md.__name__ in _pending_modules: _fully_typechecked_modules[md.__name__] = len(md.__dict__) - return md + return md_arg def typechecked(memb):
Stewori/pytypes
befcedde8cea9b189c643f905c2b7ad180f27f8e
diff --git a/tests/test_typechecker.py b/tests/test_typechecker.py index fc4483d..60546b5 100644 --- a/tests/test_typechecker.py +++ b/tests/test_typechecker.py @@ -2651,8 +2651,14 @@ class TestTypecheck_module(unittest.TestCase): def test_function_py2(self): from testhelpers import modulewide_typecheck_testhelper_py2 as mth self.assertEqual(mth.testfunc(3, 2.5, 'abcd'), (9, 7.5)) + with self.assertRaises(KeyError): + pytypes.typechecked_module('nonexistent123') self.assertEqual(mth.testfunc(3, 2.5, 7), (9, 7.5)) # would normally fail - pytypes.typechecked_module(mth) + module_name = 'testhelpers.modulewide_typecheck_testhelper_py2' + returned_mth = pytypes.typechecked_module(module_name) + self.assertEqual(returned_mth, module_name) + returned_mth = pytypes.typechecked_module(mth) + self.assertEqual(returned_mth, mth) self.assertEqual(mth.testfunc(3, 2.5, 'abcd'), (9, 7.5)) self.assertRaises(InputTypeError, lambda: mth.testfunc(3, 2.5, 7)) @@ -2662,7 +2668,8 @@ class TestTypecheck_module(unittest.TestCase): from testhelpers import modulewide_typecheck_testhelper as mth self.assertEqual(mth.testfunc(3, 2.5, 'abcd'), (9, 7.5)) self.assertEqual(mth.testfunc(3, 2.5, 7), (9, 7.5)) # would normally fail - pytypes.typechecked_module(mth) + returned_mth = pytypes.typechecked_module(mth) + self.assertEqual(returned_mth, mth) self.assertEqual(mth.testfunc(3, 2.5, 'abcd'), (9, 7.5)) self.assertRaises(InputTypeError, lambda: mth.testfunc(3, 2.5, 7))
typechecked(string) should have more consistent return type Currently if you call `typechecked` on a string module name, it has case-by-case behavior to sometimes return the original string and sometimes return the resolved module: ```python typechecked('requests') → <module 'requests'> typechecked('requests') → 'requests' ``` Could we simplify to make it unconditionally return the value that was passed in, str→str, module→module, class→class, etc?
0.0
befcedde8cea9b189c643f905c2b7ad180f27f8e
[ "tests/test_typechecker.py::TestTypecheck_module::test_function_py2" ]
[ "tests/test_typechecker.py::testClass2_defTimeCheck", "tests/test_typechecker.py::testClass2_defTimeCheck2", "tests/test_typechecker.py::testClass2_defTimeCheck3", "tests/test_typechecker.py::testClass2_defTimeCheck4", "tests/test_typechecker.py::testClass3_defTimeCheck", "tests/test_typechecker.py::testClass2_defTimeCheck_init_ov", "tests/test_typechecker.py::testfunc_check_argument_types_empty", "tests/test_typechecker.py::testfunc_varargs1", "tests/test_typechecker.py::testfunc_varargs4", "tests/test_typechecker.py::testfunc_varargs_ca1", "tests/test_typechecker.py::testfunc_varargs_ca4", "tests/test_typechecker.py::TestTypecheck::test_abstract_override", "tests/test_typechecker.py::TestTypecheck::test_annotations_from_typestring", "tests/test_typechecker.py::TestTypecheck::test_callable", "tests/test_typechecker.py::TestTypecheck::test_classmethod", "tests/test_typechecker.py::TestTypecheck::test_custom_annotations", "tests/test_typechecker.py::TestTypecheck::test_custom_generic", "tests/test_typechecker.py::TestTypecheck::test_defaults_inferred_types", "tests/test_typechecker.py::TestTypecheck::test_function", "tests/test_typechecker.py::TestTypecheck::test_get_types", "tests/test_typechecker.py::TestTypecheck::test_method", "tests/test_typechecker.py::TestTypecheck::test_method_forward", "tests/test_typechecker.py::TestTypecheck::test_parent_typecheck_no_override", "tests/test_typechecker.py::TestTypecheck::test_property", "tests/test_typechecker.py::TestTypecheck::test_staticmethod", "tests/test_typechecker.py::TestTypecheck::test_typecheck_parent_type", "tests/test_typechecker.py::TestTypecheck::test_typestring_varargs_syntax", "tests/test_typechecker.py::TestTypecheck::test_typevar_class", "tests/test_typechecker.py::TestTypecheck::test_typevar_collision", "tests/test_typechecker.py::TestTypecheck::test_various", "tests/test_typechecker.py::TestTypecheck_class::test_classmethod", "tests/test_typechecker.py::TestTypecheck_class::test_method", "tests/test_typechecker.py::TestTypecheck_class::test_staticmethod", "tests/test_typechecker.py::TestTypecheck_module::test_function_py3", "tests/test_typechecker.py::Test_check_argument_types::test_function", "tests/test_typechecker.py::Test_check_argument_types::test_inner_class", "tests/test_typechecker.py::Test_check_argument_types::test_inner_method", "tests/test_typechecker.py::Test_check_argument_types::test_methods", "tests/test_typechecker.py::TestOverride::test_auto_override", "tests/test_typechecker.py::TestOverride::test_override", "tests/test_typechecker.py::TestOverride::test_override_at_definition_time", "tests/test_typechecker.py::TestOverride::test_override_at_definition_time_with_forward_decl", "tests/test_typechecker.py::TestOverride::test_override_diamond", "tests/test_typechecker.py::TestOverride::test_override_typecheck", "tests/test_typechecker.py::TestOverride::test_override_typecheck_class", "tests/test_typechecker.py::TestOverride::test_override_vararg", "tests/test_typechecker.py::TestStubfile::test_annotations_from_stubfile_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_annotations_from_stubfile_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_callable_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_custom_generic_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_defaults_inferred_types_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_defaults_inferred_types_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_override_diamond_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_override_diamond_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_property_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_property_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_typecheck_parent_type_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_typecheck_parent_type_plain_3_5_stub", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_abstract_override_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_callable_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_classmethod_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_custom_generic_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_inferred_types", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_with_missing_annotations_class", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_with_missing_annotations_plain", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_with_missing_annotations_property", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_with_missing_annotations_static", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_function_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_get_types_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_method_forward_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_method_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_parent_typecheck_no_override_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_property", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_staticmethod_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_typecheck_parent_type", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_various_py3", "tests/test_typechecker.py::TestOverride_Python3_5::test_auto_override", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_at_definition_time", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_at_definition_time_with_forward_decl", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_diamond", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_py3", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_typecheck", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_vararg", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_function", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_inner_class", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_inner_method", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_methods", "tests/test_typechecker.py::Test_utils::test_Generator_is_of_type", "tests/test_typechecker.py::Test_utils::test_bound_typevars_readonly", "tests/test_typechecker.py::Test_utils::test_empty_values", "tests/test_typechecker.py::Test_utils::test_forward_declaration_infinite_recursion", "tests/test_typechecker.py::Test_utils::test_has_type_hints_on_slot_wrapper", "tests/test_typechecker.py::Test_utils::test_resolve_fw_decl", "tests/test_typechecker.py::Test_utils::test_tuple_ellipsis", "tests/test_typechecker.py::Test_utils::test_tuple_ellipsis_check", "tests/test_typechecker.py::Test_utils::test_type_bases", "tests/test_typechecker.py::Test_combine_argtype::test_exceptions", "tests/test_typechecker.py::Test_combine_argtype::test_function", "tests/test_typechecker.py::Test_agent::test_function_agent", "tests/test_typechecker.py::Test_agent::test_init_agent_return_None", "tests/test_typechecker.py::Test_agent::test_method_agent_return", "tests/test_typechecker.py::Test_agent_Python3_5::test_function_agent", "tests/test_typechecker.py::Test_agent_Python3_5::test_init_agent_return_None", "tests/test_typechecker.py::Test_agent_Python3_5::test_method_agent_return" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-08-06 06:08:27+00:00
apache-2.0
721
StingraySoftware__stingray-814
diff --git a/docs/changes/814.bugfix.rst b/docs/changes/814.bugfix.rst new file mode 100644 index 00000000..d90606d6 --- /dev/null +++ b/docs/changes/814.bugfix.rst @@ -0,0 +1,1 @@ +Fix issue when setting a property from a FITS file read diff --git a/stingray/base.py b/stingray/base.py index 717630d7..a70fed44 100644 --- a/stingray/base.py +++ b/stingray/base.py @@ -421,9 +421,25 @@ class StingrayObject(object): continue setattr(cls, attr.lower(), np.array(ts[attr])) + attributes_left_unchanged = [] for key, val in ts.meta.items(): - setattr(cls, key.lower(), val) + if ( + isinstance(getattr(cls.__class__, key.lower(), None), property) + and getattr(cls.__class__, key.lower(), None).fset is None + ): + attributes_left_unchanged.append(key) + continue + setattr(cls, key.lower(), val) + if len(attributes_left_unchanged) > 0: + # Only warn once, if multiple properties are affected. + attrs = ",".join(attributes_left_unchanged) + warnings.warn( + f"The input table contains protected attribute(s) of StingrayTimeseries: {attrs}. " + "These values are set internally by the class, and cannot be overwritten. " + "This issue is common when reading from FITS files using `fmt='fits'`." + " If this is the case, please consider using `fmt='ogip'` instead." + ) return cls def to_xarray(self) -> Dataset:
StingraySoftware/stingray
e4e477caff85074fdf5acd93124f34e6b85d811a
diff --git a/stingray/tests/test_base.py b/stingray/tests/test_base.py index cb3c7143..37128486 100644 --- a/stingray/tests/test_base.py +++ b/stingray/tests/test_base.py @@ -4,6 +4,7 @@ import copy import pytest import numpy as np import matplotlib.pyplot as plt +from astropy.table import Table from stingray.base import StingrayObject, StingrayTimeseries _HAS_XARRAY = importlib.util.find_spec("xarray") is not None @@ -879,6 +880,14 @@ class TestStingrayTimeseries: new_so = StingrayTimeseries.from_astropy_table(ts) assert so == new_so + def test_setting_property_fails(self): + ts = Table(dict(time=[1, 2, 3])) + ts.meta["exposure"] = 10 + with pytest.warns( + UserWarning, match=r".*protected attribute\(s\) of StingrayTimeseries: exposure" + ): + StingrayTimeseries.from_astropy_table(ts) + @pytest.mark.parametrize("highprec", [True, False]) def test_astropy_ts_roundtrip(self, highprec): if highprec:
Error reading the event file Hi Stingray Development Team, When analyzing a NICER X-ray data, I got an error when reading the event file: File /data/software/anaconda/envs/tugbabztp/lib/python3.12/site-packages/stingray/events.py:625, in EventList.read(cls, filename, fmt, **kwargs) 622 setattr(evt, key.lower(), evtdata.additional_data[key]) 623 return evt --> 625 return super().read(filename=filename, fmt=fmt) File /data/software/anaconda/envs/tugbabztp/lib/python3.12/site-packages/stingray/base.py:647, in StingrayObject.read(cls, filename, fmt) 643 ts[col_strip] += new_value 645 ts.remove_column(col) --> 647 return cls.from_astropy_table(ts) File /data/software/anaconda/envs/tugbabztp/lib/python3.12/site-packages/stingray/base.py:425, in StingrayObject.from_astropy_table(cls, ts) 422 setattr(cls, attr.lower(), np.array(ts[attr])) 424 for key, val in ts.meta.items(): --> 425 setattr(cls, key.lower(), val) 427 return cls AttributeError: property 'exposure' of 'EventList' object has no setter but I realized that I only get this error when we use the most recent version distributed by conda which I installed just a few days ago (stingray version: 2.0.0). The same code works just fine with the previous version (stingray version: 1.1.1) again installed earlier from conda. Thanks !
0.0
e4e477caff85074fdf5acd93124f34e6b85d811a
[ "stingray/tests/test_base.py::TestStingrayTimeseries::test_setting_property_fails" ]
[ "stingray/tests/test_base.py::TestStingrayObject::test_print", "stingray/tests/test_base.py::TestStingrayObject::test_preliminary", "stingray/tests/test_base.py::TestStingrayObject::test_instantiate_without_main_array_attr", "stingray/tests/test_base.py::TestStingrayObject::test_equality", "stingray/tests/test_base.py::TestStingrayObject::test_different_array_attributes", "stingray/tests/test_base.py::TestStingrayObject::test_different_meta_attributes", "stingray/tests/test_base.py::TestStingrayObject::test_apply_mask[True]", "stingray/tests/test_base.py::TestStingrayObject::test_apply_mask[False]", "stingray/tests/test_base.py::TestStingrayObject::test_partial_apply_mask[True]", "stingray/tests/test_base.py::TestStingrayObject::test_partial_apply_mask[False]", "stingray/tests/test_base.py::TestStingrayObject::test_operations", "stingray/tests/test_base.py::TestStingrayObject::test_inplace_add", "stingray/tests/test_base.py::TestStingrayObject::test_inplace_sub", "stingray/tests/test_base.py::TestStingrayObject::test_inplace_add_with_method", "stingray/tests/test_base.py::TestStingrayObject::test_inplace_sub_with_method", "stingray/tests/test_base.py::TestStingrayObject::test_failed_operations", "stingray/tests/test_base.py::TestStingrayObject::test_len", "stingray/tests/test_base.py::TestStingrayObject::test_slice", "stingray/tests/test_base.py::TestStingrayObject::test_side_effects", "stingray/tests/test_base.py::TestStingrayObject::test_astropy_roundtrip", "stingray/tests/test_base.py::TestStingrayObject::test_astropy_roundtrip_empty", "stingray/tests/test_base.py::TestStingrayObject::test_file_roundtrip_fits", "stingray/tests/test_base.py::TestStingrayObject::test_file_roundtrip[ascii]", "stingray/tests/test_base.py::TestStingrayObject::test_file_roundtrip[ascii.ecsv]", "stingray/tests/test_base.py::TestStingrayObject::test_file_roundtrip_pickle", "stingray/tests/test_base.py::TestStingrayTimeseries::test_print", "stingray/tests/test_base.py::TestStingrayTimeseries::test_invalid_instantiation", "stingray/tests/test_base.py::TestStingrayTimeseries::test_mask_is_none_then_isnt_no_gti", "stingray/tests/test_base.py::TestStingrayTimeseries::test_apply_mask", "stingray/tests/test_base.py::TestStingrayTimeseries::test_comparison", "stingray/tests/test_base.py::TestStingrayTimeseries::test_zero_out_timeseries", "stingray/tests/test_base.py::TestStingrayTimeseries::test_n_property", "stingray/tests/test_base.py::TestStingrayTimeseries::test_what_is_array_and_what_is_not", "stingray/tests/test_base.py::TestStingrayTimeseries::test_operations", "stingray/tests/test_base.py::TestStingrayTimeseries::test_operations_different_mjdref", "stingray/tests/test_base.py::TestStingrayTimeseries::test_operation_with_diff_gti", "stingray/tests/test_base.py::TestStingrayTimeseries::test_len", "stingray/tests/test_base.py::TestStingrayTimeseries::test_slice", "stingray/tests/test_base.py::TestStingrayTimeseries::test_apply_gti[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_apply_gti[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_split_ts_by_gtis", "stingray/tests/test_base.py::TestStingrayTimeseries::test_truncate", "stingray/tests/test_base.py::TestStingrayTimeseries::test_truncate_not_str", "stingray/tests/test_base.py::TestStingrayTimeseries::test_truncate_invalid", "stingray/tests/test_base.py::TestStingrayTimeseries::test_concatenate", "stingray/tests/test_base.py::TestStingrayTimeseries::test_concatenate_invalid", "stingray/tests/test_base.py::TestStingrayTimeseries::test_concatenate_gtis_overlap", "stingray/tests/test_base.py::TestStingrayTimeseries::test_concatenate_diff_mjdref", "stingray/tests/test_base.py::TestStingrayTimeseries::test_rebin", "stingray/tests/test_base.py::TestStingrayTimeseries::test_rebin_irregular", "stingray/tests/test_base.py::TestStingrayTimeseries::test_rebin_no_good_gtis", "stingray/tests/test_base.py::TestStingrayTimeseries::test_rebin_no_input", "stingray/tests/test_base.py::TestStingrayTimeseries::test_rebin_less_than_dt", "stingray/tests/test_base.py::TestStingrayTimeseries::test_sort", "stingray/tests/test_base.py::TestStingrayTimeseries::test_astropy_roundtrip[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_astropy_roundtrip[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_astropy_ts_roundtrip[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_astropy_ts_roundtrip[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip_fits[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip_fits[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip[True-ascii]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip[True-ascii.ecsv]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip[False-ascii]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip[False-ascii.ecsv]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip_pickle[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_file_roundtrip_pickle[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_shift_time[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_shift_time[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_change_mjdref[True]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_change_mjdref[False]", "stingray/tests/test_base.py::TestStingrayTimeseries::test_plot_simple", "stingray/tests/test_base.py::TestStingrayTimeseries::test_plot_default_filename", "stingray/tests/test_base.py::TestStingrayTimeseries::test_plot_custom_filename", "stingray/tests/test_base.py::TestStingrayTimeseriesSubclass::test_print", "stingray/tests/test_base.py::TestStingrayTimeseriesSubclass::test_astropy_roundtrip", "stingray/tests/test_base.py::TestStingrayTimeseriesSubclass::test_astropy_ts_roundtrip", "stingray/tests/test_base.py::TestStingrayTimeseriesSubclass::test_shift_time", "stingray/tests/test_base.py::TestStingrayTimeseriesSubclass::test_change_mjdref", "stingray/tests/test_base.py::TestJoinEvents::test_join_without_times_simulated", "stingray/tests/test_base.py::TestJoinEvents::test_join_empty_lists", "stingray/tests/test_base.py::TestJoinEvents::test_join_different_dt", "stingray/tests/test_base.py::TestJoinEvents::test_join_different_instr", "stingray/tests/test_base.py::TestJoinEvents::test_join_different_meta_attribute", "stingray/tests/test_base.py::TestJoinEvents::test_join_without_energy", "stingray/tests/test_base.py::TestJoinEvents::test_join_without_pi", "stingray/tests/test_base.py::TestJoinEvents::test_join_with_arbitrary_attribute", "stingray/tests/test_base.py::TestJoinEvents::test_join_with_gti_none", "stingray/tests/test_base.py::TestJoinEvents::test_non_overlapping_join_infer", "stingray/tests/test_base.py::TestJoinEvents::test_overlapping_join_infer", "stingray/tests/test_base.py::TestJoinEvents::test_overlapping_join_change_mjdref", "stingray/tests/test_base.py::TestJoinEvents::test_multiple_join", "stingray/tests/test_base.py::TestJoinEvents::test_join_ignore_attr", "stingray/tests/test_base.py::TestFillBTI::test_no_btis_returns_copy", "stingray/tests/test_base.py::TestFillBTI::test_event_like", "stingray/tests/test_base.py::TestFillBTI::test_no_counts_in_buffer", "stingray/tests/test_base.py::TestFillBTI::test_lc_like", "stingray/tests/test_base.py::TestFillBTI::test_ignore_attrs_ev_like", "stingray/tests/test_base.py::TestFillBTI::test_ignore_attrs_lc_like", "stingray/tests/test_base.py::TestFillBTI::test_forcing_non_uniform", "stingray/tests/test_base.py::TestFillBTI::test_forcing_uniform", "stingray/tests/test_base.py::TestFillBTI::test_bti_close_to_edge_event_like", "stingray/tests/test_base.py::TestFillBTI::test_bti_close_to_edge_lc_like", "stingray/tests/test_base.py::TestAnalyzeChunks::test_invalid_input", "stingray/tests/test_base.py::TestAnalyzeChunks::test_no_total_counts", "stingray/tests/test_base.py::TestAnalyzeChunks::test_estimate_segment_size", "stingray/tests/test_base.py::TestAnalyzeChunks::test_estimate_segment_size_more_bins", "stingray/tests/test_base.py::TestAnalyzeChunks::test_estimate_segment_size_lower_counts", "stingray/tests/test_base.py::TestAnalyzeChunks::test_estimate_segment_size_lower_dt", "stingray/tests/test_base.py::TestAnalyzeChunks::test_analyze_segments_bad_intv", "stingray/tests/test_base.py::TestAnalyzeChunks::test_analyze_segments_by_gti" ]
{ "failed_lite_validators": [ "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2024-03-27 12:55:47+00:00
mit
722
Stonesjtu__pytorch_memlab-25
diff --git a/.travis.yml b/.travis.yml index 4c040a2..c36f90a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,18 +14,22 @@ matrix: env: IPYTHON_VERSION='7' PANDAS_VERSION='1' + - python: '3.8' + env: + IPYTHON_VERSION='7' + PANDAS_VERSION='1' install: - pip install IPython==$IPYTHON_VERSION - pip install pandas==$PANDAS_VERSION -- python setup.py install -- pip install -r requirements.txt +- pip install .[test] script: - python -c 'import pytorch_memlab' +- pytest test/test_mem_reporter.py deploy: provider: pypi user: yoursky on: tags: true - python: 3.7 + python: 3.8 password: secure: P0hSqy9eGKVG/0Cu8yE1+I+V0gIUbc+B7srJTsyJPC4+COv7BqIrt1NG+3+vWdocJLuYiTbf3zpUBozdvHH0XDV8Ki0rjsQOm607Fe+d30JCaL3sXLJOe8qwbizx9nmTS04AORc7nyzn4Tc3H10zDfwxL5uk73H6mwaoMlh2v2sizB8G6Ce4kH9JXWarKahKPPSdt2u0o533Bm5/rfNzxLifGmG7o2OYIXmUbeC54f4nhBCihtc+sjKR54qfopH/Gnpl1fnFK2Q5aMOM2yUj7mrjNLgDeAECigKGZpn/uuYyy/dSJKvPFoHFP52HS6x+9/aVUUgwEhqyYZ3tFJgkyeLPVnuP5Pv7wQyZXbIBchPwljswgjxI/+8ANRM6WMUhBbnOUQPPd/6AmW6xdaJf2l0461jGqhxAUGRKpn/odFIEly3TcizIzHjkOqPbS4xkKgN7s40ai8ZFLIUXmbqa7r/dScdu7qjvRYIn+obTCIq0lR3gTZLNfHHBCYFOcLD0anlDakONaiY4++xzDw88ancLQhN5L5rsQge4QNdZS8s88gbPtei+3DfnGsUnYWWplAHdxJ+A8/CrtBrtM18E3mOuwSdKbCwd54YmL9E+KcRcL/WRpedWjNybiBCDvRoO0iw3+2EnkrTLpsuTtiXAu+oe2h1XoMyYbeVjaVVsN44= diff --git a/pytorch_memlab/line_profiler/line_profiler.py b/pytorch_memlab/line_profiler/line_profiler.py index 04c1fa2..7615ef1 100644 --- a/pytorch_memlab/line_profiler/line_profiler.py +++ b/pytorch_memlab/line_profiler/line_profiler.py @@ -6,7 +6,7 @@ import torch from .line_records import LineRecords # Seaborn's `muted` color cycle -DEFAULT_COLUMNS = ['active_bytes.all.peak', 'reserved_bytes.all.peak'] +DEFAULT_COLUMNS = ('active_bytes.all.peak', 'reserved_bytes.all.peak') class LineProfiler: @@ -88,8 +88,9 @@ class LineProfiler: try: torch.cuda.empty_cache() self._reset_cuda_stats() - except AssertionError as e: - print('Could not reset CUDA stats and cache: ' + str(e)) + # Pytorch-1.7.0 raises AttributeError while <1.6.0 raises AssertionError + except (AssertionError, AttributeError) as error: + print('Could not reset CUDA stats and cache: ' + str(error)) self.register_callback() diff --git a/pytorch_memlab/mem_reporter.py b/pytorch_memlab/mem_reporter.py index 6aff270..c2f3800 100644 --- a/pytorch_memlab/mem_reporter.py +++ b/pytorch_memlab/mem_reporter.py @@ -27,13 +27,15 @@ class MemReporter(): self.device_tensor_stat = {} # to numbering the unknown tensors self.name_idx = 0 + + tensor_names = defaultdict(list) if model is not None: assert isinstance(model, torch.nn.Module) # for model with tying weight, multiple parameters may share # the same underlying tensor - tensor_names = defaultdict(list) for name, param in model.named_parameters(): tensor_names[param].append(name) + for param, name in tensor_names.items(): self.tensor_name[id(param)] = '+'.join(name)
Stonesjtu/pytorch_memlab
03c95654cc5729276c94beb62f8af5a0711f8d67
diff --git a/test/test_mem_reporter.py b/test/test_mem_reporter.py index 971e8f1..927d7fe 100644 --- a/test/test_mem_reporter.py +++ b/test/test_mem_reporter.py @@ -7,8 +7,8 @@ import pytest concentrate_mode = False def test_reporter(): - linear = torch.nn.Linear(1024, 1024).cuda() - inp = torch.Tensor(512, 1024).cuda() + linear = torch.nn.Linear(1024, 1024) + inp = torch.Tensor(512, 1024) reporter = MemReporter(linear) out = linear(inp*(inp+3)).mean() @@ -17,16 +17,27 @@ def test_reporter(): reporter.report() +def test_reporter_without_model(): + linear = torch.nn.Linear(1024, 1024) + inp = torch.Tensor(512, 1024) + reporter = MemReporter() + + out = linear(inp*(inp+3)).mean() + reporter.report() + out.backward() + + reporter.report() + @pytest.mark.skipif(concentrate_mode, reason='concentrate') def test_reporter_tie_weight(): - linear = torch.nn.Linear(1024, 1024).cuda() - linear_2 = torch.nn.Linear(1024, 1024).cuda() + linear = torch.nn.Linear(1024, 1024) + linear_2 = torch.nn.Linear(1024, 1024) linear_2.weight = linear.weight container = torch.nn.Sequential( linear, linear_2 ) reporter = MemReporter(container) - inp = torch.Tensor(512, 1024).cuda() + inp = torch.Tensor(512, 1024) out = container(inp).mean() out.backward() @@ -34,6 +45,7 @@ def test_reporter_tie_weight(): reporter = MemReporter(container) reporter.report() [email protected](not torch.cuda.is_available(), reason='no CUDA') @pytest.mark.skipif(concentrate_mode, reason='concentrate') def test_reporter_LSTM(): lstm = torch.nn.LSTM(256, 256, num_layers=1).cuda() @@ -45,6 +57,7 @@ def test_reporter_LSTM(): reporter = MemReporter(lstm) reporter.report() [email protected](not torch.cuda.is_available(), reason='no CUDA') @pytest.mark.skipif(concentrate_mode, reason='concentrate') def test_reporter_device(): lstm_cpu = torch.nn.LSTM(256, 256)
Variable 'tensor_names' referenced before assignment https://github.com/Stonesjtu/pytorch_memlab/blob/ec9a72fc302981ddc3ee56d6e16694610d646c36/pytorch_memlab/mem_reporter.py#L37 The variable tensor_names is referenced before assignment if no model is passed into the MemReporter. Need to move it into the above if statement.
0.0
03c95654cc5729276c94beb62f8af5a0711f8d67
[ "test/test_mem_reporter.py::test_reporter_without_model" ]
[ "test/test_mem_reporter.py::test_reporter", "test/test_mem_reporter.py::test_reporter_tie_weight", "test/test_mem_reporter.py::test_reporter_LSTM", "test/test_mem_reporter.py::test_reporter_device" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-01 08:59:17+00:00
mit
723
Stranger6667__pyanyapi-42
diff --git a/.travis.yml b/.travis.yml index 1975b26..b7b5b14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,17 +1,30 @@ language: python python: - 3.5 -env: - - TOX_ENV=py26 - - TOX_ENV=py27 - - TOX_ENV=py32 - - TOX_ENV=py33 - - TOX_ENV=py34 - - TOX_ENV=py35 - - TOX_ENV=pypy - - TOX_ENV=pypy3 - - JYTHON=true +matrix: + fast_finish: true + include: + - python: 3.5 + env: TOX_ENV=py35 + - python: 3.4 + env: TOX_ENV=py34 + - python: 3.3 + env: TOX_ENV=py33 + - python: 3.2 + env: TOX_ENV=py32 + - python: 2.7 + env: TOX_ENV=py27 + - python: 2.6 + env: TOX_ENV=py26 + - python: pypy + env: TOX_ENV=pypy + - python: pypy3 + env: TOX_ENV=pypy3 + - python: 3.5 + env: $JYTHON=true install: + - if [ $TOX_ENV = "py32" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi + - if [ $TOX_ENV = "pypy3" ]; then travis_retry pip install "virtualenv<14.0.0" "tox<1.8.0"; fi - if [ -z "$JYTHON" ]; then pip install codecov; fi - if [ "$TOX_ENV" ]; then travis_retry pip install "virtualenv<14.0.0" tox; fi before_install: @@ -22,4 +35,4 @@ script: - if [ "$JYTHON" ]; then travis_retry jython setup.py test; fi - if [ "$TOX_ENV" ]; then tox -e $TOX_ENV; fi after_success: - - codecov \ No newline at end of file + - codecov diff --git a/pyanyapi/interfaces.py b/pyanyapi/interfaces.py index 698c637..c0914b2 100644 --- a/pyanyapi/interfaces.py +++ b/pyanyapi/interfaces.py @@ -274,7 +274,7 @@ class YAMLInterface(DictInterface): def perform_parsing(self): try: - return yaml.load(self.content) + return yaml.safe_load(self.content) except yaml.error.YAMLError: raise ResponseParseError(self._error_message, self.content)
Stranger6667/pyanyapi
aebee636ad26f387850a6c8ab820ce4aac3f9adb
diff --git a/tests/test_parsers.py b/tests/test_parsers.py index 38223e2..4958b21 100644 --- a/tests/test_parsers.py +++ b/tests/test_parsers.py @@ -63,6 +63,15 @@ def test_yaml_parser_error(): parsed.test +def test_yaml_parser_vulnerability(): + """ + In case of usage of yaml.load `test` value will be equal to 0. + """ + parsed = YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["exit 0"]') + with pytest.raises(ResponseParseError): + parsed.test + + @lxml_is_supported @pytest.mark.parametrize( 'settings', (
YAMLParser method is vulnerable from pyanyapi import YAMLParser YAMLParser({'test': 'container > test'}).parse('!!python/object/apply:os.system ["calc.exe"]').test Hi, there is a vulnerability in YAMLParser method in Interfaces.py, please see PoC above. It can execute arbitrary python commands resulting in command execution.
0.0
aebee636ad26f387850a6c8ab820ce4aac3f9adb
[ "tests/test_parsers.py::test_yaml_parser_error", "tests/test_parsers.py::test_yaml_parser_vulnerability", "tests/test_parsers.py::test_yaml_parse" ]
[ "tests/test_parsers.py::test_xml_objectify_parser", "tests/test_parsers.py::test_xml_objectify_parser_error", "tests/test_parsers.py::test_xml_parser_error", "tests/test_parsers.py::test_xml_parsed[settings0]", "tests/test_parsers.py::test_xml_parsed[settings1]", "tests/test_parsers.py::test_xml_simple_settings", "tests/test_parsers.py::test_json_parsed", "tests/test_parsers.py::test_multiple_parser_join", "tests/test_parsers.py::test_multiply_parsers_declaration", "tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-test-value]", "tests/test_parsers.py::test_empty_values[{\"container\":{\"test\":\"value\"}}-second-None]", "tests/test_parsers.py::test_empty_values[{\"container\":{\"fail\":[1]}}-second-None]", "tests/test_parsers.py::test_empty_values[{\"container\":[[1],[],[3]]}-third-expected3]", "tests/test_parsers.py::test_empty_values[{\"container\":null}-null-None]", "tests/test_parsers.py::test_empty_values[{\"container\":[1,2]}-test-1,2]", "tests/test_parsers.py::test_attributes", "tests/test_parsers.py::test_efficient_parsing", "tests/test_parsers.py::test_simple_config_xml_parser", "tests/test_parsers.py::test_simple_config_json_parser", "tests/test_parsers.py::test_settings_inheritance", "tests/test_parsers.py::test_complex_config", "tests/test_parsers.py::test_json_parse", "tests/test_parsers.py::test_json_value_error_parse", "tests/test_parsers.py::test_regexp_parse", "tests/test_parsers.py::test_ajax_parser", "tests/test_parsers.py::test_ajax_parser_cache", "tests/test_parsers.py::test_ajax_parser_invalid_settings", "tests/test_parsers.py::test_parse_memoization", "tests/test_parsers.py::test_regexp_settings", "tests/test_parsers.py::test_parse_all", "tests/test_parsers.py::test_parse_all_combined_parser", "tests/test_parsers.py::test_parse_csv", "tests/test_parsers.py::test_parse_csv_custom_delimiter", "tests/test_parsers.py::test_csv_parser_error", "tests/test_parsers.py::test_children[SubParser]", "tests/test_parsers.py::test_children[sub_parser1]", "tests/test_parsers.py::TestIndexOfParser::test_default[foo-b\\xe1r]", "tests/test_parsers.py::TestIndexOfParser::test_default[foo-b\\xc3\\xa1r]", "tests/test_parsers.py::TestIndexOfParser::test_parsing_error[has_bar]", "tests/test_parsers.py::TestIndexOfParser::test_parsing_error[has_baz]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-11-07 09:56:44+00:00
mit
724
Stratoscale__skipper-164
diff --git a/.gitignore b/.gitignore index 089cb66..281342a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +.vscode +**__pycache__** +**.pytest_cache** *.egg-info *.pyc .cache diff --git a/skipper/git.py b/skipper/git.py index daa02c6..5098114 100644 --- a/skipper/git.py +++ b/skipper/git.py @@ -16,7 +16,7 @@ def get_hash(short=False): if uncommitted_changes(): logging.warning("*** Uncommitted changes present - Build container version might be outdated ***") - return subprocess.check_output(git_command).strip() + return subprocess.check_output(git_command).strip().decode('utf-8') def uncommitted_changes():
Stratoscale/skipper
26e65ac0956d19f4f4a73a95d9547039c746a6b2
diff --git a/tests/test_cli.py b/tests/test_cli.py index 63011ed..9ac3b6b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1680,7 +1680,7 @@ class TestCLI(unittest.TestCase): @mock.patch('builtins.open', mock.MagicMock(create=True)) @mock.patch('os.path.exists', mock.MagicMock(autospec=True, return_value=True)) @mock.patch('yaml.safe_load', mock.MagicMock(autospec=True, return_value=SKIPPER_CONF_WITH_GIT_REV)) - @mock.patch('subprocess.check_output', mock.MagicMock(autospec=True, return_value='1234567\n')) + @mock.patch('subprocess.check_output', mock.MagicMock(autospec=True, return_value=b'1234567\n')) @mock.patch('skipper.git.uncommitted_changes', mock.MagicMock(return_value=True)) @mock.patch('skipper.runner.run', autospec=True) def test_run_with_config_including_git_revision_with_uncommitted_changes(self, skipper_runner_run_mock): @@ -1701,7 +1701,7 @@ class TestCLI(unittest.TestCase): @mock.patch('builtins.open', mock.MagicMock(create=True)) @mock.patch('os.path.exists', mock.MagicMock(autospec=True, return_value=True)) @mock.patch('yaml.safe_load', mock.MagicMock(autospec=True, return_value=SKIPPER_CONF_WITH_GIT_REV)) - @mock.patch('subprocess.check_output', mock.MagicMock(autospec=True, return_value='1234567\n')) + @mock.patch('subprocess.check_output', mock.MagicMock(autospec=True, return_value=b'1234567\n')) @mock.patch('skipper.git.uncommitted_changes', mock.MagicMock(return_value=False)) @mock.patch('skipper.runner.run', autospec=True) def test_run_with_config_including_git_revision_without_uncommitted_changes(self, skipper_runner_run_mock): diff --git a/tests/test_git.py b/tests/test_git.py index a7c4703..2eed711 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -3,8 +3,8 @@ import mock from skipper import git -GIT_HASH_FULL = '00efe974e3cf18c3493f110f5aeda04ff78b125f' -GIT_HASH_SHORT = '00efe97' +GIT_HASH_FULL = b'00efe974e3cf18c3493f110f5aeda04ff78b125f' +GIT_HASH_SHORT = b'00efe97' class TestGit(unittest.TestCase): @@ -14,7 +14,7 @@ class TestGit(unittest.TestCase): git_hash = git.get_hash() exists_mock.assert_called_once_with('.git') check_output_mock.assert_called_once_with(['git', 'rev-parse', 'HEAD']) - self.assertEqual(git_hash, GIT_HASH_FULL) + self.assertEqual(git_hash, GIT_HASH_FULL.decode('utf-8')) @mock.patch('subprocess.check_output', return_value=GIT_HASH_FULL) @mock.patch('os.path.exists', return_value=True) @@ -22,7 +22,7 @@ class TestGit(unittest.TestCase): git_hash = git.get_hash(short=False) exists_mock.assert_called_once_with('.git') check_output_mock.assert_called_once_with(['git', 'rev-parse', 'HEAD']) - self.assertEqual(git_hash, GIT_HASH_FULL) + self.assertEqual(git_hash, GIT_HASH_FULL.decode('utf-8')) @mock.patch('subprocess.check_output', return_value=GIT_HASH_SHORT) @mock.patch('os.path.exists', return_value=True) @@ -30,7 +30,7 @@ class TestGit(unittest.TestCase): git_hash = git.get_hash(short=True) exists_mock.assert_called_once_with('.git') check_output_mock.assert_called_once_with(['git', 'rev-parse', '--short', 'HEAD']) - self.assertEqual(git_hash, GIT_HASH_SHORT) + self.assertEqual(git_hash, GIT_HASH_SHORT.decode('utf-8')) @mock.patch('subprocess.check_output') @mock.patch('os.path.exists', return_value=False)
can't build skipper (skipper build cmd) with v2.0.0 and v2.0.1 See $TOPIC. I get: # skipper build ```python WARNING:root:*** Uncommitted changes present - Build container version might be outdated *** [skipper] Building image: assisted-service-build INFO:skipper:Building image: assisted-service-build Traceback (most recent call last): File "/usr/local/bin/skipper", line 10, in <module> sys.exit(main()) File "/usr/local/lib/python3.9/site-packages/skipper/main.py", line 12, in main return_code = cli.cli( File "/usr/local/lib/python3.9/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/skipper/cli.py", line 117, in build fqdn_image = image + ':' + tag TypeError: can only concatenate str (not "bytes") to str ```
0.0
26e65ac0956d19f4f4a73a95d9547039c746a6b2
[ "tests/test_git.py::TestGit::test_get_hash_with_default_argument", "tests/test_git.py::TestGit::test_get_short_hash", "tests/test_git.py::TestGit::test_get_full_hash", "tests/test_cli.py::TestCLI::test_run_with_config_including_git_revision_with_uncommitted_changes", "tests/test_cli.py::TestCLI::test_run_with_config_including_git_revision_without_uncommitted_changes" ]
[ "tests/test_git.py::TestGit::test_not_in_git_project", "tests/test_cli.py::TestCLI::test_run_with_publish_port_range", "tests/test_cli.py::TestCLI::test_run_non_interactive", "tests/test_cli.py::TestCLI::test_images_with_with_remote_error", "tests/test_cli.py::TestCLI::test_push_tag_fail", "tests/test_cli.py::TestCLI::test_build_multiple_images_with_non_existing_dockerfile", "tests/test_cli.py::TestCLI::test_subcommand_without_subcommand_params", "tests/test_cli.py::TestCLI::test_cli_help", "tests/test_cli.py::TestCLI::test_run_with_defaults_and_env_from_env_file", "tests/test_cli.py::TestCLI::test_build_multiple_images", "tests/test_cli.py::TestCLI::test_run_with_existing_remote_build_container", "tests/test_cli.py::TestCLI::test_build_existing_image_with_context", "tests/test_cli.py::TestCLI::test_subcommand_help", "tests/test_cli.py::TestCLI::test_rmi_local", "tests/test_cli.py::TestCLI::test_run_with_env_list_get_from_env", "tests/test_cli.py::TestCLI::test_images_without_local_results", "tests/test_cli.py::TestCLI::test_rmi_remote", "tests/test_cli.py::TestCLI::test_push_already_in_registry_with_force", "tests/test_cli.py::TestCLI::test_build_non_existing_image", "tests/test_cli.py::TestCLI::test_build_multiple_images_with_invalid_image", "tests/test_cli.py::TestCLI::test_images_with_missing_remote_results", "tests/test_cli.py::TestCLI::test_push_to_namespace", "tests/test_cli.py::TestCLI::test_run_with_defaults_and_env_from_multiple_env_file", "tests/test_cli.py::TestCLI::test_push_rmi_fail", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file_including_interpolated_volumes", "tests/test_cli.py::TestCLI::test_images_with_remote_results_only", "tests/test_cli.py::TestCLI::test_run_with_env", "tests/test_cli.py::TestCLI::test_run_with_existing_local_build_container", "tests/test_cli.py::TestCLI::test_images_with_multiple_local_results", "tests/test_cli.py::TestCLI::test_run_with_publish_textual_port", "tests/test_cli.py::TestCLI::test_run_with_publish_out_of_range_port", "tests/test_cli.py::TestCLI::test_push", "tests/test_cli.py::TestCLI::test_build_with_defaults_from_config_file_including_containers", "tests/test_cli.py::TestCLI::test_make_with_additional_make_params", "tests/test_cli.py::TestCLI::test_version", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file_including_workdir", "tests/test_cli.py::TestCLI::test_push_fail", "tests/test_cli.py::TestCLI::test_make_without_build_container_tag_with_context", "tests/test_cli.py::TestCLI::test_run_with_env_list", "tests/test_cli.py::TestCLI::test_make_with_default_params", "tests/test_cli.py::TestCLI::test_validate_project_image", "tests/test_cli.py::TestCLI::test_build_all_images", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file_including_invalid_interploated_volumes_interpolated", "tests/test_cli.py::TestCLI::test_make_without_build_container_tag", "tests/test_cli.py::TestCLI::test_run_with_publish_textual_port_range", "tests/test_cli.py::TestCLI::test_images_with_single_local_results", "tests/test_cli.py::TestCLI::test_build_existing_image", "tests/test_cli.py::TestCLI::test_run_with_invalid_port_range", "tests/test_cli.py::TestCLI::test_run_with_env_wrong_type", "tests/test_cli.py::TestCLI::test_cli_without_params", "tests/test_cli.py::TestCLI::test_run_with_env_overriding_config_file", "tests/test_cli.py::TestCLI::test_make", "tests/test_cli.py::TestCLI::test_build_with_context_from_config_file", "tests/test_cli.py::TestCLI::test_run_with_publish_single_port", "tests/test_cli.py::TestCLI::test_run_with_non_existing_build_container", "tests/test_cli.py::TestCLI::test_shell", "tests/test_cli.py::TestCLI::test_run_non_interactive_from_environment", "tests/test_cli.py::TestCLI::test_run_without_build_container_tag_cached", "tests/test_cli.py::TestCLI::test_run_without_build_container_tag", "tests/test_cli.py::TestCLI::test_push_with_defaults_from_config_file", "tests/test_cli.py::TestCLI::test_rmi_remote_fail", "tests/test_cli.py::TestCLI::test_build_with_defaults_from_config_file", "tests/test_cli.py::TestCLI::test_run_with_non_default_net", "tests/test_cli.py::TestCLI::test_run_with_defaults_and_env_from_config_file", "tests/test_cli.py::TestCLI::test_images_with_all_results", "tests/test_cli.py::TestCLI::test_subcommand_without_global_params", "tests/test_cli.py::TestCLI::test_images_with_local_result_and_missing_remote_results", "tests/test_cli.py::TestCLI::test_run_interactive_from_environment", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file_including_workspace", "tests/test_cli.py::TestCLI::test_make_with_defaults_from_config_file", "tests/test_cli.py::TestCLI::test_run_with_publish_multiple_ports", "tests/test_cli.py::TestCLI::test_push_already_in_registry", "tests/test_cli.py::TestCLI::test_run_with_defaults_from_config_file_including_volumes" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-30 11:43:01+00:00
apache-2.0
725
SymbiFlow__FPGA-Tool-Performance-Visualization-Library-17
diff --git a/ftpvl/fetchers.py b/ftpvl/fetchers.py index d054f65..489026a 100644 --- a/ftpvl/fetchers.py +++ b/ftpvl/fetchers.py @@ -114,17 +114,47 @@ class HydraFetcher(Fetcher): raise IndexError(f"Invalid eval_num: {self.eval_num}") build_nums = evals_json["evals"][self.eval_num]["builds"] - # collect the 'meta.json' build products + # fetch build info and download 'meta.json' data = [] for build_num in build_nums: + # get build info resp = requests.get( - f"https://hydra.vtr.tools/build/{build_num}/download/1/meta.json", + f"https://hydra.vtr.tools/build/{build_num}", + headers={"Content-Type": "application/json"}, + ) + if resp.status_code != 200: + raise Exception(f"Unable to get build {build_num}, got status code {resp.status_code}.") + + decoded = None + try: + decoded = resp.json() + except json.decoder.JSONDecodeError as err: + raise Exception(f"Unable to decode build {build_num} JSON file, {str(err)}") + + # check if build was successful + if decoded.get("buildstatus") != 0: + print(f"Warning: Build {build_num} failed with non-zero exit. Skipping...") + continue + + # check if meta.json exists + meta_json_id = None + for product_id, product_desc in decoded.get("buildproducts", {}).items(): + if product_desc.get("name", "") == "meta.json": + meta_json_id = product_id + + if meta_json_id is None: + print(f"Warning: Build {build_num} does not contain meta.json file. Skipping...") + continue + + # download meta.json + resp = requests.get( + f"https://hydra.vtr.tools/build/{build_num}/download/{meta_json_id}/meta.json", headers={"Content-Type": "application/json"}, ) if resp.status_code != 200: print( "Warning:", - f"Unable to get build {build_num}. It might have failed.", + f"Unable to get build {build_num} meta.json file.", ) continue try:
SymbiFlow/FPGA-Tool-Performance-Visualization-Library
2c06f09c80ce8fda7d82176a212de10c3d2b589a
diff --git a/tests/sample_data/build.large.json b/tests/sample_data/build.large.json new file mode 100644 index 0000000..d730794 --- /dev/null +++ b/tests/sample_data/build.large.json @@ -0,0 +1,877 @@ +{ + "project": "dusty", + "buildmetrics": {}, + "job": "baselitex_vivado-yosys_arty", + "buildoutputs": { + "out": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty" + } + }, + "jobset": "fpga-tool-perf", + "nixname": "fpga-tool-perf-baselitex-vivado-yosys-arty", + "system": "x86_64-linux", + "starttime": 1593129909, + "jobsetevals": [ + 854 + ], + "priority": 100, + "drvpath": "/nix/store/s0badfaz2kccsyilsgrmjqhwbndxai3h-fpga-tool-perf-baselitex-vivado-yosys-arty.drv", + "timestamp": 1593129909, + "finished": 1, + "releasename": null, + "buildstatus": 0, + "buildproducts": { + "4": { + "sha256hash": "611fd64c8dcf9f531f6e3ca40085c6e5ece8c3e8e10ca275a8178f245383fb6c", + "sha1hash": "4d9b07cc8aa183c8f1c209e2755459ef0d67b056", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.xpr", + "subtype": "data", + "filesize": 5753, + "name": "litex-linux.xpr" + }, + "22": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux_pgm.tcl", + "subtype": "data", + "sha1hash": "079393545687002cb94afa5987a9c38a03f3baf5", + "sha256hash": "d8df2f0e60cff4c2477ecc52522c7d79589799414772aae8b39a8f986b86d87b", + "type": "file", + "name": "litex-linux_pgm.tcl", + "filesize": 3101 + }, + "75": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_route_status.rpt", + "subtype": "data", + "sha1hash": "2227f5e561493e61d5acfcae92337b2a04bf09e6", + "sha256hash": "c649a158d5349e30415bae01f5cc7ac1e804c21237c7ce399ba568ef91ff73ea", + "type": "file", + "name": "litex-linux_route_status.rpt", + "filesize": 651 + }, + "24": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.blif", + "subtype": "data", + "sha1hash": "cb553e40fe93026693b2879f7a9fa51226f550c0", + "sha256hash": "8f5297666f451a815da053f6e5d49131834096fbbbc8f2b9fa3cff20bac0fb1d", + "type": "file", + "name": "litex-linux.blif", + "filesize": 6151493 + }, + "43": { + "sha256hash": "8425442b7c369e88faeab6bf76bfcad88af955afd010b2ca22277bc6468c93aa", + "sha1hash": "b5214cfaa67e632a26065c99acf2e4925952ec88", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/vivado.jou", + "filesize": 891, + "name": "vivado.jou" + }, + "80": { + "name": "litex-linux_methodology_drc_routed.rpt", + "filesize": 98389, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_methodology_drc_routed.rpt", + "defaultpath": "", + "type": "file", + "sha1hash": "488cefcec4a3cac9fe5e7a921a09af3657c23e25", + "sha256hash": "b0b280ef67763fec20cfe6ce7799233c5a04894866d3ee265161e47c7db73c6e" + }, + "39": { + "name": "litex-linux_utilization_placed.pb", + "filesize": 242, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_utilization_placed.pb", + "defaultpath": "", + "type": "file", + "sha1hash": "5ab62d0ad0e2c82388b82ab5166c821cee33d384", + "sha256hash": "6a9e6e1df5bd47d3261604ca0775ecbd5cfeb85d59f44ff20aea9bb60b7e8384" + }, + "38": { + "filesize": 459, + "name": "vivado.pb", + "type": "file", + "sha256hash": "07b612e52d6d3b3d8ebb61b6c5f189902c90b7fb9f24e16862bd4412845c6dd1", + "sha1hash": "94b9bdeb1e3479fe004a0a7f747c60326a10a122", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/vivado.pb", + "defaultpath": "" + }, + "85": { + "name": "top_timing_summary_routed.rpt", + "filesize": 124178, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/top_timing_summary_routed.rpt", + "defaultpath": "", + "type": "file", + "sha1hash": "f2011be6a10e344b3a2da96ee24ac3783ab5057a", + "sha256hash": "990080f205864077c7ff9a1758a1788033b7cc824772c19b4f48aae47417be87" + }, + "6": { + "filesize": 800, + "name": "vivado.jou", + "type": "file", + "sha256hash": "186bbbe5855bc0d78c5bb48effc3d2900680530e79074aea81d2265af0d1a462", + "sha1hash": "92cd6c1551024c3f09ea30775ee5e21bb998c5f9", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/vivado.jou", + "subtype": "data", + "defaultpath": "" + }, + "21": { + "sha256hash": "a6ba24502e097cbb1188ce0489b604661f1843d5778ca3cd889554fc671e8e3a", + "sha1hash": "0712deeded6545d2a51b23bfa3bca10b7f4e7d9e", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.mk", + "subtype": "data", + "filesize": 270, + "name": "litex-linux.mk" + }, + "5": { + "sha256hash": "93e161b2d8641c926b304f6c7d55c4a20d18a1e449ccb6aa81f5619f239e051b", + "sha1hash": "dc0313c9ea558763f3e7ac6d8870d09afb0b287d", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/meta.json", + "subtype": "data", + "filesize": 2168, + "name": "meta.json" + }, + "1": { + "type": "file", + "sha256hash": "964a6dbe4039cc53715389d7cf3bada14b8fdef33d6f0859ea490797f513fa88", + "sha1hash": "b4b7575ed0478b35429b2d76a89bd6ecf42337cc", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/mem.init", + "defaultpath": "", + "filesize": 48793, + "name": "mem.init" + }, + "70": { + "filesize": 161, + "name": ".write_bitstream.begin.rst", + "sha256hash": "5ad965291e7e9e8ce5cdbf92968ed1a9f319b4261a553762c8ffe2568b65c22e", + "sha1hash": "22563e4e91da5229e824a8a3315dd0a2c13f229e", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.write_bitstream.begin.rst", + "subtype": "data" + }, + "53": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/rundef.js", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "776c3f78e0c797f69b7e78ce7624972b69ab0c42", + "sha256hash": "99228ea4d0794bb180154c018649938914eee238f8250488ad815f92af5586ce", + "name": "rundef.js", + "filesize": 1930 + }, + "13": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.bit", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "de30572592328cea82d46c73bc38c3593709425b", + "sha256hash": "db2c88480a248c93aaade3032cb9a2c3eb1404aa5b395971beb2f0fc6245e82e", + "name": "litex-linux.bit", + "filesize": 2192111 + }, + "76": { + "type": "file", + "sha256hash": "cefbb22d84bfef12a1396bf17d13a3aa7b04e7a9a5981cd517c98ca2b14f20aa", + "sha1hash": "3e6884d60295fa5e72ed8540beb62c3ea5f76e24", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/runme.log", + "defaultpath": "", + "filesize": 73529, + "name": "runme.log" + }, + "37": { + "filesize": 85171, + "name": "litex-linux_io_placed.rpt", + "sha256hash": "da3e20841a52a713050d9a59491528983b146671ec5b650d0b21e3d74418683b", + "sha1hash": "57dfe8cdd38a89f2ee139720382e68be6c77accf", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_io_placed.rpt" + }, + "63": { + "filesize": 9555, + "name": "opt_design.pb", + "type": "file", + "sha256hash": "770c7b6325a0fc41898f1e280339064ac1341f5d2ec8b881c05f4e0cad1ec6a6", + "sha1hash": "b580f1c5727d07180f4827c888ccc15075716e5c", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/opt_design.pb", + "defaultpath": "" + }, + "69": { + "filesize": 0, + "name": ".vivado.end.rst", + "type": "file", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.vivado.end.rst", + "defaultpath": "" + }, + "84": { + "filesize": 286, + "name": "vrs_config_1.xml", + "type": "file", + "sha256hash": "944439ddde7ecf0a76166a4e6d16e8c1d197b6aeeedff014937253590ef82344", + "sha1hash": "aabc658972bc43296a9b20ea8f7801d6fe99730d", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/.jobs/vrs_config_1.xml", + "defaultpath": "" + }, + "47": { + "filesize": 4650, + "name": "litex-linux.tcl", + "sha256hash": "de5080e7895cbde2af1db49b714fa1a0f836a4e1244a169c9e19024eb9e416e9", + "sha1hash": "870c1285b481d7f200f0e04f36d7646acf0e977d", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux.tcl" + }, + "19": { + "filesize": 20, + "name": "mem_2.init", + "type": "file", + "sha256hash": "58de9c82fde1bce8307f928b168df628f78affe91d9f033322e070ae71c29125", + "sha1hash": "d5e8768b5a008fe37a49749998b2d621d60f6012", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/mem_2.init", + "defaultpath": "" + }, + "9": { + "filesize": 1001, + "name": "webtalk_pa.xml", + "type": "file", + "sha256hash": "ff5542cf5e269eb473146e763351cbc22d0460681e8d116480a2843fce7fc964", + "sha1hash": "dc4ba651ae1856eb1122bf90b378cb8e335b1bd5", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.cache/wt/webtalk_pa.xml", + "defaultpath": "" + }, + "82": { + "filesize": 0, + "name": ".Vivado_Implementation.queue.rst", + "type": "file", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.Vivado_Implementation.queue.rst", + "defaultpath": "" + }, + "71": { + "filesize": 0, + "name": ".write_bitstream.end.rst", + "type": "file", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.write_bitstream.end.rst", + "subtype": "data", + "defaultpath": "" + }, + "59": { + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.opt_design.end.rst", + "filesize": 0, + "name": ".opt_design.end.rst" + }, + "20": { + "filesize": 0, + "name": "mem_1.init", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/mem_1.init", + "subtype": "data" + }, + "48": { + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux.bit", + "defaultpath": "", + "type": "file", + "sha1hash": "de30572592328cea82d46c73bc38c3593709425b", + "sha256hash": "db2c88480a248c93aaade3032cb9a2c3eb1404aa5b395971beb2f0fc6245e82e", + "name": "litex-linux.bit", + "filesize": 2192111 + }, + "26": { + "filesize": 9632593, + "name": "litex-linux.edif", + "sha256hash": "d2cc1eb38efc0cab731120c9862fd137b1af1b8f6d0a67e3ce9b8ce7d899f130", + "sha1hash": "bb2f5ebe02d51cba6baddd0557d2a9575e910ef5", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.edif", + "subtype": "data" + }, + "72": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/htr.txt", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "20c99f2e52d96c28a53b55ce549d9cea1a502bba", + "sha256hash": "c2810760aa3641056f009af3d3e93a76c0c2420b35f9e789ae565e62186d75cf", + "name": "htr.txt", + "filesize": 384 + }, + "33": { + "sha256hash": "651296bffa7de8e2c6bd88056ceb585972b81eeef94da3571126d8e7914f437c", + "sha1hash": "3e911f486118250de63cb8ce16dfb12de54df052", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_drc_opted.rpt", + "filesize": 23765, + "name": "litex-linux_drc_opted.rpt" + }, + "67": { + "filesize": 3583, + "name": "project.wdf", + "sha256hash": "86cafc952b8bf95026dc7ba71e57008588b48c4b98d2e1c091e6a2f6d61dcb46", + "sha1hash": "1421b68b1aa89951728312cbac6c5c2a99c7364b", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/project.wdf" + }, + "49": { + "filesize": 161, + "name": ".opt_design.begin.rst", + "type": "file", + "sha256hash": "5ad965291e7e9e8ce5cdbf92968ed1a9f319b4261a553762c8ffe2568b65c22e", + "sha1hash": "22563e4e91da5229e824a8a3315dd0a2c13f229e", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.opt_design.begin.rst", + "subtype": "data", + "defaultpath": "" + }, + "81": { + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_drc_routed.rpt", + "sha1hash": "019d901cf2fd6eea433164d207b58be70f62f306", + "sha256hash": "c41b76e7a6941192aeadc62198273102003a37d79eb616c17fe0aebfd549ae22", + "type": "file", + "name": "litex-linux_drc_routed.rpt", + "filesize": 23901 + }, + "17": { + "name": "top_utilization_placed.rpt", + "filesize": 8234, + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/top_utilization_placed.rpt", + "subtype": "data", + "sha1hash": "2f9983fa5b53df6f60b5bdf0a79de4df98b6a0c2", + "sha256hash": "e5d74ae9452428dc7dcb476054f5a75479dc988784cc30204ff4fc7e96a7701e", + "type": "file" + }, + "25": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/vivado.log", + "subtype": "data", + "sha1hash": "1773c15c0868340642ff988537b17dd6992e0309", + "sha256hash": "df269531623620ca48205eaeb77d3817c2568aa733e84605e9115c075d702f9a", + "type": "file", + "name": "vivado.log", + "filesize": 93697 + }, + "57": { + "type": "file", + "sha256hash": "7df34f03eb4f9557da97b1f8cc77079cc9fd42ebcd918fc039d7bc77b1dcf955", + "sha1hash": "b768f18eb08db449270b10f94a4a3d6ce5f24a59", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/runme.sh", + "subtype": "data", + "defaultpath": "", + "filesize": 1576, + "name": "runme.sh" + }, + "74": { + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_opt.dcp", + "sha1hash": "69977ddbb97ec30384ce69dec6fd04f97041e3ac", + "sha256hash": "51b4837ab83bebad29b017799b829e3d7cd1faa6d752bb1f2fd4f5aefe66a5e9", + "type": "file", + "name": "litex-linux_opt.dcp", + "filesize": 1825371 + }, + "58": { + "name": "litex-linux_timing_summary_routed.rpx", + "filesize": 605181, + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_timing_summary_routed.rpx", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "c93c1a38b0fee90bcb8fdef0dff4f192bc1a6164", + "sha256hash": "c1dad9f5c8ba1539cc856d079d3977d913055e328dda3f1a404570b27da13c3a" + }, + "18": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.json", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "9227a0f4ab995d860b92ae15066ec1c7be81fb9e", + "sha256hash": "b367af7aff53c075d18aa441f94d02a1b291370422331b488b119e368589a741", + "name": "litex-linux.json", + "filesize": 26549067 + }, + "3": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/vivado_51.backup.log", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "869dcee8e9e14ace420126c86a72212a5deff801", + "sha256hash": "29a2f4048ed3cc2656619cfec323d5eac128a919b50326d10cde1e1e73dbffe4", + "name": "vivado_51.backup.log", + "filesize": 1096 + }, + "68": { + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/place_design.pb", + "sha1hash": "e04c04f7ea27322c93debdfd530fd496e628f6f9", + "sha256hash": "afd907c07a289e34c9139d2a4a19c688a28873aa0d62f0c29582225fdea3f32f", + "type": "file", + "name": "place_design.pb", + "filesize": 48941 + }, + "45": { + "name": "litex-linux.dcp", + "filesize": 1937308, + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux.dcp", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "71c73b67e6d478c898406c282c17e39b9708875b", + "sha256hash": "2038d1f0c4148cc97c713c2d4b299adad2d287fc9ac8f6309b0219afaf3b04fa" + }, + "29": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.route_design.begin.rst", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "22563e4e91da5229e824a8a3315dd0a2c13f229e", + "sha256hash": "5ad965291e7e9e8ce5cdbf92968ed1a9f319b4261a553762c8ffe2568b65c22e", + "name": ".route_design.begin.rst", + "filesize": 161 + }, + "7": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/yosys.tcl", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "0d4a184f1a9b4c3fee3532761d18de8143723f1f", + "sha256hash": "1f18a7155f8b9832828504d2e282e435dddc6347f2c0b1a97ebf8fbfb0abefdf", + "name": "yosys.tcl", + "filesize": 796 + }, + "73": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/ISEWrap.js", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "b9bb12cf1bd5cfb91e1ce6115c9f05a6d6b2fa4c", + "sha256hash": "e3a4ba121d566c77db9037e96bc1cdc28e660bf92b1c07dc54a46715fd2fc260", + "name": "ISEWrap.js", + "filesize": 7308 + }, + "50": { + "sha256hash": "393994fef3207765f5fdbb498f1a437e4384ab4bc1b459e93f4469f1da961233", + "sha1hash": "60f9dbaa5816e5948dcc5e3ce71026a0c4c49add", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/write_bitstream.pb", + "filesize": 36658, + "name": "write_bitstream.pb" + }, + "32": { + "name": "usage_statistics_webtalk.html", + "filesize": 28900, + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/usage_statistics_webtalk.html", + "sha1hash": "21624523efc30977c4f40c04edf1e45bb4b7c969", + "sha256hash": "8a9df95b7ec5494030bca0a2f03224d0f486f3f8d5aeb132a95b744558fb4542", + "type": "file" + }, + "10": { + "name": "litex-linux_run.tcl", + "filesize": 824, + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux_run.tcl", + "subtype": "data", + "sha1hash": "ffa070bd7e37a2e0d5d71e336ffa34bad672aa2c", + "sha256hash": "9b0fa3a5fb73437c2c39f53ba8be831799d6a2967f75d6cba048a3f736557412", + "type": "file" + }, + "66": { + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_drc_routed.pb", + "sha1hash": "da94b022a430614d6464ddab8abf4cc6cd2e01b4", + "sha256hash": "17c43db0fbd27d9040ee1ae60dd963bc3fa8f1adbc02deb9af63a91ce217bbbb", + "type": "file", + "name": "litex-linux_drc_routed.pb", + "filesize": 37 + }, + "56": { + "name": ".init_design.begin.rst", + "filesize": 161, + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.init_design.begin.rst", + "subtype": "data", + "sha1hash": "22563e4e91da5229e824a8a3315dd0a2c13f229e", + "sha256hash": "5ad965291e7e9e8ce5cdbf92968ed1a9f319b4261a553762c8ffe2568b65c22e", + "type": "file" + }, + "16": { + "sha256hash": "61dec913b55e90b73087e2f7a232ac3a0c49c8d59d7a260d4d551da711f52479", + "sha1hash": "99efd1d2ae608b2676bf6b6573cdabf52cce663b", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/lscpu.txt", + "filesize": 20, + "name": "lscpu.txt" + }, + "34": { + "name": "litex-linux_drc_routed.rpx", + "filesize": 46267, + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_drc_routed.rpx", + "sha1hash": "63d215371b3f55f03ad5ff006a3cebb815a02ace", + "sha256hash": "5dcb368039672757cc109616316596deaf4cc4f2a20e4fa32f4ca97f87537309", + "type": "file" + }, + "60": { + "name": "litex-linux_timing_summary_routed.rpt", + "filesize": 769067, + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_timing_summary_routed.rpt", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "8250c3f1f123f7e5849ee33632d371766ef3b155", + "sha256hash": "5bf6b549860628ea2024ea82fa5052156d839e7c7ee5159d295f37102657612a" + }, + "8": { + "type": "file", + "sha256hash": "ab914e7fa99f5c1fdaa839cb40bc62ac678fca2d0da123b4a23dc3525ad7c0a4", + "sha1hash": "bc0d1980aedae39f28dd780b6f17b67f717667ce", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.cache/wt/project.wpc", + "defaultpath": "", + "filesize": 121, + "name": "project.wpc" + }, + "65": { + "name": "litex-linux_utilization_placed.rpt", + "filesize": 10107, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_utilization_placed.rpt", + "defaultpath": "", + "type": "file", + "sha1hash": "68a75058db3021bd415eebdc7de897c25a14e3aa", + "sha256hash": "a1b802ee6295d3c7b2e3022f4fd526cfc034da0adce27c68e43a53bffc90b6f2" + }, + "27": { + "filesize": 284, + "name": "litex-linux.lpr", + "type": "file", + "sha256hash": "70a24272869ddbec87b060f3538fc5bfdbbc7575b8906fb8815a1a679f254b11", + "sha1hash": "f3570566db02f240b702f41a85de3782c76e4475", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.hw/litex-linux.lpr", + "defaultpath": "" + }, + "55": { + "filesize": 44, + "name": "litex-linux_route_status.pb", + "type": "file", + "sha256hash": "054bee4e4e8201a3670766b6b2aa1fbe0b8af3f4fb92eecd1025b800972dd990", + "sha1hash": "d28ed356e5342b4fa1d8c8e525b52f2ce7bfea41", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_route_status.pb", + "subtype": "data", + "defaultpath": "" + }, + "15": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/uname.txt", + "subtype": "data", + "sha1hash": "1ce185d9a182940b71bafacb2ba653dafc795153", + "sha256hash": "3c654532a682c2939a4180076dba3d6248baccafc4b50184fde31729499e15c7", + "type": "file", + "name": "uname.txt", + "filesize": 82 + }, + "46": { + "sha256hash": "783572309d4e4697fa40c7ea63194ec398efec44c40c601384c0de68e44ee011", + "sha1hash": "0960a3994826b39329ca8dedb6c457dedaca83cc", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_control_sets_placed.rpt", + "subtype": "data", + "filesize": 90164, + "name": "litex-linux_control_sets_placed.rpt" + }, + "28": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/runme.bat", + "subtype": "data", + "sha1hash": "b6e42ac93473dbedb4ba28d9cc03b00b68a32235", + "sha256hash": "24885b3dbb922ea548c7e9f83d44c1b1a92b0aba195579f6c9969cffe50fcb00", + "type": "file", + "name": "runme.bat", + "filesize": 257 + }, + "40": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.place_design.end.rst", + "subtype": "data", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "type": "file", + "name": ".place_design.end.rst", + "filesize": 0 + }, + "83": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.init_design.end.rst", + "subtype": "data", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "type": "file", + "name": ".init_design.end.rst", + "filesize": 0 + }, + "31": { + "sha256hash": "98c18794b278a29558dcb53c53fcbeaca0f3417c01e30b52ecf8967974f02b6a", + "sha1hash": "4cb99d0df9547a0788a2b34d5f39319568b94cd5", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_power_routed.rpx", + "subtype": "data", + "filesize": 4520695, + "name": "litex-linux_power_routed.rpx" + }, + "64": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.vivado.begin.rst", + "subtype": "data", + "sha1hash": "0393919ba27b331e8c76a6665b3cd7c99ada0f63", + "sha256hash": "b8f127f6e272b9e5307137c45c9c84c817f965a03f00734ea6fc9b06a191dda7", + "type": "file", + "name": ".vivado.begin.rst", + "filesize": 159 + }, + "30": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_methodology_drc_routed.rpx", + "subtype": "data", + "sha1hash": "878731b46d6aed0c6e2203d29511a90259194fde", + "sha256hash": "8fab35147bdb2430ba29d811073f9229d72dbacd1fe00e869439aea847503eda", + "type": "file", + "name": "litex-linux_methodology_drc_routed.rpx", + "filesize": 199049 + }, + "52": { + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/ISEWrap.sh", + "subtype": "data", + "sha1hash": "2ba2498220e86f4418a28466ddec413265af9cbe", + "sha256hash": "a9705aa05f7bfc31bbc927e1198cc23c97027ad111288c61959e6f5c98ed3574", + "type": "file", + "name": "ISEWrap.sh", + "filesize": 1664 + }, + "12": { + "sha256hash": "05bdbcb4365d72a605ca877b50414afc8adc740c8185af9d57889cba8e6e4252", + "sha1hash": "760586691239a586c64c6b0edca9f9c4cc701712", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.tcl", + "filesize": 122, + "name": "litex-linux.tcl" + }, + "41": { + "name": "litex-linux_clock_utilization_routed.rpt", + "filesize": 33480, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_clock_utilization_routed.rpt", + "defaultpath": "", + "type": "file", + "sha1hash": "ce652a9cf410a053b01f2527d9f916e73042e01d", + "sha256hash": "4a2ac94bafc57cd8155c35d864a614163d648ecd145c86d33e803292cb730dda" + }, + "14": { + "name": "yosys.log", + "filesize": 4287306, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/yosys.log", + "defaultpath": "", + "type": "file", + "sha1hash": "cc5de2657511c889eb6045c57dac0626a93da5dc", + "sha256hash": "90c610bff390137290733dab0a078a832f458e5741825928499c7ecdbfc46fbb" + }, + "36": { + "filesize": 723, + "name": "litex-linux_power_summary_routed.pb", + "type": "file", + "sha256hash": "bb600e33b6939f2843fbb10a1924d727b66fc8874b5c37a984a51aea48a402e5", + "sha1hash": "6aecb965edefa093ea6543b237caf79e4d2cc50a", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_power_summary_routed.pb", + "defaultpath": "" + }, + "54": { + "name": "litex-linux_power_routed.rpt", + "filesize": 13455, + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_power_routed.rpt", + "defaultpath": "", + "type": "file", + "sha1hash": "b8de14a03d86cca34483b84cb7990cee0abc8735", + "sha256hash": "7b64d7149d046538c177e2f258e90df7f0cdee1ff1312bf21ddba171cddaf818" + }, + "77": { + "filesize": 73945, + "name": "litex-linux.vdi", + "type": "file", + "sha256hash": "fe01547924cfa95a9359998e67128aed5b1367bab42b56eb10fd54d6f74d381d", + "sha1hash": "13450c85e3ec3bb4a868d403b238d590cfe72445", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux.vdi", + "subtype": "data", + "defaultpath": "" + }, + "62": { + "sha256hash": "8da2608eeba58577c064d0cb9aea4ce7be00488008b7bffbc594eded6a45c040", + "sha1hash": "a7dd54683e067966689aff6b3b16ef093c032f2e", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_placed.dcp", + "subtype": "data", + "filesize": 3019150, + "name": "litex-linux_placed.dcp" + }, + "78": { + "sha256hash": "49a28e66264af48ceda54b4506fd11f53cbc3b2593c99669fbeb4b532e0c65d5", + "sha1hash": "0b205a62885228fea8e5ba9e52254ca28e6375e7", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/usage_statistics_webtalk.xml", + "subtype": "data", + "filesize": 41982, + "name": "usage_statistics_webtalk.xml" + }, + "61": { + "type": "file", + "sha256hash": "5269be30f9c5d09ab77fccc6b43e2a82db18e1ca6c52959e1d62e91ecceef479", + "sha1hash": "20606bbc93d5010c9d0b000555fe14fbf71a1190", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/init_design.pb", + "defaultpath": "", + "filesize": 5239, + "name": "init_design.pb" + }, + "44": { + "filesize": 161, + "name": ".place_design.begin.rst", + "sha256hash": "5ad965291e7e9e8ce5cdbf92968ed1a9f319b4261a553762c8ffe2568b65c22e", + "sha1hash": "22563e4e91da5229e824a8a3315dd0a2c13f229e", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.place_design.begin.rst", + "subtype": "data" + }, + "11": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/vivado_51.backup.jou", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "96b087601bf14494f9d6a0595bbd87f91a407222", + "sha256hash": "f46d819f16dedec29a736397031a72474a02ed6c1abaf8f14fc0b7c51c942399", + "name": "vivado_51.backup.jou", + "filesize": 747 + }, + "42": { + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/gen_run.xml", + "subtype": "data", + "defaultpath": "", + "type": "file", + "sha1hash": "f2b8ae0639024dcb23c835e97ffddf693d79027f", + "sha256hash": "ecb1b7fb2a1ab6c302c0536a5e32ee592aa497e6bb30a5071f8eb2fcd5b30ff1", + "name": "gen_run.xml", + "filesize": 5640 + }, + "2": { + "type": "file", + "sha256hash": "b5ae1ed3abd559cbfa3d293f6e2889bbc56de1a233f2a4230cc7722c584050cf", + "sha1hash": "d9831ed75d8cdecc605c5f92c1d2ec53c79f0125", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/Makefile", + "defaultpath": "", + "filesize": 815, + "name": "Makefile" + }, + "79": { + "filesize": 17294, + "name": "route_design.pb", + "sha256hash": "3c5ecc6560ac11de807b8c5647aa23c20839900e3ddbaf1527dd27d610b8c906", + "sha1hash": "3d01cb0e996e4679d24cf5b8702f1de89fe50fc7", + "type": "file", + "defaultpath": "", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/route_design.pb" + }, + "51": { + "filesize": 0, + "name": ".route_design.end.rst", + "type": "file", + "sha256hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "sha1hash": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/.route_design.end.rst", + "defaultpath": "" + }, + "23": { + "filesize": 11390, + "name": "hydra-build-products", + "type": "file", + "sha256hash": "2bfea4676e397b275415a334dfe09c4ed505a12133ce3507221fd0b14668bfe0", + "sha1hash": "4491112ffcd4d7e1cb2738f8eae6cd77c7767fdd", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/nix-support/hydra-build-products", + "defaultpath": "" + }, + "35": { + "filesize": 4199145, + "name": "litex-linux_routed.dcp", + "type": "file", + "sha256hash": "356a3ed04e6b5c16a41b6e27e5ef9f3f9157cae790386b839fb234c4d2b7e481", + "sha1hash": "70d9f0dbd64800c48b2f49750e5a54d8ac92acb3", + "subtype": "data", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/litex-linux.runs/impl_1/litex-linux_routed.dcp", + "defaultpath": "" + } + }, + "id": 1397, + "stoptime": 1593130245 +} \ No newline at end of file diff --git a/tests/sample_data/build.small.json b/tests/sample_data/build.small.json new file mode 100644 index 0000000..1f4e920 --- /dev/null +++ b/tests/sample_data/build.small.json @@ -0,0 +1,15 @@ +{ + "buildstatus": 0, + "buildproducts": { + "5": { + "sha256hash": "93e161b2d8641c926b304f6c7d55c4a20d18a1e449ccb6aa81f5619f239e051b", + "sha1hash": "dc0313c9ea558763f3e7ac6d8870d09afb0b287d", + "type": "file", + "defaultpath": "", + "path": "/nix/store/ajav7i3q5ii38pm24diknyccs8hn6nwd-fpga-tool-perf-baselitex-vivado-yosys-arty/meta.json", + "subtype": "data", + "filesize": 2168, + "name": "meta.json" + } + } +} \ No newline at end of file diff --git a/tests/test_fetcher_large.py b/tests/test_fetcher_large.py index 3716a8a..aa14b01 100644 --- a/tests/test_fetcher_large.py +++ b/tests/test_fetcher_large.py @@ -65,6 +65,8 @@ class TestHydraFetcherLarge(unittest.TestCase): evals_fn = 'tests/sample_data/evals.large.json' evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' + build_fn = 'tests/sample_data/build.large.json' + meta_fn = 'tests/sample_data/meta.large.json' # setup /evals request mock @@ -73,13 +75,21 @@ class TestHydraFetcherLarge(unittest.TestCase): evals_json_encoded = f.read() evals_json_decoded = json.loads(evals_json_encoded) m.get(evals_url, text=evals_json_encoded) + + # read sample build response + build_json_encoded = None + with open(build_fn, "r") as f: + build_json_encoded = f.read() - # setup /meta.json request mock + # setup /build and /meta.json request mock with open(meta_fn, "r") as f: meta_json_encoded = f.read() for eval_obj in evals_json_decoded["evals"]: for build_num in eval_obj["builds"]: - url = f'https://hydra.vtr.tools/build/{build_num}/download/1/meta.json' + # setup /build + m.get(f'https://hydra.vtr.tools/build/{build_num}', text=build_json_encoded) + # setup meta.json + url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' m.get(url, text=meta_json_encoded) # run tests on different eval_num @@ -97,8 +107,6 @@ class TestHydraFetcherLarge(unittest.TestCase): expected_num_rows = len(evals_json_decoded['evals'][eval_num]['builds']) self.assertEqual(len(result.index), expected_num_rows) - # TODO: more tests on real data - class TestJSONFetcherLarge(unittest.TestCase): """ diff --git a/tests/test_fetcher_small.py b/tests/test_fetcher_small.py index 9182159..f97ba85 100644 --- a/tests/test_fetcher_small.py +++ b/tests/test_fetcher_small.py @@ -49,15 +49,26 @@ class TestHydraFetcherSmall(unittest.TestCase): evals_fn = 'tests/sample_data/evals.small.json' evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' - # load sample json data + build_fn = 'tests/sample_data/build.small.json' + + # setup /evals request mock with open(evals_fn, "r") as f: json_data = f.read() - m.get(evals_url, text=json_data) # setup /evals request mock + m.get(evals_url, text=json_data) + + # setup /build and /meta.json request mock + with open(build_fn, "r") as f: + json_data = f.read() for build_num in range(12): - url = f'https://hydra.vtr.tools/build/{build_num}/download/1/meta.json' + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' payload = {"build_num": build_num} - m.get(url, json=payload) # setup /meta.json request mock + m.get(meta_url, json=payload) # setup /meta.json request mock # run tests on different eval_num for eval_num in range(0, 3): @@ -87,15 +98,26 @@ class TestHydraFetcherSmall(unittest.TestCase): evals_fn = 'tests/sample_data/evals.small.json' evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' - # load sample json data + build_fn = 'tests/sample_data/build.small.json' + + # setup /evals request mock with open(evals_fn, "r") as f: json_data = f.read() - m.get(evals_url, text=json_data) # setup /evals request mock + m.get(evals_url, text=json_data) - for build_num in range(4): - url = f'https://hydra.vtr.tools/build/{build_num}/download/1/meta.json' - payload = {"build_num": build_num, "extra": 1} - m.get(url, json=payload) # setup /meta.json request mock + # setup /build and /meta.json request mock + with open(build_fn, "r") as f: + json_data = f.read() + + for build_num in range(12): + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' + payload = {"build_num": build_num} + m.get(meta_url, json=payload) # setup /meta.json request mock # test exclusion hf1 = HydraFetcher( @@ -135,13 +157,24 @@ class TestHydraFetcherSmall(unittest.TestCase): evals_fn = 'tests/sample_data/evals.small.json' evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' - # load sample json data + build_fn = 'tests/sample_data/build.small.json' + + # setup /evals request mock with open(evals_fn, "r") as f: json_data = f.read() - m.get(evals_url, text=json_data) # setup /evals request mock + m.get(evals_url, text=json_data) + + # setup /build and /meta.json request mock + with open(build_fn, "r") as f: + json_data = f.read() for build_num in range(4): - url = f'https://hydra.vtr.tools/build/{build_num}/download/1/meta.json' + # /build/:buildid0 + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' payload = { "max_freq": { "clk": {
HydraFetcher unable to fetch meta.json of older builds The current hydrafetcher assumes that `meta.json` is the only build product when fetching it from Hydra. Thus, it fetches the `meta.json` file from the following link: ```python "https://hydra.vtr.tools/build/{build_num}/download/1/meta.json" ``` This assumption does not hold for older builds ([example](https://hydra.vtr.tools/build/1382)), since the `1` in the path could actually be a different number (in the example, `8`). This can be resolved by first fetching the build info using the [Hydra API](https://hydra.nixos.org/build/124511651/download/1/hydra/#idm140737319750000) and searching for the file named `meta.json`.
0.0
2c06f09c80ce8fda7d82176a212de10c3d2b589a
[ "tests/test_fetcher_large.py::TestHydraFetcherLarge::test_hydrafetcher_get_evaluation", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_eval_num", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_mapping", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_hydra_clock_names" ]
[ "tests/test_fetcher_large.py::TestHydraFetcherLarge::test_hydrafetcher_init", "tests/test_fetcher_large.py::TestJSONFetcherLarge::test_jsonfetcher_get_evaluation", "tests/test_fetcher_large.py::TestJSONFetcherLarge::test_jsonfetcher_init", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_init", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_get_evaluation", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_get_evaluation_mapping", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_init" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-07-31 22:19:33+00:00
mit
726
SymbiFlow__FPGA-Tool-Performance-Visualization-Library-24
diff --git a/ftpvl/fetchers.py b/ftpvl/fetchers.py index e70bc9d..1e9559b 100644 --- a/ftpvl/fetchers.py +++ b/ftpvl/fetchers.py @@ -1,4 +1,5 @@ """ Fetchers are responsible for ingesting and standardizing data for future processing. """ +from datetime import datetime import json from typing import Any, Dict, List @@ -228,6 +229,37 @@ class HydraFetcher(Fetcher): return data + def _check_legacy_icebreaker(self, row): + """ + Returns True if row is from a test on an Icebreaker board before Jul 31, + 2020. + + This is useful because these legacy tests recorded frequency in MHz + instead of Hz, while all other boards record in Hz. This flag can be + used to check if the units need to be changed. + + Parameters + ---------- + row : dict + a dictionary that is the result of decoding a meta.json file + + Returns + ------- + bool + Returns true if row is icebreaker board before Aug 1, 2020. False + otherwise. + """ + date = None + board = None + try: + date = row["date"] # format: 2020-07-17T22:12:41 + board = row["board"] + timestamp = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") + return timestamp < datetime(2020, 7, 31) and board == "icebreaker" + except KeyError: + print("Warning: Unable to find date and board in meta.json, required for supporting legacy Icebreaker.") + return False # Assume not legacy icebreaker + def _preprocess(self, data: List[Dict]) -> pd.DataFrame: """ Using data from _download(), processes and standardizes the data and @@ -237,13 +269,21 @@ class HydraFetcher(Fetcher): processed_data = [] for row in flattened_data: + legacy_icestorm = self._check_legacy_icebreaker(row) processed_row = {} if self.mapping is None: processed_row = row else: for in_col_name, out_col_name in self.mapping.items(): processed_row[out_col_name] = row[in_col_name] - processed_row["freq"] = Helpers.get_actual_freq(row, self.hydra_clock_names) + + actual_freq = Helpers.get_actual_freq(row, self.hydra_clock_names) + if actual_freq: + if legacy_icestorm: + # freq in MHz, no change needed + processed_row["freq"] = actual_freq + else: + processed_row["freq"] = actual_freq / 1_000_000 # convert hz to mhz processed_row.update(Helpers.get_versions(row)) processed_data.append(processed_row) diff --git a/ftpvl/helpers.py b/ftpvl/helpers.py index d326384..54a0121 100644 --- a/ftpvl/helpers.py +++ b/ftpvl/helpers.py @@ -62,39 +62,19 @@ def get_versions(obj: dict) -> dict: return {k: v for k, v in obj.items() if k.startswith("versions.")} -def rescale_actual_freq(freq: Union[int, float]) -> Union[int, float]: - """ - Given a frequency with an unspecified unit, returns frequency in megahertz - by assuming the original unit is hertz if input frequency is greater than 1 - million. - - Parameters - ---------- - freq : Union[int, float] - a number that is a frequency - - Returns - ------- - Union[int, float] - the input frequency in megahertz - """ - one_mhz = 1_000_000 - if freq > one_mhz: - return freq / one_mhz - else: - return freq - - def get_actual_freq(obj: dict, hydra_clock_names: list = None) -> Union[int, float]: """ Given a flattened object decoded from meta.json, return the actual frequency - as a number in megahertz. + as a number. Since a meta.json object might contain multiple frequencies, we look through all clock names specified in hydra_clock_names and use the first one in the list. If none of the specified clock names exists in the object, we use the shortest clock name to find the frequency. + The output of this function returns a number with undetermined units. + External logic should handle converting units if necessary. + Parameters ---------- obj : dict @@ -114,13 +94,13 @@ def get_actual_freq(obj: dict, hydra_clock_names: list = None) -> Union[int, flo # if max_freq is unnested if "max_freq" in obj: - return rescale_actual_freq(obj["max_freq"]) + return obj["max_freq"] else: # check if max_freq contains clock_name in HYDRA_CLOCK_NAMES for clock_name in hydra_clock_names: key = f"max_freq.{clock_name}.actual" if key in obj: - return rescale_actual_freq(obj[key]) + return obj[key] # if none of those exist, choose the shortest one or return None max_freq_keys = [ @@ -128,7 +108,7 @@ def get_actual_freq(obj: dict, hydra_clock_names: list = None) -> Union[int, flo ] if len(max_freq_keys) > 0: shortest_clock_name = min(max_freq_keys, key=len) - return rescale_actual_freq(obj[shortest_clock_name]) + return obj[shortest_clock_name] else: return None
SymbiFlow/FPGA-Tool-Performance-Visualization-Library
0d5464c63006ae08e299e2aba15968d584bab1b7
diff --git a/tests/test_fetcher_small.py b/tests/test_fetcher_small.py index 80d8fdc..84bde5e 100644 --- a/tests/test_fetcher_small.py +++ b/tests/test_fetcher_small.py @@ -22,6 +22,7 @@ class TestHydraFetcherSmall(unittest.TestCase): different mapping exclusion, renaming pagination + with/without board and date information """ def test_hydrafetcher_init(self): @@ -75,7 +76,11 @@ class TestHydraFetcherSmall(unittest.TestCase): # /meta.json meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' - payload = {"build_num": build_num} + payload = { + "build_num": build_num, + "date": "2020-07-17T22:12:40", + "board": "arty" + } m.get(meta_url, json=payload) # setup /meta.json request mock # run tests on different eval_num @@ -88,8 +93,161 @@ class TestHydraFetcherSmall(unittest.TestCase): eval_num=eval_num) result = hf.get_evaluation().get_df() - col = [x for x in range(eval_num * 4, eval_num * 4 + 4)] - expected = pd.DataFrame({"build_num": col}) + expected = pd.DataFrame({ + "build_num": [x for x in range(eval_num * 4, eval_num * 4 + 4)], + "date": ["2020-07-17T22:12:40" for _ in range(4)], + "board": ["arty" for _ in range(4)] + }) + assert_frame_equal(result, expected) + + eval_id = hf.get_evaluation().get_eval_id() + assert eval_id == eval_num + 1 + + def test_hydrafetcher_get_evaluation_icebreaker_old(self): + """ + get_evaluation() should return an Evaluation corresponding to the small + dataset and the specified eval_num. + + Tests legacy icebreaker support, where icebreaker boards report + max frequency in MHz instead of Hz. + """ + with requests_mock.Mocker() as m: + evals_fn = 'tests/sample_data/evals.small.json' + evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' + + build_fn = 'tests/sample_data/build.small.json' + + # setup /evals request mock + with open(evals_fn, "r") as f: + json_data = f.read() + m.get(evals_url, text=json_data) + + # setup /build and /meta.json request mock + with open(build_fn, "r") as f: + json_data = f.read() + + for build_num in range(12): + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' + payload = { + "build_num": build_num, + "date": "2020-07-30T22:12:40", + "board": "icebreaker", + "max_freq": 81.05 + } + m.get(meta_url, json=payload) # setup /meta.json request mock + + # run tests on different eval_num + for eval_num in range(0, 3): + with self.subTest(eval_num=eval_num): + # if mapping is not defined, should not remap + hf = HydraFetcher( + project="dusty", + jobset="fpga-tool-perf", + eval_num=eval_num, + mapping={"build_num": "build_num"}) + result = hf.get_evaluation().get_df() + + expected = pd.DataFrame({ + "build_num": [x for x in range(eval_num * 4, eval_num * 4 + 4)], + "freq": [81.05 for _ in range(4)] + }) + print(result.columns) + assert_frame_equal(result, expected) + + eval_id = hf.get_evaluation().get_eval_id() + assert eval_id == eval_num + 1 + + def test_hydrafetcher_get_evaluation_icebreaker_new(self): + """ + get_evaluation() should return an Evaluation corresponding to the small + dataset and the specified eval_num. + + Tests legacy icebreaker support does not affect an eval where the date + is not before 7-31-2020. + """ + with requests_mock.Mocker() as m: + evals_fn = 'tests/sample_data/evals.small.json' + evals_url = 'https://hydra.vtr.tools/jobset/dusty/fpga-tool-perf/evals' + + build_fn = 'tests/sample_data/build.small.json' + + # setup /evals request mock + with open(evals_fn, "r") as f: + json_data = f.read() + m.get(evals_url, text=json_data) + + # setup /build and /meta.json request mock + with open(build_fn, "r") as f: + json_data = f.read() + + # test if date is not before 7-31-2020 + for build_num in range(4): + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' + payload = { + "build_num": build_num, + "date": "2020-07-31T22:12:40", + "board": "icebreaker", + "max_freq": 81050000 + } + m.get(meta_url, json=payload) # setup /meta.json request mock + + # test if board is not icebreaker + for build_num in range(4, 8): + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' + payload = { + "build_num": build_num, + "date": "2020-07-30T22:12:40", + "board": "arty", + "max_freq": 81050000 + } + m.get(meta_url, json=payload) # setup /meta.json request mock + + # test if date and board are not included + for build_num in range(8, 12): + # /build/:buildid + build_url = f'https://hydra.vtr.tools/build/{build_num}' + m.get(build_url, text=json_data) + + # /meta.json + meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' + payload = { + "build_num": build_num, + # date and build intentionally removed + "max_freq": 81050000 + } + m.get(meta_url, json=payload) # setup /meta.json request mock + + # run tests on different eval_num + for eval_num in range(0, 3): + with self.subTest(eval_num=eval_num): + # if mapping is not defined, should not remap + hf = HydraFetcher( + project="dusty", + jobset="fpga-tool-perf", + eval_num=eval_num, + mapping={"build_num": "build_num"}) + result = hf.get_evaluation().get_df() + + # all results should have frequency converted from hz to mhz (no legacy icebreaker) + expected = pd.DataFrame({ + "build_num": [x for x in range(eval_num * 4, eval_num * 4 + 4)], + "freq": [81.05 for _ in range(4)] + }) assert_frame_equal(result, expected) eval_id = hf.get_evaluation().get_eval_id() @@ -168,7 +326,7 @@ class TestHydraFetcherSmall(unittest.TestCase): # setup /evals request mock with open(evals_fn, "r") as f: json_data = f.read() - m.get(evals_url, text=json_data) + m.get(evals_url, text=json_data) # setup /build and /meta.json request mock with open(build_fn, "r") as f: @@ -181,7 +339,11 @@ class TestHydraFetcherSmall(unittest.TestCase): # /meta.json meta_url = f'https://hydra.vtr.tools/build/{build_num}/download/5/meta.json' - payload = {"build_num": build_num} + payload = { + "build_num": build_num, + "date": "2020-07-17T22:12:40", + "board": "arty" + } m.get(meta_url, json=payload) # setup /meta.json request mock # test exclusion @@ -243,15 +405,17 @@ class TestHydraFetcherSmall(unittest.TestCase): payload = { "max_freq": { "clk": { - "actual": 100 + "actual": 1000000 }, "clk_i": { - "actual": 200 + "actual": 2000000 }, "sys_clk": { - "actual": 300 + "actual": 3000000 } - } + }, + "date": "2020-07-17T22:12:40", + "board": "arty" } m.get(url, json=payload) # setup /meta.json request mock @@ -260,9 +424,9 @@ class TestHydraFetcherSmall(unittest.TestCase): # format test cases as tuples: # ({hydra_clock_names}, {expected_clock}) test_cases = [ - (["clk", "clk_i", "sys_clk"], 100), - (["clk_i", "sys_clk", "clk"], 200), - (["sys_clk", "clk", "clk_i"], 300), + (["clk", "clk_i", "sys_clk"], 1.0), + (["clk_i", "sys_clk", "clk"], 2.0), + (["sys_clk", "clk", "clk_i"], 3.0), ] for hydra_clock_name, expected_clock in test_cases: @@ -286,7 +450,7 @@ class TestHydraFetcherSmall(unittest.TestCase): hydra_clock_names=[]) result = hf.get_evaluation().get_df() - expected_col = [100 for _ in range(4)] + expected_col = [1.0 for _ in range(4)] expected_series = pd.Series(expected_col, name="freq") assert_series_equal(result["freq"], expected_series) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index fed1e6f..e343be5 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -39,30 +39,13 @@ class TestHelpers(): result = get_versions({}) assert result == {} - def test_rescale_actual_freq(self): - """ Test if rescaling works correctly """ - result = rescale_actual_freq(1_000_000) - assert result == 1_000_000 - - result = rescale_actual_freq(1_000_001) - assert result == 1.000001 - - result = rescale_actual_freq(1000) - assert result == 1000 - - result = rescale_actual_freq(32_000_000) - assert result == 32 - - result = rescale_actual_freq(5_000_000) - assert result == 5 - def test_get_actual_freq(self): """ Test if get_actual_freq correctly extracts max frequency """ obj = { - "max_freq": 500 + "max_freq": 5_000_000 } result = get_actual_freq(flatten(obj)) - assert result == 500 + assert result == 5_000_000 obj = { "max_freq": { @@ -72,7 +55,7 @@ class TestHelpers(): } } result = get_actual_freq(flatten(obj)) - assert result == 12 + assert result == 12_000_000 def test_get_actual_freq_hydra_clock_names(self): """ Test if get_actual_freq correctly selects the most important clock """ @@ -89,7 +72,7 @@ class TestHelpers(): } } result = get_actual_freq(flatten(obj), ["clk", "sys_clk", "clk_i"]) - assert result == 12 + assert result == 12_000_000 # should select sys_clk since it is higher priority obj = { @@ -103,7 +86,7 @@ class TestHelpers(): } } result = get_actual_freq(flatten(obj), ["clk", "sys_clk", "clk_i"]) - assert result == 24 + assert result == 24_000_000 # should select clk_i since it is higher priority obj = { @@ -117,7 +100,7 @@ class TestHelpers(): } } result = get_actual_freq(flatten(obj), ["clk_i", "sys_clk", "clk"]) - assert result == 12 + assert result == 12_000_000 # should select shortest clock name since none are specified obj = { @@ -131,7 +114,7 @@ class TestHelpers(): } } result = get_actual_freq(flatten(obj), ["clk", "sys_clk", "clk_i"]) - assert result == 12 + assert result == 12_000_000 def test_get_styling(self): """ Test if get_styling correctly queries colormap and returns correct
Legacy Icestorm Processor As of August 1st, [fpga-tool-perf issue #190](https://github.com/SymbiFlow/fpga-tool-perf/issues/190) to correct the reported frequency of icestorm boards has been resolved. Now, all boards correctly report frequency in hertz. However, this does not retroactively change fpga-tool-perf evaluations that were run before the fix was merged. Therefore, we need to create a processor that allows the user to explicitly fix the icestorm data to ensure that we can compare icestorm frequency data before and after the fix.
0.0
0d5464c63006ae08e299e2aba15968d584bab1b7
[ "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_hydra_clock_names", "tests/test_helpers.py::TestHelpers::test_get_actual_freq", "tests/test_helpers.py::TestHelpers::test_get_actual_freq_hydra_clock_names" ]
[ "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_eval_num", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_eval_num_absolute", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_icebreaker_new", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_icebreaker_old", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_get_evaluation_mapping", "tests/test_fetcher_small.py::TestHydraFetcherSmall::test_hydrafetcher_init", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_get_evaluation", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_get_evaluation_mapping", "tests/test_fetcher_small.py::TestJSONFetcherSmall::test_jsonfetcher_init", "tests/test_helpers.py::TestHelpers::test_flatten", "tests/test_helpers.py::TestHelpers::test_get_versions", "tests/test_helpers.py::TestHelpers::test_get_styling" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-11 19:51:10+00:00
mit
727
TACC__agavepy-106
diff --git a/agavepy/agave.py b/agavepy/agave.py index 4216948..0cb8010 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -25,7 +25,8 @@ from agavepy.clients import (clients_create, clients_delete, clients_list, from agavepy.tokens import token_create, refresh_token from agavepy.utils import load_config, save_config from agavepy.files import (files_copy, files_delete, files_download, - files_list, files_mkdir, files_move, files_pems_list, files_upload) + files_list, files_mkdir, files_move, files_pems_delete, files_pems_list, + files_upload) import sys @@ -845,6 +846,20 @@ class Agave(object): files_move(self.api_server, self.token, source, destination) + def files_pems_delete(self, path): + """ Remove user permissions associated with a file or folder. + + These permissions are set at the API level and do not reflect *nix or + other file system ACL. + Deletes all permissions on a file except those of the owner. + """ + # Check if tokens need to be refreshed. + self.refresh_tokens() + + # Delete api permissions. + files_pems_delete(self.api_server, self.token, path) + + def files_pems_list(self, path): """ List the user permissions associated with a file or folder diff --git a/agavepy/files/__init__.py b/agavepy/files/__init__.py index 426e785..b6b95cb 100644 --- a/agavepy/files/__init__.py +++ b/agavepy/files/__init__.py @@ -4,5 +4,6 @@ from .download import files_download from .list import files_list from .mkdir import files_mkdir from .move import files_move +from .pems_delete import files_pems_delete from .pems_list import files_pems_list from .upload import files_upload diff --git a/agavepy/files/pems_delete.py b/agavepy/files/pems_delete.py new file mode 100644 index 0000000..74ea6dc --- /dev/null +++ b/agavepy/files/pems_delete.py @@ -0,0 +1,32 @@ +""" + pems_list.py +""" +import requests +from .exceptions import AgaveFilesError +from ..utils import handle_bad_response_status_code + + +def files_pems_delete(tenant_url, access_token, path): + """ Remove user permissions associated with a file or folder. + + These permissions are set at the API level and do not reflect *nix or other + file system ACL. + Deletes all permissions on a file except those of the owner. + """ + # Set request url. + endpoint = "{0}/{1}/{2}".format(tenant_url, "files/v2/pems/system", path) + + # Obtain file path. "path" should include the system name at the begining, + # so we get rid of it. + destination = '/'.join( path.split('/')[1:] ) + + # Make request. + try: + headers = {"Authorization":"Bearer {0}".format(access_token)} + params = {"pretty": "true"} + resp = requests.delete(endpoint, headers=headers, params=params) + except Exception as err: + raise AgaveFilesError(err) + + # Handle bad status code. + handle_bad_response_status_code(resp) diff --git a/docs/docsite/files/admin.rst b/docs/docsite/files/admin.rst index b90c28c..ed7bde0 100644 --- a/docs/docsite/files/admin.rst +++ b/docs/docsite/files/admin.rst @@ -13,3 +13,9 @@ or other file system ACL. >>> ag.files_pems_list("system-id/some-dir") USER READ WRITE EXEC username yes yes yes + +To remove all the permissions on a file, except those of the owner: + +.. code-block:: pycon + + agave.files_pems_delete("system-id/some-dir")
TACC/agavepy
496b0eac501b6cd138920c69bf23ef438dbe7162
diff --git a/tests/files-pems_test.py b/tests/files-pems_test.py index 41d6abe..068a513 100644 --- a/tests/files-pems_test.py +++ b/tests/files-pems_test.py @@ -24,10 +24,28 @@ class MockServerListingsEndpoints(BaseHTTPRequestHandler): """ Mock the Agave API """ def do_GET(self): + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + self.send_response(200) self.end_headers() self.wfile.write(json.dumps(sample_files_pems_list_response).encode()) + def do_DELETE(self): + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + + self.send_response(200) + self.end_headers() + class TestMockServer(MockServer): @@ -44,7 +62,7 @@ class TestMockServer(MockServer): def test_files_pems_list(self, capfd): - """ Test files listings + """ Test permissions listings """ local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) agave = Agave(api_server=local_uri) @@ -52,7 +70,7 @@ class TestMockServer(MockServer): agave.created_at = str(int(time.time())) agave.expires_in = str(14400) - # List files. + # List permissions. agave.files_pems_list("tacc-globalfs-username/") # Stdout should contain the putput from the command. @@ -61,3 +79,16 @@ class TestMockServer(MockServer): assert "username" in out assert "yes" in out assert "200" in err + + + def test_files_pems_list(self): + """ Test permissions deletion + """ + local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) + agave = Agave(api_server=local_uri) + agave.token = "mock-access-token" + agave.created_at = str(int(time.time())) + agave.expires_in = str(14400) + + # Delete permissions. + agave.files_pems_delete("tacc-globalfs-username/")
Implement files_pems_delete method **Is your feature request related to a problem? Please describe.** Part of the changes proposed for release v3.0.0 of `TACC-Cloud/agave-cli` **Describe the solution you'd like** Implement a method to remove user permissions from a file or folder. For all but iRODS systems, these permissions are set at the API level and do not reflect *nix or other file system ACL. On iRODS systems, if the system.storageConfig.mirror attribute is set to true then any permissions set via the API will be mirrored onto the remote system.
0.0
496b0eac501b6cd138920c69bf23ef438dbe7162
[ "tests/files-pems_test.py::TestMockServer::test_files_pems_list" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-11-30 18:07:16+00:00
bsd-3-clause
728
TACC__agavepy-107
diff --git a/agavepy/agave.py b/agavepy/agave.py index 0cb8010..2d73cf2 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -26,7 +26,7 @@ from agavepy.tokens import token_create, refresh_token from agavepy.utils import load_config, save_config from agavepy.files import (files_copy, files_delete, files_download, files_list, files_mkdir, files_move, files_pems_delete, files_pems_list, - files_upload) + files_pems_update, files_upload) import sys @@ -873,6 +873,25 @@ class Agave(object): files_pems_list(self.api_server, self.token, path) + def files_pems_update(self, path, username, perms, recursive=False): + """ Edit user permissions associated with a file or folder. + + These permissions are set at the API level and do not reflect *nix or + other file system ACL. + Deletes all permissions on a file except those of the owner. + Valid values for setting permission with the -P flag are READ, WRITE, + EXECUTE, READ_WRITE, READ_EXECUTE, WRITE_EXECUTE, ALL, and NONE. + """ + # Check if tokens need to be refreshed. + self.refresh_tokens() + + # Update api permissions. + files_pems_update( + self.api_server, self.token, + path, username, perms, + recursive=recursive) + + def files_upload(self, source, destination): """ Upload file to remote system """ diff --git a/agavepy/files/__init__.py b/agavepy/files/__init__.py index b6b95cb..1daf53e 100644 --- a/agavepy/files/__init__.py +++ b/agavepy/files/__init__.py @@ -6,4 +6,5 @@ from .mkdir import files_mkdir from .move import files_move from .pems_delete import files_pems_delete from .pems_list import files_pems_list +from .pems_update import files_pems_update from .upload import files_upload diff --git a/agavepy/files/pems_delete.py b/agavepy/files/pems_delete.py index 74ea6dc..b1b9dce 100644 --- a/agavepy/files/pems_delete.py +++ b/agavepy/files/pems_delete.py @@ -1,5 +1,5 @@ """ - pems_list.py + pems_delete.py """ import requests from .exceptions import AgaveFilesError diff --git a/agavepy/files/pems_update.py b/agavepy/files/pems_update.py new file mode 100644 index 0000000..9ae319f --- /dev/null +++ b/agavepy/files/pems_update.py @@ -0,0 +1,39 @@ +""" + pems_update.py +""" +import requests +from .exceptions import AgaveFilesError +from ..utils import handle_bad_response_status_code + + +def files_pems_update(tenant_url, access_token, path, username, perms, recursive=False): + """ Edit user permissions associated with a file or folder. + + These permissions are set at the API level and do not reflect *nix or other + file system ACL. + Deletes all permissions on a file except those of the owner. + Valid values for setting permission with the -P flag are READ, WRITE, + EXECUTE, READ_WRITE, READ_EXECUTE, WRITE_EXECUTE, ALL, and NONE. + """ + # Set request url. + endpoint = "{0}/{1}/{2}".format(tenant_url, "files/v2/pems/system", path) + + # Obtain file path. "path" should include the system name at the begining, + # so we get rid of it. + destination = '/'.join( path.split('/')[1:] ) + + # Make request. + try: + headers = {"Authorization":"Bearer {0}".format(access_token)} + data = { + "username": username, + "permission": perms, + "recursive": recursive + } + params = {"pretty": "true"} + resp = requests.post(endpoint, headers=headers, data=data, params=params) + except Exception as err: + raise AgaveFilesError(err) + + # Handle bad status code. + handle_bad_response_status_code(resp) diff --git a/docs/docsite/files/admin.rst b/docs/docsite/files/admin.rst index ed7bde0..d120f34 100644 --- a/docs/docsite/files/admin.rst +++ b/docs/docsite/files/admin.rst @@ -19,3 +19,18 @@ To remove all the permissions on a file, except those of the owner: .. code-block:: pycon agave.files_pems_delete("system-id/some-dir") + + +To edit permissions for another user, let's say her username is "collab," +to view a file: + +.. code-block:: pycon + + ag.files_pems_update("system-id/path", "collab", "ALL", recursive=True) + +Now, a user with username "collab" has permissions to access the all contents +of the specified directory (hence the ``recursive=True`` option). + +Valid values for setting permission are ``READ``, ``WRITE``, ``EXECUTE``, +``READ_WRITE``, ``READ_EXECUTE``, ``WRITE_EXECUTE``, ``ALL``, and ``NONE``. +This same action can be performed recursively on directories using ``recursive=True``.
TACC/agavepy
5d5fc59ea175d7c9ee04847b6577e8656da6e981
diff --git a/tests/files-pems_test.py b/tests/files-pems_test.py index 068a513..0f3a662 100644 --- a/tests/files-pems_test.py +++ b/tests/files-pems_test.py @@ -46,6 +46,17 @@ class MockServerListingsEndpoints(BaseHTTPRequestHandler): self.send_response(200) self.end_headers() + def do_POST(self): + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + + self.send_response(200) + self.end_headers() + class TestMockServer(MockServer): @@ -81,7 +92,7 @@ class TestMockServer(MockServer): assert "200" in err - def test_files_pems_list(self): + def test_files_pems_delete(self, capfd): """ Test permissions deletion """ local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) @@ -92,3 +103,20 @@ class TestMockServer(MockServer): # Delete permissions. agave.files_pems_delete("tacc-globalfs-username/") + out, err = capfd.readouterr() + assert "200" in err + + + def test_files_pems_update(self, capfd): + """ Test permissions updates + """ + local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) + agave = Agave(api_server=local_uri) + agave.token = "mock-access-token" + agave.created_at = str(int(time.time())) + agave.expires_in = str(14400) + + # Delete permissions. + agave.files_pems_update("tacc-globalfs-username/", "collaborator", "ALL") + out, err = capfd.readouterr() + assert "200" in err
Implement files_pems_update **Is your feature request related to a problem? Please describe.** Part of the changes proposed for release v3.0.0 of `TACC-Cloud/agave-cli` **Describe the solution you'd like** Implement method to edit user permissions on a file or folder. For all but iRODS systems, these permissions are set at the API level and do not reflect *nix or other file system ACL. On iRODS systems, if the system.storageConfig.mirror attribute is set to true then any permissions set via the API will be mirrored onto the remote system.
0.0
5d5fc59ea175d7c9ee04847b6577e8656da6e981
[ "tests/files-pems_test.py::TestMockServer::test_files_pems_update" ]
[ "tests/files-pems_test.py::TestMockServer::test_files_pems_list", "tests/files-pems_test.py::TestMockServer::test_files_pems_delete" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-12-03 16:30:39+00:00
mit
729
TACC__agavepy-108
diff --git a/agavepy/agave.py b/agavepy/agave.py index 2d73cf2..26d0b79 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -25,8 +25,8 @@ from agavepy.clients import (clients_create, clients_delete, clients_list, from agavepy.tokens import token_create, refresh_token from agavepy.utils import load_config, save_config from agavepy.files import (files_copy, files_delete, files_download, - files_list, files_mkdir, files_move, files_pems_delete, files_pems_list, - files_pems_update, files_upload) + files_history, files_list, files_mkdir, files_move, files_pems_delete, + files_pems_list, files_pems_update, files_upload) import sys @@ -513,7 +513,7 @@ class Agave(object): return list(set(base)) - def init(self, tenantsurl="https://agaveapi.co/tenants"): + def init(self, tenantsurl="https://api.tacc.utexas.edu/tenants"): """ Initilize a session Initialize a session by setting parameters refering to the tenant you @@ -619,7 +619,7 @@ class Agave(object): self.expires_at = session_context["expires_at"] - def list_tenants(self, tenantsurl="https://agaveapi.co/tenants"): + def list_tenants(self, tenantsurl="https://api.tacc.utexas.edu/tenants"): """ List Agave tenants PARAMETERS @@ -816,6 +816,16 @@ class Agave(object): files_download(self.api_server, self.token, source, destination) + def files_history(self, path): + """ List the history of events for a specific file/folder + """ + # Check if tokens need to be refreshed. + self.refresh_tokens() + + # List events for path. + files_history(self.api_server, self.token, path) + + def files_list(self, system_path, long_format=False): """ List files on remote system """ diff --git a/agavepy/files/__init__.py b/agavepy/files/__init__.py index 1daf53e..5aedd4e 100644 --- a/agavepy/files/__init__.py +++ b/agavepy/files/__init__.py @@ -1,6 +1,7 @@ from .copy import files_copy from .delete import files_delete from .download import files_download +from .history import files_history from .list import files_list from .mkdir import files_mkdir from .move import files_move diff --git a/agavepy/files/history.py b/agavepy/files/history.py new file mode 100644 index 0000000..0a5fe12 --- /dev/null +++ b/agavepy/files/history.py @@ -0,0 +1,37 @@ +""" + history.py +""" +import requests +from .exceptions import AgaveFilesError +from ..utils import handle_bad_response_status_code + + +def files_history(tenant_url, access_token, path): + """ List the history of events for a specific file/folder + """ + # Set request url. + endpoint = "{0}/{1}/{2}".format(tenant_url, "files/v2/history/system", path) + + # Obtain file path. "path" should include the system name at the begining, + # so we get rid of it. + destination = '/'.join( path.split('/')[1:] ) + + # Make request. + try: + headers = {"Authorization":"Bearer {0}".format(access_token)} + params = {"pretty": "true"} + resp = requests.get(endpoint, headers=headers, params=params) + except Exception as err: + raise AgaveFilesError(err) + + # Handle bad status code. + handle_bad_response_status_code(resp) + + print("{0:<13} {1:<20} {2:<32} {3:<}".format("USER", "EVENT", "DATE", "DESCRIPTION")) + for msg in resp.json()["result"]: + user = msg["createdBy"] + event = msg["status"] + date = msg["created"] + description = msg["description"] + + print("{0:<13} {1:<20} {2:<32} {3:<}".format(user, event, date, description)) diff --git a/agavepy/tenants/tenants.py b/agavepy/tenants/tenants.py index 77dde1a..196e20d 100644 --- a/agavepy/tenants/tenants.py +++ b/agavepy/tenants/tenants.py @@ -38,7 +38,7 @@ def get_tenants(url): return resp.json() -def tenant_list(tenantsurl="https://agaveapi.co/tenants"): +def tenant_list(tenantsurl="https://api.tacc.utexas.edu/tenants"): """ List Agave tenants List all Agave tenants for a given Agave host. Information listed is the diff --git a/docs/docsite/files/admin.rst b/docs/docsite/files/admin.rst index d120f34..81f4fab 100644 --- a/docs/docsite/files/admin.rst +++ b/docs/docsite/files/admin.rst @@ -34,3 +34,20 @@ of the specified directory (hence the ``recursive=True`` option). Valid values for setting permission are ``READ``, ``WRITE``, ``EXECUTE``, ``READ_WRITE``, ``READ_EXECUTE``, ``WRITE_EXECUTE``, ``ALL``, and ``NONE``. This same action can be performed recursively on directories using ``recursive=True``. + + +File or Directory History +######################### +You can list the history of events for a specific file or folder. +This will give more descriptive information (when applicable) related to number +of retries, permission grants and revocations, reasons for failure, and hiccups +that may have occurred in a recent process. + +.. code-block:: pycon + + >>> ag.files_history("system-id/path/to/dir") + USER EVENT DATE DESCRIPTION + username CREATED 2018-11-02T10:08:54.000-05:00 New directory created at https://api.sd2e.org/files/v2/media/system/system-id//path/to/dir + username PERMISSION_REVOKE 2018-11-30T11:22:01.000-06:00 All permissions revoked + username PERMISSION_GRANT 2018-12-03T10:11:07.000-06:00 OWNER permission granted to collaborator +
TACC/agavepy
7353677359e0ceb6d361e442bb04e7ddab7422ea
diff --git a/tests/files-history_test.py b/tests/files-history_test.py new file mode 100644 index 0000000..bc486a6 --- /dev/null +++ b/tests/files-history_test.py @@ -0,0 +1,70 @@ +""" + files-history_tests.py +""" +import pytest +import json +import os +import sys +import time +from testsuite_utils import MockServer +from response_templates import response_template_to_json +try: # python 2 + from BaseHTTPServer import BaseHTTPRequestHandler +except ImportError: # python 3 + from http.server import BaseHTTPRequestHandler +from agavepy.agave import Agave + + +# Sample successful responses from the agave api. +sample_files_history_response = response_template_to_json("files-history.json") + + + +class MockServerListingsEndpoints(BaseHTTPRequestHandler): + """ Mock the Agave API + """ + def do_GET(self): + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps(sample_files_history_response).encode()) + + +class TestMockServer(MockServer): + """ Test file listing-related agave api endpoints + """ + + @classmethod + def setup_class(cls): + """ Set up an agave mock server + + Listen and serve mock api as a daemon. + """ + MockServer.serve.__func__(cls, MockServerListingsEndpoints) + + + def test_files_history(self, capfd): + """ Test history + """ + local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) + agave = Agave(api_server=local_uri) + agave.token = "mock-access-token" + agave.created_at = str(int(time.time())) + agave.expires_in = str(14400) + + # List permissions. + agave.files_history("tacc-globalfs-username/") + + # Stdout should contain the putput from the command. + # Stderr will contain logs from the mock http server. + out, err = capfd.readouterr() + assert "username" in out + assert "CREATED" in out + assert "PERMISSION_REVOKE" in out + assert "200" in err diff --git a/tests/sample_responses/files-history.json b/tests/sample_responses/files-history.json new file mode 100644 index 0000000..cd8c5ea --- /dev/null +++ b/tests/sample_responses/files-history.json @@ -0,0 +1,61 @@ +{ + "status": "success", + "message": null, + "version": "2.2.22-r7deb380", + "result": [ + { + "status": "CREATED", + "created": "2018-11-02T10:08:54.000-05:00", + "createdBy": "username", + "description": "New directory created at https://api.sd2e.org/files/v2/media/system/tacc-globalfs-username//new-fir" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-11-30T11:22:01.000-06:00", + "createdBy": "username", + "description": "All permissions revoked" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-11-30T11:45:58.000-06:00", + "createdBy": "username", + "description": "All permissions revoked" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-11-30T11:46:53.000-06:00", + "createdBy": "username", + "description": "All permissions revoked" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-11-30T12:01:06.000-06:00", + "createdBy": "username", + "description": "All permissions revoked" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-12-03T10:09:19.000-06:00", + "createdBy": "username", + "description": "All permissions revoked for colabbo" + }, + { + "status": "PERMISSION_GRANT", + "created": "2018-12-03T10:09:19.000-06:00", + "createdBy": "username", + "description": "OWNER permission granted to colabbo" + }, + { + "status": "PERMISSION_REVOKE", + "created": "2018-12-03T10:11:07.000-06:00", + "createdBy": "username", + "description": "All permissions revoked for collab" + }, + { + "status": "PERMISSION_GRANT", + "created": "2018-12-03T10:11:07.000-06:00", + "createdBy": "username", + "description": "OWNER permission granted to collab" + } + ] +}
Implement files_history **Is your feature request related to a problem? Please describe.** Part of the changes proposed for release v3.0.0 of `TACC-Cloud/agave-cli` **Describe the solution you'd like** Implement method that list the history of events for a specific file/folder.
0.0
7353677359e0ceb6d361e442bb04e7ddab7422ea
[ "tests/files-history_test.py::TestMockServer::test_files_history" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-12-04 21:06:13+00:00
mit
730
TACC__agavepy-62
diff --git a/Makefile b/Makefile index 174afb5..43a069c 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ shell: build # Start a shell inside the build environment. $(DOCKER_RUN_AGAVECLI) bash tests: - pytest -v --cache-clear tests/ + pytest -vv --cache-clear tests/ tests-py2: - python2 -m pytest -v tests + python2 -m pytest -vv tests diff --git a/agavepy/agave.py b/agavepy/agave.py index ca599ce..a0d4b3a 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -568,7 +568,7 @@ class Agave(object): if cache_dir is None: cache_dir = os.path.expanduser("~/.agave") - save_config(cache_dir, current_context) + save_config(cache_dir, current_context, self.client_name) def list_tenants(self, tenantsurl="https://api.tacc.utexas.edu/tenants"): @@ -609,6 +609,8 @@ class Agave(object): self.api_key, self.api_secret = clients_create( self.username, client_name, description, tenant_url) + # Save client name upon successful return of function. + self.client_name = client_name def clients_list(self): diff --git a/agavepy/utils/cachedir_helpers.py b/agavepy/utils/cachedir_helpers.py index 2f0af07..0345f30 100644 --- a/agavepy/utils/cachedir_helpers.py +++ b/agavepy/utils/cachedir_helpers.py @@ -6,6 +6,8 @@ import json import requests import sys import os +from collections import defaultdict + def make_cache_dir(cache_dir): @@ -23,7 +25,7 @@ def make_cache_dir(cache_dir): os.makedirs(cache_dir) -def save_config(cache_dir, current_context): +def save_config(cache_dir, current_context, client_name): """ Initiate an Agave Tenant Create or switch the current context to a specified Agave tenant. @@ -40,20 +42,35 @@ def save_config(cache_dir, current_context): For example: { "current": { - "access_token": "some-token", - ... - "username": "user" - }, - "tenants": { - "3dem": { - "access_token": "other-token", + "client-name": { + "access_token": "some-token", ... "username": "user" + } + }, + "sessions": { + "3dem": { + "username": { + "client-name": { + "access_token": "other-token", + ... + "username": "user" + }, + "client-name-2": { + "access_token": "some-other-token", + ... + "username" + } + } }, "sd2e": { - "acces_token": "some-token", - ... - "usernamer":user" + "username": { + "client-name": { + "acces_token": "some-token", + ... + "usernamer":user" + } + } } } } @@ -73,33 +90,52 @@ def save_config(cache_dir, current_context): with open(config_file, "r") as f: agave_context = json.load(f) else: - agave_context = dict() + agave_context = defaultdict(lambda: defaultdict(dict)) # Set up ~/.agave/config.json # We are saving configurations for the first time so we have to set # "current" and add it to "tenants". - if "tenants" not in agave_context: - # No existing tenants, so we just add the current context. - agave_context["current"] = current_context + if "sessions" not in agave_context: + # No current session, so we just add the current context. + agave_context["current"][client_name] = current_context - # Create an empty dictionary for "tenants" key. - agave_context["tenants"] = dict() # Save current tenant context. - agave_context["tenants"][current_context["tenantid"]] = agave_context["current"] - # "tenants" already exist so we just have to put the current context - # back in. + tenant_id = current_context["tenantid"] + username = current_context["username"] + + # Initialize fields as appropiate. + # Will save the saved current context, this already includes the client + # name. + agave_context["sessions"][tenant_id][username] = \ + agave_context["current"] + # There are existing sessions already so we just have to properly save the + # current context. else: - # Save current tenant context. - agave_context["tenants"][agave_context["current"]["tenantid"]] = agave_context["current"] + # Save current tenant context to sessions. + # The saved client should be the only entry in the current session. + saved_client = list(agave_context["current"].keys())[0] + tenant_id = agave_context["current"][saved_client]["tenantid"] + username = agave_context["current"][saved_client]["username"] + + # Initialized sessions fields if they don't already exist. + if tenant_id not in agave_context["sessions"].keys(): + agave_context["sessions"][tenant_id] = dict() + if username not in agave_context["sessions"][tenant_id].keys(): + agave_context["sessions"][tenant_id][username] = dict() + + # Save current context on sessions. + agave_context["sessions"][tenant_id][username][saved_client] = \ + agave_context["current"][saved_client] - # Save current_context as such. - agave_context["current"] = current_context + # Save "current_context". + del agave_context["current"][saved_client] + agave_context["current"][client_name] = current_context # Save data to cache dir files. with open(config_file, "w") as f: - json.dump(agave_context, f, sort_keys=True, indent=4) + json.dump(agave_context, f, indent=4) with open(current_file, "w") as f: - json.dump(agave_context["current"], f, sort_keys=True) + json.dump(agave_context["current"][client_name], f, sort_keys=True)
TACC/agavepy
08b6bb088b95b0c71c9404b220df1b9d0915b770
diff --git a/tests/sample_responses/sample-config.json b/tests/sample_responses/sample-config.json index cfb1ae4..5bf44c6 100644 --- a/tests/sample_responses/sample-config.json +++ b/tests/sample_responses/sample-config.json @@ -1,43 +1,53 @@ { - "current": { - "access_token": "", - "apikey": "", - "apisecret": "", - "baseurl": "https://api.sd2e.org", - "created_at": "", - "devurl": "", - "expires_at": "", - "expires_in": "", - "refresh_token": "", - "tenantid": "sd2e", - "username": "" - }, - "tenants": { - "irec": { - "access_token": "", - "apikey": "", - "apisecret": "", - "baseurl": "https://irec.tenants.prod.tacc.cloud", - "created_at": "", - "devurl": "", - "expires_at": "", - "expires_in": "", - "refresh_token": "", - "tenantid": "irec", - "username": "" + "current": { + "client-3": { + "tenantid": "sd2e", + "baseurl": "https://api.sd2e.org", + "devurl": "", + "apisecret": "", + "apikey": "", + "username": "user-3", + "access_token": "", + "refresh_token": "", + "created_at": "", + "expires_in": "", + "expires_at": "" + } }, - "sd2e": { - "access_token": "", - "apikey": "", - "apisecret": "", - "baseurl": "https://api.sd2e.org", - "created_at": "", - "devurl": "", - "expires_at": "", - "expires_in": "", - "refresh_token": "", - "tenantid": "sd2e", - "username": "" + "sessions": { + "sd2e": { + "user-1": { + "client-1": { + "tenantid": "sd2e", + "baseurl": "https://api.sd2e.org", + "devurl": "", + "apisecret": "", + "apikey": "", + "username": "user-1", + "access_token": "", + "refresh_token": "", + "created_at": "", + "expires_in": "", + "expires_at": "" + } + } + }, + "tacc.prod": { + "user-2": { + "client-2": { + "tenantid": "tacc.prod", + "baseurl": "https://api.tacc.utexas.edu", + "devurl": "", + "apisecret": "", + "apikey": "", + "username": "user-2", + "access_token": "", + "refresh_token": "", + "created_at": "", + "expires_in": "", + "expires_at": "" + } + } + } } - } } diff --git a/tests/save_configs_test.py b/tests/save_configs_test.py index bb95c65..8b95504 100644 --- a/tests/save_configs_test.py +++ b/tests/save_configs_test.py @@ -49,10 +49,18 @@ class TestSaveConfigs: cache_dir = tempfile.mkdtemp() a = Agave(tenant_id="sd2e") + a.client_name = "client-1" + a.username = "user-1" a.save_configs(cache_dir) - b = Agave(tenant_id="irec") + + b = Agave(tenant_id="tacc.prod") + b.client_name = "client-2" + b.username = "user-2" b.save_configs(cache_dir) + c = Agave(tenant_id="sd2e") + c.client_name = "client-3" + c.username = "user-3" c.save_configs(cache_dir) with open("{}/config.json".format(cache_dir), "r") as f:
Improve the way the users interact with multiple tenants/users/clients Issue #53 addresses a new format to store credentials. The introduced format makes it possible to switch between multiple tenants. However, users who have admin capabilities in agave may have multiple accounts and/or may have different oauth clients for different purposes. ## Proposed changes Currently the configurations file has entries organized by tenant id. To allow for indexing by tenant, username, and client name. The new format could be something like this: ``` { "current": { "client-1" : { // the configurations include tenant and user info already. } }, "sessions": { "sd2e": { "admin": { "client-1": { ... }, "client-2": { ... } }, "user1":{ "client-1": { ... }, "client-2": { ... } } }, "tacc": { "admin": { "client-1": { ... } } } } } ```
0.0
08b6bb088b95b0c71c9404b220df1b9d0915b770
[ "tests/save_configs_test.py::TestSaveConfigs::test_save_configs" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-09-28 17:07:11+00:00
mit
731
TACC__agavepy-63
diff --git a/agavepy/agave.py b/agavepy/agave.py index a0d4b3a..0de4ff9 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -22,7 +22,7 @@ import requests from agavepy.tenants import tenant_list from agavepy.clients import clients_create, clients_list from agavepy.tokens import token_create -from agavepy.utils import save_config +from agavepy.utils import load_config, save_config import sys sys.path.insert(0, os.path.dirname(__file__)) @@ -234,34 +234,6 @@ class Agave(object): setattr(self, attr, value) - # The following sectionsets tenant ID (tenant_id) and tenant url - # (api_server). - # Neither tenant ID nor tenant url are set. - if self.tenant_id is None and self.api_server is None: - tenants = self.list_tenants(tenantsurl="https://api.tacc.utexas.edu/tenants") - value = input("\nPlease specify the ID for the tenant you wish to interact with: ") - self.tenant_id = tenants[value]["id"] - tenant_url = tenants[value]["url"] - if tenant_url[-1] == '/': - tenant_url = tenant_url[:-1] - self.api_server = tenant_url - # Tenant ID was not set. - elif self.tenant_id is None and self.api_server is not None: - tenants = tenant_list(tenantsurl="https://api.tacc.utexas.edu/tenants") - - for _, tenant in tenants.items(): - if self.api_server in tenant["url"]: - self.tenant_id = tenant["id"] - # Tenant url was not set. - elif self.api_server is None and self.tenant_id is not None: - tenants = tenant_list(tenantsurl="https://api.tacc.utexas.edu/tenants") - - tenant_url = tenants[self.tenant_id]["url"] - if tenant_url[-1] == '/': - tenant_url = tenant_url[:-1] - self.api_server = tenant_url - - if self.resources is None: self.resources = load_resource(self.api_server) self.host = urllib.parse.urlsplit(self.api_server).netloc @@ -536,6 +508,40 @@ class Agave(object): return list(set(base)) + def init(self): + """ Initilize a session + + Initialize a session by setting parameters refering to the tenant you + wish to interact with. + """ + # The following sectionsets tenant ID (tenant_id) and tenant url + # (api_server). + # Neither tenant ID nor tenant url are set. + if self.tenant_id is None and self.api_server is None: + tenants = self.list_tenants(tenantsurl="https://api.tacc.utexas.edu/tenants") + value = input("\nPlease specify the ID for the tenant you wish to interact with: ") + self.tenant_id = tenants[value]["id"] + tenant_url = tenants[value]["url"] + if tenant_url[-1] == '/': + tenant_url = tenant_url[:-1] + self.api_server = tenant_url + # Tenant ID was not set. + elif self.tenant_id is None and self.api_server is not None: + tenants = tenant_list(tenantsurl="https://api.tacc.utexas.edu/tenants") + + for _, tenant in tenants.items(): + if self.api_server in tenant["url"]: + self.tenant_id = tenant["id"] + # Tenant url was not set. + elif self.api_server is None and self.tenant_id is not None: + tenants = tenant_list(tenantsurl="https://api.tacc.utexas.edu/tenants") + + tenant_url = tenants[self.tenant_id]["url"] + if tenant_url[-1] == '/': + tenant_url = tenant_url[:-1] + self.api_server = tenant_url + + def save_configs(self, cache_dir=None): """ Save configs @@ -547,6 +553,12 @@ class Agave(object): cache_dir: string (default: None) If no cache_dir is passed it will default to ~/.agave. """ + # Check that client name is set. + if self.client_name is None or isinstance(self.client_name, Resource): + print( + "You must set the client_name attribute before saving configurations with this method") + return + current_context = { "tenantid": self.tenant_id, "baseurl": self.api_server, @@ -571,6 +583,36 @@ class Agave(object): save_config(cache_dir, current_context, self.client_name) + def load_configs(self, cache_dir=None, tenant_id=None, username=None, client_name=None): + """ Load session cntext from configuration file + + PARAMETERS + ---------- + cache_dir: string (default: None) + Path to directory for storing sessions. It defaults to "~/.agave". + username: string (default: None) + client_name: string (default: None) + Name of oauth client. + """ + # Set cache dir. + if cache_dir is None: + cache_dir = os.path.expanduser("~/.agave") + + session_context = load_config(cache_dir, tenant_id, username, client_name) + + self.client_name = list(session_context)[0] + self.tenant_id = session_context[self.client_name]["tenantid"] + self.api_server = session_context[self.client_name]["baseurl"] + self.api_secret = session_context[self.client_name]["apisecret"] + self.api_key = session_context[self.client_name]["apikey"] + self.username = session_context[self.client_name]["username"] + self.token = session_context[self.client_name]["access_token"] + self.refresh_token = session_context[self.client_name]["refresh_token"] + self.created_at = session_context[self.client_name]["created_at"] + self.expires_in = session_context[self.client_name]["expires_in"] + self.expires_at = session_context[self.client_name]["expires_at"] + + def list_tenants(self, tenantsurl="https://api.tacc.utexas.edu/tenants"): """ List Agave tenants diff --git a/agavepy/utils/__init__.py b/agavepy/utils/__init__.py index 0aff1bb..85ff707 100644 --- a/agavepy/utils/__init__.py +++ b/agavepy/utils/__init__.py @@ -1,2 +1,3 @@ -from .cachedir_helpers import save_config from .response_handlers import handle_bad_response_status_code +from .load_configs import load_config +from .save_configs import save_config diff --git a/agavepy/utils/load_configs.py b/agavepy/utils/load_configs.py new file mode 100644 index 0000000..43d97a3 --- /dev/null +++ b/agavepy/utils/load_configs.py @@ -0,0 +1,45 @@ +""" + load_configs.py +""" +import errno +import json +import os + + + +def load_config(cache_dir, tenant_id, username, client_name): + """ Load configurations from file + + Load configuration information from file, if it exists. + These function will look for the file config.json to restore a session. + + PARAMETERS + ---------- + cache_dir: string + Path to store session configuration. + tenant_id: string + username: string + client_name: string + + RETURNS + ------- + current_context: dict + Dictionary with client name as key and session context as value. + """ + # Configuration info will be store by default in these files. + config_file = "{}/config.json".format(cache_dir) + + # Read in configuration from cache dir if it exist, raise an exception. + if os.path.isfile(config_file): + with open(config_file, "r") as f: + agave_context = json.load(f) + else: + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), config_file) + + # Return the current session context if no extra parameters are passed. + if tenant_id is None or username is None or client_name is None: + return agave_context["current"] + else: + print(agave_context) + return agave_context["sessions"][tenant_id][username] diff --git a/agavepy/utils/cachedir_helpers.py b/agavepy/utils/save_configs.py similarity index 85% rename from agavepy/utils/cachedir_helpers.py rename to agavepy/utils/save_configs.py index 0345f30..d94d0b8 100644 --- a/agavepy/utils/cachedir_helpers.py +++ b/agavepy/utils/save_configs.py @@ -1,5 +1,5 @@ """ - cachedir_helpers.py + save_configs.py """ from __future__ import print_function import json @@ -26,18 +26,18 @@ def make_cache_dir(cache_dir): def save_config(cache_dir, current_context, client_name): - """ Initiate an Agave Tenant + """ Save session configurations to file. - Create or switch the current context to a specified Agave tenant. - The current context along with all previous used are stored in a - local database (arguments.agavedb). + Create or switch the current session context. The ~/.agave/config.json file will have the following format: * "current" will specify the configuration to be used for the current - session. The contents of this section should match those of - ~/.agave/current. - * "tenants" will have one or more keys, and each key will have a json - object related to it. Each key will correspond to a tenant id. + session. The contents of this section should include a nested json + object wich will hold all session configurations. It matches the + information of ~/.agave/current. + * "sessions" will be a series of nested json objects. Each session + configuration will be indexed by tenant id, user name, and client name, + respectively. For example: { @@ -77,6 +77,12 @@ def save_config(cache_dir, current_context, client_name): PARAMETERS ---------- + cache_dir: string + Path to store session configuration. + current_context: dict + Session context. + client_name: string + Name of oauth client being used in the current session. """ # Get location to store configuration. make_cache_dir(cache_dir)
TACC/agavepy
720e84f6df4d06c91dd7f1606c44e2a01870a530
diff --git a/tests/save_configs_test.py b/tests/configs_test.py similarity index 52% rename from tests/save_configs_test.py rename to tests/configs_test.py index 8b95504..9265847 100644 --- a/tests/save_configs_test.py +++ b/tests/configs_test.py @@ -1,7 +1,7 @@ """ - save_configs_test.py + configs_test.py -Test save configuration function. +Test save and load configuration function. """ import pytest import json @@ -49,16 +49,19 @@ class TestSaveConfigs: cache_dir = tempfile.mkdtemp() a = Agave(tenant_id="sd2e") + a.init() a.client_name = "client-1" a.username = "user-1" a.save_configs(cache_dir) b = Agave(tenant_id="tacc.prod") + b.init() b.client_name = "client-2" b.username = "user-2" b.save_configs(cache_dir) c = Agave(tenant_id="sd2e") + c.init() c.client_name = "client-3" c.username = "user-3" c.save_configs(cache_dir) @@ -72,3 +75,51 @@ class TestSaveConfigs: assert config == sample_config finally: shutil.rmtree(cache_dir) + + + @patch("agavepy.tenants.tenants.get_tenants") + def test_load_configs(self, mock_get_tenants): + """ Test load_configs function + """ + try: + # create a tmp dir and use it as a cache dir. + cache_dir = tempfile.mkdtemp() + # Save sample configurations to cache dir. + with open("{}/config.json".format(cache_dir), "w") as f: + json.dump(sample_config, f, indent=4) + + ag = Agave() + ag.load_configs(cache_dir=cache_dir) + + sample_client = list(sample_config["current"].keys())[0] + assert ag.client_name == sample_client + assert ag.tenant_id == sample_config["current"][sample_client]["tenantid"] + assert ag.username == sample_config["current"][sample_client]["username"] + + finally: + shutil.rmtree(cache_dir) + + + @patch("agavepy.tenants.tenants.get_tenants") + def test_load_configs_specify_session(self, mock_get_tenants): + """ Test load_configs function + + Load a specific session from a configurations file. + """ + try: + # create a tmp dir and use it as a cache dir. + cache_dir = tempfile.mkdtemp() + # Save sample configurations to cache dir. + with open("{}/config.json".format(cache_dir), "w") as f: + json.dump(sample_config, f, indent=4) + + ag = Agave() + ag.load_configs(cache_dir=cache_dir, tenant_id="tacc.prod", + username="user-2", client_name="client-2") + + assert ag.client_name == "client-2" + assert ag.username == "user-2" + assert ag.tenant_id == "tacc.prod" + + finally: + shutil.rmtree(cache_dir) diff --git a/tests/initialize_agave_test.py b/tests/initialize_agave_test.py index 796703c..f8c1d57 100644 --- a/tests/initialize_agave_test.py +++ b/tests/initialize_agave_test.py @@ -41,6 +41,7 @@ class TestAgaveInitialization: # Instantiate Agave object making reference to local mock server. ag = Agave() + ag.init() assert ag.tenant_id == "sd2e" assert ag.api_server == "https://api.sd2e.org"
Improve way of restoring credentials from a configurations file Currently, `Agave` provides a restore method which reads configurations from the legacy `~/.agave/current` file. We need to implement a similar method that works with the changes proposed in issue #60.
0.0
720e84f6df4d06c91dd7f1606c44e2a01870a530
[ "tests/configs_test.py::TestSaveConfigs::test_save_configs", "tests/configs_test.py::TestSaveConfigs::test_load_configs", "tests/configs_test.py::TestSaveConfigs::test_load_configs_specify_session", "tests/initialize_agave_test.py::TestAgaveInitialization::test_Agave_init" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-09-28 21:01:46+00:00
mit
732
TACC__agavepy-87
diff --git a/agavepy/agave.py b/agavepy/agave.py index 53dfcb1..4eb104e 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -23,7 +23,8 @@ from agavepy.tenants import tenant_list from agavepy.clients import clients_create, clients_list from agavepy.tokens import token_create, refresh_token from agavepy.utils import load_config, save_config -from agavepy.files import files_delete, files_download, files_list, files_upload +from agavepy.files import (files_copy, files_delete, files_download, + files_list, files_upload) import sys @@ -727,6 +728,16 @@ class Agave(object): self.expires_at = token_data["expires_at"] + def files_copy(self, source, destination): + """ Copy a file from source to destination on a remote system + """ + # Check if tokens need to be refreshed. + self.refresh_tokens() + + # Make a copy of the file. + files_copy(self.api_server, self.token, source, destination) + + def files_delete(self, file_path): """ Delete a file from remote system """ diff --git a/agavepy/files/__init__.py b/agavepy/files/__init__.py index 6b72224..b7043b2 100644 --- a/agavepy/files/__init__.py +++ b/agavepy/files/__init__.py @@ -1,3 +1,4 @@ +from .copy import files_copy from .delete import files_delete from .download import files_download from .list import files_list diff --git a/agavepy/files/copy.py b/agavepy/files/copy.py new file mode 100644 index 0000000..af1475b --- /dev/null +++ b/agavepy/files/copy.py @@ -0,0 +1,29 @@ +""" + copy.py +""" +import requests +from .exceptions import AgaveFilesError +from ..utils import handle_bad_response_status_code + + +def files_copy(tenant_url, access_token, source, destination): + """ Copy files from remote to remote system + """ + # Set request url. + endpoint = "{0}/{1}/{2}".format(tenant_url, "files/v2/media/system", source) + + # Obtain file path from remote uri. "destination" should include the system + # name at the begining, get rid of it. + destination = '/'.join( destination.split('/')[1:] ) + + # Make request. + try: + data = {"action": "copy", "path": destination} + headers = {"Authorization":"Bearer {0}".format(access_token)} + params = {"pretty": "true"} + resp = requests.put(endpoint, headers=headers, data=data, params=params) + except Exception as err: + raise AgaveFilesError(err) + + # Handle bad status code. + handle_bad_response_status_code(resp) diff --git a/agavepy/files/list.py b/agavepy/files/list.py index 157db67..d922088 100644 --- a/agavepy/files/list.py +++ b/agavepy/files/list.py @@ -1,5 +1,5 @@ """ - files.py + list.py """ from __future__ import print_function, division import py diff --git a/agavepy/files/upload.py b/agavepy/files/upload.py index f4cbbdd..9369e57 100644 --- a/agavepy/files/upload.py +++ b/agavepy/files/upload.py @@ -1,5 +1,5 @@ """ - download.py + upload.py """ from __future__ import print_function import ntpath diff --git a/docs/docsite/files/files.rst b/docs/docsite/files/files.rst index 09e56e0..606a15c 100644 --- a/docs/docsite/files/files.rst +++ b/docs/docsite/files/files.rst @@ -72,7 +72,21 @@ the name ``cool_data.bin``. .. code-block:: pycon - >>> agave.files_upload("./important_data.ext", "tacc-globalfs-username/cool_data.bin") + >>> agave.files_upload("./important_data.ext", + "tacc-globalfs-username/cool_data.bin") + + +Make a copy of a file on a remote system +######################################## + +So now, you have a file called ``important_data.ext`` on your remote storage +system ``tacc-globalfs-username``. Let's make a copy of it: + + +.. code-block:: pycon + + >>> agave.files_copy("tacc-globalfs-username/important_data.ext", + "tacc-globalfs-username/important_data-copy.ext") Delete a file
TACC/agavepy
ef180a6180fb233687d27bf7f9f7391fe69cb6a9
diff --git a/tests/files_test.py b/tests/files_test.py index fe7ccdc..58168cf 100644 --- a/tests/files_test.py +++ b/tests/files_test.py @@ -122,6 +122,44 @@ class MockServerFilesEndpoints(BaseHTTPRequestHandler): self.wfile.write(json.dumps(sample_files_upload_response).encode()) + def do_PUT(self): + """ Mock endpoint to test files_copy method. + """ + # elements is a list of path elements, i.e., ["a", "b"] ~ "/a/b". + elements = self.send_headers() + if elements is None or not "/files/v2/media/system" in self.path: + self.send_response(400) + self.end_headers() + return + + # Submitted form data. + form = cgi.FieldStorage( + fp = self.rfile, + headers = self.headers, + environ = { + "REQUEST_METHOD": "POST", + "CONTENT_TYPE": self.headers["Content-Type"] + }) + + # Check access token is not empty. + token = self.headers.getheader("Authorization") + if token is None or token == "": + self.send_response(400) + self.end_headers() + return + + # Check request data. + if form.getvalue("action", "") == "": + self.send_response(400) + self.end_headers() + return + + if form.getvalue("path", "") == "": + self.send_response(400) + self.end_headers() + return + + def do_DELETE(self): """ Delete file """ @@ -256,3 +294,15 @@ class TestMockServer(MockServer): # rm dummy file in current working directory. if os.path.exists(tmp_file): os.remove(tmp_file) + + def test_files_copy(self): + """ test files copying from remote to remote + + The call to files_copy has no side effects on the host so the function + call should simply be able to return successfully. + """ + local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) + agave = Agave(api_server=local_uri) + agave.token = "mock-access-token" + + agave.files_copy("tacc-globalfs/file", "tacc-globalfs/file-copy")
Implement a method to copy files within remote systems Implement a method that allows the user to copy a file or directory from one remote system to another or within the same remote system.
0.0
ef180a6180fb233687d27bf7f9f7391fe69cb6a9
[ "tests/files_test.py::TestMockServer::test_files_copy" ]
[ "tests/files_test.py::TestMockServer::test_files_download", "tests/files_test.py::TestMockServer::test_files_upload", "tests/files_test.py::TestMockServer::test_files_delete" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-31 19:37:47+00:00
mit
733
TACC__agavepy-93
diff --git a/agavepy/agave.py b/agavepy/agave.py index a6cfa1e..6245c49 100644 --- a/agavepy/agave.py +++ b/agavepy/agave.py @@ -20,7 +20,7 @@ import dateutil.parser import requests from agavepy.tenants import tenant_list -from agavepy.clients import clients_create, clients_list +from agavepy.clients import clients_create, clients_delete, clients_list from agavepy.tokens import token_create, refresh_token from agavepy.utils import load_config, save_config from agavepy.files import (files_copy, files_delete, files_download, @@ -636,7 +636,7 @@ class Agave(object): def clients_create(self, client_name, description): - """ Create an Agave Oauth client + """ Create an Oauth client Save the api key and secret upon a successfull reuest to Agave. @@ -660,8 +660,31 @@ class Agave(object): self.client_name = client_name + def clients_delete(self, client_name=None): + """ Delete an Oauth client + + If no client_name is passed then we will try to delete the oauth client + stored in the current session. + """ + # Set username. + if self.username == "" or self.username is None: + self.username = input("API username: ") + + # If client_name is not set, then delete the current client, if it + # exists. + if client_name is None: + client_name = self.client_name + + # Delete client. + clients_delete(self.api_server, self.username, client_name) + + # If we deleted the current client, then zero out its secret and key. + if self.client_name == client_name: + self.api_key, self.api_secret = "", "" + + def clients_list(self): - """ List all Agave oauth clients + """ List all oauth clients """ # Set username. if self.username == "" or self.username is None: diff --git a/agavepy/clients/__init__.py b/agavepy/clients/__init__.py index aa93013..cfa3ed8 100644 --- a/agavepy/clients/__init__.py +++ b/agavepy/clients/__init__.py @@ -1,2 +1,3 @@ from .create import clients_create +from .delete import clients_delete from .list import clients_list diff --git a/agavepy/clients/create.py b/agavepy/clients/create.py index d52e59b..a83f668 100644 --- a/agavepy/clients/create.py +++ b/agavepy/clients/create.py @@ -5,17 +5,14 @@ Functions to create Agave oauth clients. """ from __future__ import print_function import getpass -import json import requests -import sys -from os import path from .exceptions import AgaveClientError from ..utils import handle_bad_response_status_code def clients_create(username, client_name, description, tenant_url): - """ Create an Agave client + """ Create an oauth client Make a request to Agave to create an oauth client. Returns the client's api key and secret as a tuple. diff --git a/agavepy/clients/delete.py b/agavepy/clients/delete.py new file mode 100644 index 0000000..b5b4ff7 --- /dev/null +++ b/agavepy/clients/delete.py @@ -0,0 +1,29 @@ +""" + clients.py +""" +import getpass +import requests +from .exceptions import AgaveClientError +from ..utils import handle_bad_response_status_code + + + +def clients_delete(tenant_url, username, client_name): + """ Create an Oauth client + """ + # Set the endpoint. + endpoint = "{}/clients/v2/{}".format(tenant_url, client_name) + + # Get user's password. + passwd = getpass.getpass(prompt="API password: ") + + # Make request. + try: + resp = requests.delete(endpoint, auth=(username, passwd)) + del passwd + except Exception as err: + del passwd + raise AgaveClientError(err) + + # Handle bad status code. + handle_bad_response_status_code(resp) diff --git a/agavepy/clients/list.py b/agavepy/clients/list.py index 140e9d4..eebd29e 100644 --- a/agavepy/clients/list.py +++ b/agavepy/clients/list.py @@ -5,10 +5,7 @@ Functions to list agave oauth clients. """ from __future__ import print_function import getpass -import json import requests -import sys -from os import path from .exceptions import AgaveClientError from ..utils import handle_bad_response_status_code diff --git a/docs/docsite/authentication/clients.rst b/docs/docsite/authentication/clients.rst index a7242cc..b3b4402 100644 --- a/docs/docsite/authentication/clients.rst +++ b/docs/docsite/authentication/clients.rst @@ -9,8 +9,8 @@ Creating a client ################# -Once you have soecified the tenant you wish to interact with :ref:`tenants` -we can go ahead and create an oauth client, which in turn we will use to biant +Once you have specified the tenant you wish to interact with :ref:`tenants` +we can go ahead and create an oauth client, which in turn we will use to obtain and refresh tokens. To create a client use the method ``clients_create``. @@ -47,3 +47,17 @@ To list all agave oauth clients registered for a given user, one can use the NAME DESCRIPTION client-name some description >>> + + +Deleting a client +################# + +If you want to delete an oauth client, you can do as such: + +.. code-block:: pycon + + >>> ag.clients_delete("some-client-name") + API password: + +If you don't pass a client name to ``clients_delete``, then the ``Agave`` +object will try to delete the oauth client in its current session.
TACC/agavepy
a06e776cda5d239750b0547dcb3e328a4f36e2a5
diff --git a/tests/clients_test.py b/tests/clients_test.py index da3563d..729f9ce 100644 --- a/tests/clients_test.py +++ b/tests/clients_test.py @@ -35,6 +35,13 @@ class MockServerClientEndpoints(BaseHTTPRequestHandler): def do_GET(self): """ Mock oauth client listing. """ + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + self.send_response(200) self.end_headers() self.wfile.write(json.dumps(sample_client_list_response).encode()) @@ -43,6 +50,13 @@ class MockServerClientEndpoints(BaseHTTPRequestHandler): def do_POST(self): """ Mock agave client creation """ + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + # Get request data. form = cgi.FieldStorage( fp = self.rfile, @@ -80,6 +94,20 @@ class MockServerClientEndpoints(BaseHTTPRequestHandler): self.wfile.write(json.dumps(sample_client_create_response).encode()) + def do_DELETE(self): + """ test clients_delete + """ + # Check that basic auth is used. + authorization = self.headers.get("Authorization") + if authorization == "" or authorization is None: + self.send_response(400) + self.end_headers() + return + + self.send_response(200) + self.end_headers() + + class TestMockServer(MockServer): """ Test client-related agave api endpoints @@ -120,6 +148,32 @@ class TestMockServer(MockServer): assert ag.api_secret == "some secret" + @patch("agavepy.agave.input") + @patch("agavepy.clients.delete.getpass.getpass") + def test_client_delete(self, mock_input, mock_pass): + """ Test clients_delete op + + Patch username and password from user to send a client create request + to mock server. + """ + # Patch username and password. + mock_input.return_value = "user" + mock_pass.return_value = "pass" + + # Instantiate Agave object making reference to local mock server. + local_uri = "http://localhost:{port}/".format(port=self.mock_server_port) + ag = Agave(api_server=local_uri) + ag.client_name = "client-name" + ag.api_key = "some api key" + ag.api_secret = "some secret" + + # Create client. + ag.clients_delete() + + assert ag.api_key == "" + assert ag.api_secret == "" + + @patch("agavepy.agave.input") @patch("agavepy.clients.list.getpass.getpass") def test_clients_list(self, mock_input, mock_pass, capfd):
Implement an oauth client delete method Write an document a method to delete oauth clients.
0.0
a06e776cda5d239750b0547dcb3e328a4f36e2a5
[ "tests/clients_test.py::TestMockServer::test_client_delete" ]
[ "tests/clients_test.py::TestMockServer::test_client_create", "tests/clients_test.py::TestMockServer::test_clients_list" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-11-07 18:04:40+00:00
mit
734
TDAmeritrade__stumpy-583
diff --git a/stumpy/aamp_motifs.py b/stumpy/aamp_motifs.py index 5fc6cb6..1e00c52 100644 --- a/stumpy/aamp_motifs.py +++ b/stumpy/aamp_motifs.py @@ -380,6 +380,8 @@ def aamp_match( if T_subseq_isfinite is None: T, T_subseq_isfinite = core.preprocess_non_normalized(T, m) + if len(T_subseq_isfinite.shape) == 1: + T_subseq_isfinite = T_subseq_isfinite[np.newaxis, :] D = np.empty((d, n - m + 1)) for i in range(d): diff --git a/stumpy/motifs.py b/stumpy/motifs.py index 213002c..5b59b14 100644 --- a/stumpy/motifs.py +++ b/stumpy/motifs.py @@ -445,6 +445,10 @@ def match( if M_T is None or Σ_T is None: # pragma: no cover T, M_T, Σ_T = core.preprocess(T, m) + if len(M_T.shape) == 1: + M_T = M_T[np.newaxis, :] + if len(Σ_T.shape) == 1: + Σ_T = Σ_T[np.newaxis, :] D = np.empty((d, n - m + 1)) for i in range(d):
TDAmeritrade/stumpy
d2884510304eea876bd05bf64cecc31f2fa07105
diff --git a/tests/test_aamp_motifs.py b/tests/test_aamp_motifs.py index b8325f5..006521f 100644 --- a/tests/test_aamp_motifs.py +++ b/tests/test_aamp_motifs.py @@ -2,7 +2,7 @@ import numpy as np import numpy.testing as npt import pytest -from stumpy import aamp_motifs, aamp_match +from stumpy import core, aamp_motifs, aamp_match import naive @@ -211,3 +211,31 @@ def test_aamp_match(Q, T): ) npt.assert_almost_equal(left, right) + + [email protected]("Q, T", test_data) +def test_aamp_match_T_subseq_isfinite(Q, T): + m = Q.shape[0] + excl_zone = int(np.ceil(m / 4)) + max_distance = 0.3 + T, T_subseq_isfinite = core.preprocess_non_normalized(T, len(Q)) + + for p in [1.0, 2.0, 3.0]: + left = naive_aamp_match( + Q, + T, + p=p, + excl_zone=excl_zone, + max_distance=max_distance, + ) + + right = aamp_match( + Q, + T, + T_subseq_isfinite, + p=p, + max_matches=None, + max_distance=max_distance, + ) + + npt.assert_almost_equal(left, right) diff --git a/tests/test_motifs.py b/tests/test_motifs.py index 07dbf2c..beef44e 100644 --- a/tests/test_motifs.py +++ b/tests/test_motifs.py @@ -235,3 +235,30 @@ def test_match(Q, T): ) npt.assert_almost_equal(left, right) + + [email protected]("Q, T", test_data) +def test_match_mean_stddev(Q, T): + m = Q.shape[0] + excl_zone = int(np.ceil(m / 4)) + max_distance = 0.3 + + left = naive_match( + Q, + T, + excl_zone, + max_distance=max_distance, + ) + + M_T, Σ_T = core.compute_mean_std(T, len(Q)) + + right = match( + Q, + T, + M_T, + Σ_T, + max_matches=None, + max_distance=lambda D: max_distance, # also test lambda functionality + ) + + npt.assert_almost_equal(left, right)
stumpy.match bug with parameters: Sliding mean and Sliding standard deviation ### Discussed in https://github.com/TDAmeritrade/stumpy/discussions/581 <div type='discussions-op-text'> <sup>Originally posted by **brunopinos31** March 31, 2022</sup> I have a bug when i try to use the stumpy.match function with parameters: Sliding mean and Sliding standard deviation. ![image](https://user-images.githubusercontent.com/92527271/161106075-5853222b-5073-4e57-8cda-e75d1abe171b.png) </div>
0.0
d2884510304eea876bd05bf64cecc31f2fa07105
[ "tests/test_motifs.py::test_match_mean_stddev[Q0-T0]", "tests/test_motifs.py::test_match_mean_stddev[Q1-T1]", "tests/test_motifs.py::test_match_mean_stddev[Q2-T2]" ]
[ "tests/test_aamp_motifs.py::test_aamp_motifs_one_motif", "tests/test_aamp_motifs.py::test_aamp_motifs_two_motifs", "tests/test_aamp_motifs.py::test_aamp_naive_match_exact", "tests/test_aamp_motifs.py::test_aamp_naive_match_exclusion_zone", "tests/test_aamp_motifs.py::test_aamp_match[Q0-T0]", "tests/test_aamp_motifs.py::test_aamp_match[Q1-T1]", "tests/test_aamp_motifs.py::test_aamp_match[Q2-T2]", "tests/test_aamp_motifs.py::test_aamp_match_T_subseq_isfinite[Q0-T0]", "tests/test_aamp_motifs.py::test_aamp_match_T_subseq_isfinite[Q1-T1]", "tests/test_aamp_motifs.py::test_aamp_match_T_subseq_isfinite[Q2-T2]", "tests/test_motifs.py::test_motifs_one_motif", "tests/test_motifs.py::test_motifs_two_motifs", "tests/test_motifs.py::test_motifs_max_matches", "tests/test_motifs.py::test_naive_match_exclusion_zone", "tests/test_motifs.py::test_match[Q0-T0]", "tests/test_motifs.py::test_match[Q1-T1]", "tests/test_motifs.py::test_match[Q2-T2]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-03-31 20:39:21+00:00
bsd-3-clause
735
TDAmeritrade__stumpy-892
diff --git a/stumpy/core.py b/stumpy/core.py index 57d05f9..3208859 100644 --- a/stumpy/core.py +++ b/stumpy/core.py @@ -1042,7 +1042,7 @@ def compute_mean_std(T, m): @njit( # "f8(i8, f8, f8, f8, f8, f8)", - fastmath=True + fastmath={"nsz", "arcp", "contract", "afn", "reassoc"} ) def _calculate_squared_distance( m, QT, μ_Q, σ_Q, M_T, Σ_T, Q_subseq_isconstant, T_subseq_isconstant @@ -1097,10 +1097,10 @@ def _calculate_squared_distance( elif Q_subseq_isconstant or T_subseq_isconstant: D_squared = m else: - denom = m * σ_Q * Σ_T + denom = (σ_Q * Σ_T) * m denom = max(denom, config.STUMPY_DENOM_THRESHOLD) - ρ = (QT - m * μ_Q * M_T) / denom + ρ = (QT - (μ_Q * M_T) * m) / denom ρ = min(ρ, 1.0) D_squared = np.abs(2 * m * (1.0 - ρ)) diff --git a/stumpy/gpu_stump.py b/stumpy/gpu_stump.py index d66283d..7f103b7 100644 --- a/stumpy/gpu_stump.py +++ b/stumpy/gpu_stump.py @@ -178,9 +178,9 @@ def _compute_and_update_PI_kernel( elif Q_subseq_isconstant[i] or T_subseq_isconstant[j]: p_norm = m else: - denom = m * σ_Q[i] * Σ_T[j] + denom = (σ_Q[i] * Σ_T[j]) * m denom = max(denom, config.STUMPY_DENOM_THRESHOLD) - ρ = (QT_out[i] - m * μ_Q[i] * M_T[j]) / denom + ρ = (QT_out[i] - (μ_Q[i] * M_T[j]) * m) / denom ρ = min(ρ, 1.0) p_norm = 2 * m * (1.0 - ρ)
TDAmeritrade/stumpy
900b10cda4ebeed5cc90d3b4cd1972e6ae18ea10
diff --git a/tests/test_precision.py b/tests/test_precision.py index c819c7e..c879850 100644 --- a/tests/test_precision.py +++ b/tests/test_precision.py @@ -1,10 +1,22 @@ +import functools +from unittest.mock import patch + import naive import numpy as np import numpy.testing as npt +import pytest +from numba import cuda import stumpy from stumpy import config, core +try: + from numba.errors import NumbaPerformanceWarning +except ModuleNotFoundError: + from numba.core.errors import NumbaPerformanceWarning + +TEST_THREADS_PER_BLOCK = 10 + def test_mpdist_snippets_s(): # This test function raises an error if the distance between @@ -55,3 +67,134 @@ def test_distace_profile(): ) npt.assert_almost_equal(D_ref, D_comp) + + +def test_calculate_squared_distance(): + # This test function raises an error if the distance between a subsequence + # and another does not satisfy the symmetry property. + seed = 332 + np.random.seed(seed) + T = np.random.uniform(-1000.0, 1000.0, [64]) + m = 3 + + T_subseq_isconstant = core.rolling_isconstant(T, m) + M_T, Σ_T = core.compute_mean_std(T, m) + + n = len(T) + k = n - m + 1 + for i in range(k): + for j in range(k): + QT_i = core._sliding_dot_product(T[i : i + m], T) + dist_ij = core._calculate_squared_distance( + m, + QT_i[j], + M_T[i], + Σ_T[i], + M_T[j], + Σ_T[j], + T_subseq_isconstant[i], + T_subseq_isconstant[j], + ) + + QT_j = core._sliding_dot_product(T[j : j + m], T) + dist_ji = core._calculate_squared_distance( + m, + QT_j[i], + M_T[j], + Σ_T[j], + M_T[i], + Σ_T[i], + T_subseq_isconstant[j], + T_subseq_isconstant[i], + ) + + comp = dist_ij - dist_ji + ref = 0.0 + + npt.assert_almost_equal(ref, comp, decimal=14) + + +def test_snippets(): + # This test function raises an error if there is a considerable loss of precision + # that violates the symmetry property of a distance measure. + m = 10 + k = 3 + s = 3 + seed = 332 + np.random.seed(seed) + T = np.random.uniform(-1000.0, 1000.0, [64]) + + isconstant_custom_func = functools.partial( + naive.isconstant_func_stddev_threshold, quantile_threshold=0.05 + ) + ( + ref_snippets, + ref_indices, + ref_profiles, + ref_fractions, + ref_areas, + ref_regimes, + ) = naive.mpdist_snippets( + T, m, k, s=s, mpdist_T_subseq_isconstant=isconstant_custom_func + ) + ( + cmp_snippets, + cmp_indices, + cmp_profiles, + cmp_fractions, + cmp_areas, + cmp_regimes, + ) = stumpy.snippets(T, m, k, s=s, mpdist_T_subseq_isconstant=isconstant_custom_func) + + npt.assert_almost_equal( + ref_snippets, cmp_snippets, decimal=config.STUMPY_TEST_PRECISION + ) + npt.assert_almost_equal( + ref_indices, cmp_indices, decimal=config.STUMPY_TEST_PRECISION + ) + npt.assert_almost_equal( + ref_profiles, cmp_profiles, decimal=config.STUMPY_TEST_PRECISION + ) + npt.assert_almost_equal( + ref_fractions, cmp_fractions, decimal=config.STUMPY_TEST_PRECISION + ) + npt.assert_almost_equal(ref_areas, cmp_areas, decimal=config.STUMPY_TEST_PRECISION) + npt.assert_almost_equal(ref_regimes, cmp_regimes) + + [email protected]("ignore", category=NumbaPerformanceWarning) +@patch("stumpy.config.STUMPY_THREADS_PER_BLOCK", TEST_THREADS_PER_BLOCK) +def test_distance_symmetry_property_in_gpu(): + if not cuda.is_available(): # pragma: no cover + pytest.skip("Skipping Tests No GPUs Available") + + # This test function raises an error if the distance between a subsequence + # and another one does not satisfy the symmetry property. + seed = 332 + np.random.seed(seed) + T = np.random.uniform(-1000.0, 1000.0, [64]) + m = 3 + + i, j = 2, 10 + # M_T, Σ_T = core.compute_mean_std(T, m) + # Σ_T[i] is `650.912209452633` + # Σ_T[j] is `722.0717285148525` + + # This test raises an error if arithmetic operation in ... + # ... `gpu_stump._compute_and_update_PI_kernel` does not + # generates the same result if values of variable for mean and std + # are swapped. + + T_A = T[i : i + m] + T_B = T[j : j + m] + + mp_AB = stumpy.gpu_stump(T_A, m, T_B) + mp_BA = stumpy.gpu_stump(T_B, m, T_A) + + d_ij = mp_AB[0, 0] + d_ji = mp_BA[0, 0] + + comp = d_ij - d_ji + ref = 0.0 + + npt.assert_almost_equal(comp, ref, decimal=15)
Snippets Unit Test Assertion Failure It appears that snippets unit tests are failing [here](https://github.com/TDAmeritrade/stumpy/actions/runs/5569517430/jobs/10172918123) and it's not clear if it may be related to the snippet comment in #828
0.0
900b10cda4ebeed5cc90d3b4cd1972e6ae18ea10
[ "tests/test_precision.py::test_snippets" ]
[ "tests/test_precision.py::test_mpdist_snippets_s", "tests/test_precision.py::test_distace_profile", "tests/test_precision.py::test_calculate_squared_distance" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-08-01 05:42:11+00:00
mit
736
TRoboto__Maha-103
diff --git a/maha/cleaners/functions/remove_fn.py b/maha/cleaners/functions/remove_fn.py index 1385f34..47786b8 100644 --- a/maha/cleaners/functions/remove_fn.py +++ b/maha/cleaners/functions/remove_fn.py @@ -3,6 +3,8 @@ Functions that operate on a string and remove certain characters. """ from __future__ import annotations +from maha.rexy import non_capturing_group + __all__ = [ "remove", "remove_strings", @@ -92,7 +94,7 @@ def remove( emojis: bool = False, use_space: bool = True, custom_strings: list[str] | str | None = None, - custom_expressions: ExpressionGroup | Expression | str | None = None, + custom_expressions: ExpressionGroup | Expression | list[str] | str | None = None, ): """Removes certain characters from the given text. @@ -168,7 +170,7 @@ def remove( for more information, by default True custom_strings: Include any other string(s), by default None - custom_expressions: Union[:class:`~.ExpressionGroup`, :class:`~.Expression`, str] + custom_expressions: Include any other regular expression expressions, by default None Returns @@ -213,11 +215,15 @@ def remove( if isinstance(custom_strings, str): custom_strings = [custom_strings] + chars_to_remove.extend(custom_strings) + + # expressions to remove if isinstance(custom_expressions, str): custom_expressions = Expression(custom_expressions) - chars_to_remove.extend(custom_strings) - # expressions to remove + elif isinstance(custom_expressions, list): + custom_expressions = Expression(non_capturing_group(*custom_expressions)) + expressions_to_remove = ExpressionGroup(custom_expressions) # Since each argument has the same name as the corresponding constant
TRoboto/Maha
8908cd383ec4af6805be25bfe04ec3e4df6f7939
diff --git a/tests/cleaners/test_remove.py b/tests/cleaners/test_remove.py index df184a8..071f5a6 100644 --- a/tests/cleaners/test_remove.py +++ b/tests/cleaners/test_remove.py @@ -823,3 +823,12 @@ def test_remove_arabic_letter_dots_with_edge_case(input: str, expected: str): def test_remove_arabic_letter_dots_general(input: str, expected: str): assert remove_arabic_letter_dots(input) == expected + + +def test_remove_list_input(simple_text_input: str): + list_ = ["بِسْمِ", "the", "ال(?=ر)"] + processed_text = remove(text=simple_text_input, custom_expressions=list_) + assert ( + processed_text + == "1. ،اللَّهِ رَّحْمَٰنِ رَّحِيمِ In name of Allah,Most Gracious, Most Merciful." + )
Adding a list of strings to cleaner functions ### What problem are you trying to solve? Enhance the cleaners functions to take a list of strings as input if needed. ### Examples (if relevant) ```py >>> from maha.cleaners.functions import remove >>> text = "من اليوم سوف ينتقل صديقي منور من المدينة المنورة وعنوانه الجديد هو الرياض" >>>remove(text, custom_expressions = [r"\bمن\b", r"\bعن\b") 'اليوم سوف ينتقل صديقي منور المدينة المنورة وعنوانه الجديد هو الرياض' ``` ### Definition of Done - It must adhere to the coding style used in the defined cleaner functions. - The implementation should cover most use cases. - Adding tests
0.0
8908cd383ec4af6805be25bfe04ec3e4df6f7939
[ "tests/cleaners/test_remove.py::test_remove_list_input" ]
[ "tests/cleaners/test_remove.py::test_remove_with_arabic", "tests/cleaners/test_remove.py::test_remove_with_english", "tests/cleaners/test_remove.py::test_remove_english", "tests/cleaners/test_remove.py::test_remove_with_false_use_space", "tests/cleaners/test_remove.py::test_remove_with_random_true_inputs", "tests/cleaners/test_remove.py::test_remove_with_arabic_letters", "tests/cleaners/test_remove.py::test_remove_with_english_letters", "tests/cleaners/test_remove.py::test_remove_with_english_small_letters", "tests/cleaners/test_remove.py::test_remove_with_english_capital_letters", "tests/cleaners/test_remove.py::test_remove_with_english_capital_letters_false_use_space", "tests/cleaners/test_remove.py::test_remove_with_numbers", "tests/cleaners/test_remove.py::test_remove_numbers", "tests/cleaners/test_remove.py::test_remove_with_harakat", "tests/cleaners/test_remove.py::test_remove_harakat", "tests/cleaners/test_remove.py::test_remove_all_harakat", "tests/cleaners/test_remove.py::test_remove_with_punctuations", "tests/cleaners/test_remove.py::test_remove_punctuations", "tests/cleaners/test_remove.py::test_remove_with_arabic_numbers", "tests/cleaners/test_remove.py::test_remove_with_english_numbers", "tests/cleaners/test_remove.py::test_remove_with_arabic_punctuations", "tests/cleaners/test_remove.py::test_remove_with_english_punctuations", "tests/cleaners/test_remove.py::test_remove_with_custom_character", "tests/cleaners/test_remove.py::test_remove_with_custom_characters_not_found[test]", "tests/cleaners/test_remove.py::test_remove_with_custom_characters_not_found[strings1]", "tests/cleaners/test_remove.py::test_remove_with_custom_patterns[[A-Za-z]]", "tests/cleaners/test_remove.py::test_remove_with_tatweel", "tests/cleaners/test_remove.py::test_remove_tatweel", "tests/cleaners/test_remove.py::test_reduce_repeated_substring_default", "tests/cleaners/test_remove.py::test_reduce_repeated_substring_raises_valueerror", "tests/cleaners/test_remove.py::test_reduce_repeated_substring[h", "tests/cleaners/test_remove.py::test_reduce_repeated_substring[heheh", "tests/cleaners/test_remove.py::test_reduce_repeated_substring[\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647\\u0647-\\u0647\\u0647-3-2]", "tests/cleaners/test_remove.py::test_reduce_repeated_substring[heeellloooooooo-helo-2-1]", "tests/cleaners/test_remove.py::test_reduce_repeated_substring[heeelloooooooo-hello-3-1]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[\\u0648\\u0644\\u0642\\u062f", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#\\u0627\\u0644\\u0648\\u0631\\u062f", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[\\u064a\\u0627", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[\\u0623\\u0643\\u062b\\u0631", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[\\u064a\\u062c\\u0628", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[.#\\u0643\\u0631\\u0629", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[@#\\u0628\\u0631\\u0645\\u062c\\u0629-@#\\u0628\\u0631\\u0645\\u062c\\u0629]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[_#\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629-_#\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[&#\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645-&#\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#11111\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647-11111\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#\\u0645\\u0633\\u0623\\u0644\\u0629_\\u0631\\u0642\\u0645_1111-\\u0645\\u0633\\u0623\\u0644\\u0629_\\u0631\\u0642\\u0645_1111]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#Hello-Hello]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#\\u0645\\u0631\\u062d\\u0628\\u0627-\\u0645\\u0631\\u062d\\u0628\\u0627]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[#\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628-\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[&#\\u0631\\u0645\\u0636\\u0627\\u0646-&#\\u0631\\u0645\\u0636\\u0627\\u0646]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[_#\\u0627\\u0644\\u0639\\u064a\\u062f-_#\\u0627\\u0644\\u0639\\u064a\\u062f]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[^#\\u0627\\u0644\\u062a\\u0639\\u0644\\u064a\\u0645_\\u0644\\u0644\\u062c\\u0645\\u064a\\u0639-^\\u0627\\u0644\\u062a\\u0639\\u0644\\u064a\\u0645_\\u0644\\u0644\\u062c\\u0645\\u064a\\u0639]", "tests/cleaners/test_remove.py::test_remove_hash_keep_tag[:#\\u0627\\u0644\\u0631\\u064a\\u0627\\u0636\\u0629-:\\u0627\\u0644\\u0631\\u064a\\u0627\\u0636\\u0629]", "tests/cleaners/test_remove.py::test_remove_with_ligtures", "tests/cleaners/test_remove.py::test_remove_with_hashtags_simple", "tests/cleaners/test_remove.py::test_remove_with_hashtags_with_arabic", "tests/cleaners/test_remove.py::test_remove_with_hashtags[test-test]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#test-]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642-]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[test", "tests/cleaners/test_remove.py::test_remove_with_hashtags[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#hashtag_start", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#hashtag", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#\\u0647\\u0627\\u064a\\u0634\\u062a\\u0627\\u0642hashtag", "tests/cleaners/test_remove.py::test_remove_with_hashtags[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#123-]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[_#\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629-_#\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[&#\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645-&#\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[11111#\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647-11111#\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[.#Good-.]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[@#test-@#test]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[#\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628-]", "tests/cleaners/test_remove.py::test_remove_with_hashtags[AB#CD-AB#CD]", "tests/cleaners/test_remove.py::test_remove_hashtags", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[test-test]", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#test-]", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642-#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642]", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[test", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#hashtag_start", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#hashtag", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#\\u0647\\u0627\\u064a\\u0634\\u062a\\u0627\\u0642hashtag", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_english_hashtag[#123-]", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[test-test]", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#test-#test]", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#\\u0645\\u0646\\u0634\\u0646-]", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[test", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#hashtag", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#hashtag_start", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#\\u0647\\u0627\\u0634\\u062a\\u0627\\u0642hashtag", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#123-#123]", "tests/cleaners/test_remove.py::test_remove_with_arabic_hashtag[#\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628-]", "tests/cleaners/test_remove.py::test_remove_with_mentions[test-test]", "tests/cleaners/test_remove.py::test_remove_with_mentions[@", "tests/cleaners/test_remove.py::test_remove_with_mentions[@test-]", "tests/cleaners/test_remove.py::test_remove_with_mentions[@\\u0645\\u0646\\u0634\\u0646-]", "tests/cleaners/test_remove.py::test_remove_with_mentions[[email protected]@web.com]", "tests/cleaners/test_remove.py::test_remove_with_mentions[test", "tests/cleaners/test_remove.py::test_remove_with_mentions[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_mentions[@mention_start", "tests/cleaners/test_remove.py::test_remove_with_mentions[@\\u0645\\u0646\\u0634\\u0646", "tests/cleaners/test_remove.py::test_remove_with_mentions[@\\u0647\\u0627\\u064a\\u0634\\u062a\\u0627\\u0642mention", "tests/cleaners/test_remove.py::test_remove_with_mentions[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_mentions[@123-]", "tests/cleaners/test_remove.py::test_remove_with_mentions[@mention", "tests/cleaners/test_remove.py::test_remove_with_mentions[_@\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629-_@\\u062c\\u0645\\u0639\\u0629_\\u0645\\u0628\\u0627\\u0631\\u0643\\u0629]", "tests/cleaners/test_remove.py::test_remove_with_mentions[&@\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645-&@\\u0645\\u0633\\u0627\\u0628\\u0642\\u0629_\\u0627\\u0644\\u0642\\u0631\\u0622\\u0646_\\u0627\\u0644\\u0643\\u0631\\u064a\\u0645]", "tests/cleaners/test_remove.py::test_remove_with_mentions[11111@\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647-11111@\\u0631\\u0633\\u0648\\u0644_\\u0627\\u0644\\u0644\\u0647]", "tests/cleaners/test_remove.py::test_remove_with_mentions[.@Good-.]", "tests/cleaners/test_remove.py::test_remove_with_mentions[@\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628-]", "tests/cleaners/test_remove.py::test_remove_with_mentions[AB@CD-AB@CD]", "tests/cleaners/test_remove.py::test_remove_with_mentions[#@test-#@test]", "tests/cleaners/test_remove.py::test_remove_mentions", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[test-test]", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@test-]", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@\\u0645\\u0646\\u0634\\u0646-@\\u0645\\u0646\\u0634\\u0646]", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[test", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@mention_start", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@\\u0645\\u0646\\u0634\\u0646", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@mention", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@\\u0647\\u0627\\u064a\\u0634\\u062a\\u0627\\u0642mention", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_english_mentions[@123-]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[test-test]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@test-@test]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@\\u0645\\u0646\\u0634\\u0646-]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[[email protected]@web.com]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[test", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[\\u062a\\u062c\\u0631\\u0628\\u0629", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@mention_start", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@\\u0645\\u0646\\u0634\\u0646", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@\\u0647\\u0627\\u064a\\u0634\\u062a\\u0627\\u0642mention", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[\\u0641\\u064a", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@123-@123]", "tests/cleaners/test_remove.py::test_remove_with_arabic_mentions[@\\u0644\\u064f\\u0642\\u0650\\u0651\\u0628-]", "tests/cleaners/test_remove.py::test_remove_with_emails[test-test]", "tests/cleaners/test_remove.py::test_remove_with_emails[@test-@test]", "tests/cleaners/test_remove.py::test_remove_with_emails[[email protected]]", "tests/cleaners/test_remove.py::test_remove_with_emails[[email protected]]", "tests/cleaners/test_remove.py::test_remove_with_emails[[email protected]]", "tests/cleaners/test_remove.py::test_remove_with_emails[email@web-email@web]", "tests/cleaners/test_remove.py::test_remove_emails", "tests/cleaners/test_remove.py::test_remove_with_links[test-test]", "tests/cleaners/test_remove.py::test_remove_with_links[.test.-.test.]", "tests/cleaners/test_remove.py::test_remove_with_links[web.com-]", "tests/cleaners/test_remove.py::test_remove_with_links[web-1.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[web.co.uk-]", "tests/cleaners/test_remove.py::test_remove_with_links[www.web.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[http://web.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[http://www.web.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[https://web.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[https://www.web.edu.jo-]", "tests/cleaners/test_remove.py::test_remove_with_links[https://www.web.notwebsite.noo-]", "tests/cleaners/test_remove.py::test_remove_with_links[www.web.notwebsite.noo-www.web.notwebsite.noo]", "tests/cleaners/test_remove.py::test_remove_with_links[www.web.website.com-]", "tests/cleaners/test_remove.py::test_remove_with_empty_string", "tests/cleaners/test_remove.py::test_remove_links", "tests/cleaners/test_remove.py::test_remove_should_raise_valueerror", "tests/cleaners/test_remove.py::test_remove_with_random_input", "tests/cleaners/test_remove.py::test_remove_with_emojis", "tests/cleaners/test_remove.py::test_remove_strings[\\u0628\\u0650\\u0633\\u0652\\u0645\\u0650\\u0627\\u0644\\u0644\\u0651\\u064e\\u0647\\u0650", "tests/cleaners/test_remove.py::test_remove_strings[1.", "tests/cleaners/test_remove.py::test_remove_strings_raise_valueerror", "tests/cleaners/test_remove.py::test_remove_patterns", "tests/cleaners/test_remove.py::test_remove_extra_spaces[--1]", "tests/cleaners/test_remove.py::test_remove_extra_spaces[", "tests/cleaners/test_remove.py::test_remove_extra_spaces[test", "tests/cleaners/test_remove.py::test_remove_extra_spaces_raise_valueerror", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0628-\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u062a-\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u062b-\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u062c-\\u062d]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u062e-\\u062d]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0630-\\u062f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0632-\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0634-\\u0633]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0636-\\u0635]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0638-\\u0637]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u063a-\\u0639]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0641-\\u06a1]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0642-\\u066f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0646-\\u06ba]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u064a-\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_individual_letters[\\u0629-\\u0647]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0628\\u0627\\u0628-\\u066e\\u0627\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u062a\\u0644-\\u066e\\u0644]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u062b\\u0631\\u0648\\u0629-\\u066e\\u0631\\u0648\\u0647]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u062c\\u0645\\u0644-\\u062d\\u0645\\u0644]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u062e\\u0648-\\u062d\\u0648]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0630\\u0648\\u0642-\\u062f\\u0648\\u066f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0632\\u064a\\u0627\\u062f\\u0629-\\u0631\\u0649\\u0627\\u062f\\u0647]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0634\\u0645\\u0633-\\u0633\\u0645\\u0633]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0636\\u0648\\u0621-\\u0635\\u0648\\u0621]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0638\\u0644\\u0627\\u0645-\\u0637\\u0644\\u0627\\u0645]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u063a\\u064a\\u0645-\\u0639\\u0649\\u0645]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0641\\u0648\\u0642-\\u06a1\\u0648\\u066f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0642\\u0644\\u0628-\\u066f\\u0644\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u0646\\u0648\\u0631-\\u066e\\u0648\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_begin[\\u064a\\u0648\\u0645-\\u0649\\u0648\\u0645]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0631\\u0628\\u0648-\\u0631\\u066e\\u0648]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u062a\\u0631-\\u0648\\u066e\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u062b\\u0628-\\u0648\\u066e\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u062c\\u0644-\\u0648\\u062d\\u0644]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0645\\u062e\\u062f\\u0631-\\u0645\\u062d\\u062f\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u062d\\u0630\\u0631-\\u062d\\u062f\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u0632\\u0631-\\u0648\\u0631\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u062d\\u0634\\u062f-\\u062d\\u0633\\u062f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u0636\\u0648\\u0621-\\u0648\\u0635\\u0648\\u0621]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u062d\\u0638\\u0631-\\u062d\\u0637\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0635\\u063a\\u0649-\\u0635\\u0639\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0627\\u0641\\u0644\\u0627\\u0645-\\u0627\\u06a1\\u0644\\u0627\\u0645]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0648\\u0642\\u0649-\\u0648\\u066f\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0633\\u0646\\u0629-\\u0633\\u066e\\u0647]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_mid[\\u0633\\u0644\\u064a\\u0645-\\u0633\\u0644\\u0649\\u0645]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0635\\u0628-\\u0635\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0633\\u062a-\\u0633\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u062d\\u062b-\\u062d\\u066e]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u062d\\u0631\\u062c-\\u062d\\u0631\\u062d]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0645\\u062e-\\u0645\\u062d]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0639\\u0648\\u0630-\\u0639\\u0648\\u062f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0648\\u0632-\\u0648\\u0631]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0631\\u0634-\\u0631\\u0633]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0648\\u0636\\u0648\\u0621-\\u0648\\u0635\\u0648\\u0621]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0648\\u0639\\u0638-\\u0648\\u0639\\u0637]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0635\\u0645\\u063a-\\u0635\\u0645\\u0639]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0648\\u0641\\u0649-\\u0648\\u06a1\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u062d\\u0642-\\u062d\\u066f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0633\\u0646-\\u0633\\u06ba]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0645\\u064a-\\u0645\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_dots_end[\\u0635\\u0644\\u0627\\u0629-\\u0635\\u0644\\u0627\\u0647]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646-\\u0627\\u0644\\u066e\\u066e\\u0649\\u0627\\u06ba]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646\\u064f", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646\\n\\u0642\\u0648\\u064a-\\u0627\\u0644\\u066e\\u066e\\u0649\\u0627\\u06ba\\n\\u066f\\u0648\\u0649]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646.-\\u0627\\u0644\\u066e\\u066e\\u0649\\u0627\\u06ba.0]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646.-\\u0627\\u0644\\u066e\\u066e\\u0649\\u0627\\u06ba.1]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u064a\\u0627\\u0646\\u061f-\\u0627\\u0644\\u066e\\u066e\\u0649\\u0627\\u06ba\\u061f]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u0652\\u064a\\u0627\\u0646\\U0001f60a-\\u0627\\u0644\\u066e\\u066e\\u0652\\u0649\\u0627\\u06ba\\U0001f60a]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_with_edge_case[\\u0627\\u0644\\u0628\\u0646\\u0652\\u064a\\u0627\\u0646\\u064f\\u060c-\\u0627\\u0644\\u066e\\u066e\\u0652\\u0649\\u0627\\u06ba\\u064f\\u060c]", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_general[\\u200f\\u0627\\u062d\\u0630\\u0631\\u0648\\u0627", "tests/cleaners/test_remove.py::test_remove_arabic_letter_dots_general[\\u0627\\u0644\\u0645\\u062a\\u0633\\u0644\\u0633\\u0644\\u0627\\u062a" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-04 08:47:59+00:00
bsd-3-clause
737
TRoboto__Maha-30
diff --git a/maha/parsers/rules/time/values.py b/maha/parsers/rules/time/values.py index 7c581a6..4a7d08e 100644 --- a/maha/parsers/rules/time/values.py +++ b/maha/parsers/rules/time/values.py @@ -729,13 +729,9 @@ _start_of_last_day = ( LAST_SPECIFIC_DAY_OF_SPECIFIC_MONTH = FunctionValue( lambda match: parse_value( { - "month": _months.get_matched_expression(match.group("month")).value.month # type: ignore - + 1 - if _months.get_matched_expression(match.group("month")).value.month # type: ignore - + 1 - <= 12 - else 1, + "month": _months.get_matched_expression(match.group("month")).value.month, # type: ignore "weekday": _days.get_matched_expression(match.group("day")).value(-1), # type: ignore + "day": 31, } ), spaced_patterns(_start_of_last_day, named_group("month", _months.join())),
TRoboto/Maha
a576d5385f6ba011f81cf8d0e69f52f756006489
diff --git a/tests/parsers/test_time.py b/tests/parsers/test_time.py index 8fa926c..57182e3 100644 --- a/tests/parsers/test_time.py +++ b/tests/parsers/test_time.py @@ -726,6 +726,20 @@ def test_time(expected, input): assert_expression_output(output, expected) [email protected]( + "expected,input", + [ + (NOW.replace(day=30), "آخر خميس من شهر 9"), + (NOW.replace(day=29), "آخر اربعاء من شهر 9"), + (NOW.replace(day=22, month=2), "آخر اثنين من شهر شباط"), + (NOW.replace(day=28, month=2), "آخر احد من شهر شباط"), + ], +) +def test_last_specific_day_of_specific_month(expected, input): + output = parse_dimension(input, time=True) + assert_expression_output(output, expected) + + @pytest.mark.parametrize( "input", [
Last day of month parsing returns incorrect date ### What happened? Check the following example: ```py >>> from datetime import datetime >>> from maha.parsers.functions import parse_dimension >>> date = datetime(2021, 9, 21) >>> sample_text = "آخر اثنين من شهر شباط" >>> parse_dimension(sample_text, time=True)[0].value + date datetime.datetime(2021, 3, 15, 0, 0) ``` Obviously this is wrong, we're asking for February while it returns March. The correct answer is: ```py datetime.datetime(2021, 2, 22) ``` ### Python version 3.8 ### What operating system are you using? Linux ### Code to reproduce the issue _No response_ ### Relevant log output _No response_
0.0
a576d5385f6ba011f81cf8d0e69f52f756006489
[ "tests/parsers/test_time.py::test_last_specific_day_of_specific_month[expected2-\\u0622\\u062e\\u0631" ]
[ "tests/parsers/test_time.py::test_current_year[\\u0647\\u0630\\u064a", "tests/parsers/test_time.py::test_current_year[\\u0647\\u0627\\u064a", "tests/parsers/test_time.py::test_current_year[\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_current_year[\\u0627\\u0644\\u0639\\u0627\\u0645]", "tests/parsers/test_time.py::test_current_year[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_previous_year[", "tests/parsers/test_time.py::test_previous_year[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_previous_year[\\u0627\\u0644\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_previous_year[\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_next_year[", "tests/parsers/test_time.py::test_next_year[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_next_year[\\u0627\\u0644\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_next_year[\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_before_years[3-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_before_years[5-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_before_years[20-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_before_years[-100-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_after_before_years[-20-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_after_before_years[-10-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_after_before_years[-25-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_next_two_years[", "tests/parsers/test_time.py::test_next_two_years[\\u0627\\u0644\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_next_two_years[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_next_two_years[\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_previous_two_years[", "tests/parsers/test_time.py::test_previous_two_years[\\u0627\\u0644\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_previous_two_years[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_previous_two_years[\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_this_year[\\u0627\\u0644\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_this_year[\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_this_year[\\u0627\\u0644\\u0639\\u0627\\u0645]", "tests/parsers/test_time.py::test_this_year[\\u0627\\u0644\\u0633\\u0646\\u0629", "tests/parsers/test_time.py::test_this_year[\\u0639\\u0627\\u0645", "tests/parsers/test_time.py::test_this_year[\\u0647\\u0627\\u064a", "tests/parsers/test_time.py::test_n_months[3-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_n_months[2-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_n_months[1-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_n_months[-8-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_n_months[-2-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_n_months[-1-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_n_months[1-\\u0627\\u0644\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_n_months[-1-\\u0627\\u0644\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_n_months[2-\\u0627\\u0644\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_n_months[-2-\\u0627\\u0644\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_after_30_months", "tests/parsers/test_time.py::test_specific_month[12-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_specific_month[12-\\u0643\\u0627\\u0646\\u0648\\u0646", "tests/parsers/test_time.py::test_specific_month[12-\\u062f\\u064a\\u0633\\u0645\\u0628\\u0631]", "tests/parsers/test_time.py::test_specific_month[1-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_specific_month[2-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_specific_month[2-\\u0634\\u0628\\u0627\\u0637]", "tests/parsers/test_time.py::test_specific_month[2-\\u0641\\u0628\\u0631\\u0627\\u064a\\u0631]", "tests/parsers/test_time.py::test_next_specific_month_same_year[11-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_next_specific_month_same_year[11-\\u062a\\u0634\\u0631\\u064a\\u0646", "tests/parsers/test_time.py::test_next_specific_month_same_year[12-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_next_specific_month_same_year[10-\\u0627\\u0643\\u062a\\u0648\\u0628\\u0631", "tests/parsers/test_time.py::test_next_specific_month_same_year[10-\\u062a\\u0634\\u0631\\u064a\\u0646", "tests/parsers/test_time.py::test_next_specific_month_same_year[12-\\u0643\\u0627\\u0646\\u0648\\u0646", "tests/parsers/test_time.py::test_next_specific_month_next_year[11-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_next_specific_month_next_year[10-\\u0627\\u0643\\u062a\\u0648\\u0628\\u0631", "tests/parsers/test_time.py::test_next_specific_month_next_year[2-\\u0634\\u0628\\u0627\\u0637", "tests/parsers/test_time.py::test_next_specific_month_next_year[3-\\u0622\\u0630\\u0627\\u0631", "tests/parsers/test_time.py::test_next_specific_month_next_year[3-\\u0623\\u0630\\u0627\\u0631", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[11-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[11-\\u062a\\u0634\\u0631\\u064a\\u0646", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[12-\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[10-\\u0627\\u0643\\u062a\\u0648\\u0628\\u0631", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[2-\\u0634\\u0628\\u0627\\u0637", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[10-\\u062a\\u0634\\u0631\\u064a\\u0646", "tests/parsers/test_time.py::test_previous_specific_month_previous_year[12-\\u0643\\u0627\\u0646\\u0648\\u0646", "tests/parsers/test_time.py::test_previous_specific_month_same_year[2-\\u0634\\u0628\\u0627\\u0637", "tests/parsers/test_time.py::test_previous_this_month[\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_previous_this_month[\\u0627\\u0644\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_previous_this_month[\\u062e\\u0644\\u0627\\u0644", "tests/parsers/test_time.py::test_next_weeks[3-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_weeks[2-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_weeks[1-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_weeks[1-\\u0627\\u0644\\u0623\\u0633\\u0628\\u0648\\u0639", "tests/parsers/test_time.py::test_next_weeks[2-\\u0627\\u0644\\u0623\\u0633\\u0628\\u0648\\u0639", "tests/parsers/test_time.py::test_next_weeks[0-\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_next_weeks[0-", "tests/parsers/test_time.py::test_previous_weeks[-1-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_previous_weeks[-1-\\u0627\\u0644\\u0625\\u0633\\u0628\\u0648\\u0639", "tests/parsers/test_time.py::test_previous_weeks[-1-\\u0627\\u0644\\u0627\\u0633\\u0628\\u0648\\u0639", "tests/parsers/test_time.py::test_previous_weeks[-2-\\u0627\\u0644\\u0623\\u0633\\u0628\\u0648\\u0639", "tests/parsers/test_time.py::test_previous_weeks[-4-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_previous_weeks[-2-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_next_days[3-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_days[21-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_days[1-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_days[2-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_next_days[1-\\u0628\\u0643\\u0631\\u0629]", "tests/parsers/test_time.py::test_next_days[1-\\u0628\\u0643\\u0631\\u0647]", "tests/parsers/test_time.py::test_next_days[1-\\u0627\\u0644\\u063a\\u062f]", "tests/parsers/test_time.py::test_next_days[1-\\u063a\\u062f\\u0627]", "tests/parsers/test_time.py::test_next_days[1-\\u0627\\u0644\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_next_days[2-\\u0627\\u0644\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_next_days[0-\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_next_days[0-", "tests/parsers/test_time.py::test_previous_days[-1-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_previous_days[-1-\\u0627\\u0644\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_previous_days[-1-\\u0627\\u0644\\u0628\\u0627\\u0631\\u062d\\u0629]", "tests/parsers/test_time.py::test_previous_days[-1-\\u0645\\u0628\\u0627\\u0631\\u062d]", "tests/parsers/test_time.py::test_previous_days[-1-\\u0627\\u0645\\u0628\\u0627\\u0631\\u062d]", "tests/parsers/test_time.py::test_previous_days[-2-\\u0627\\u0648\\u0644", "tests/parsers/test_time.py::test_previous_days[-2-\\u0627\\u0644\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_previous_days[-20-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_previous_days[-10-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_previous_days[-2-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_specific_next_weekday[7-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_next_weekday[1-\\u0627\\u0644\\u0623\\u0631\\u0628\\u0639\\u0627", "tests/parsers/test_time.py::test_specific_next_weekday[1-\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_specific_next_weekday[2-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633]", "tests/parsers/test_time.py::test_specific_next_weekday[2-\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_specific_next_weekday[2-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_specific_next_weekday[5-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_next_weekday[5-\\u0627\\u0644\\u0627\\u062d\\u062f", "tests/parsers/test_time.py::test_specific_next_weekday[6-\\u0627\\u0644\\u0627\\u062b\\u0646\\u064a\\u0646]", "tests/parsers/test_time.py::test_specific_next_weekday[7-\\u0627\\u0644\\u062b\\u0644\\u0627\\u062b\\u0627]", "tests/parsers/test_time.py::test_specific_next_weekday[7-\\u062b\\u0644\\u0627\\u062b\\u0627\\u0621]", "tests/parsers/test_time.py::test_specific_next_weekday[8-\\u0627\\u0644\\u0623\\u0631\\u0628\\u0639\\u0627\\u0621", "tests/parsers/test_time.py::test_specific_next_weekday[15-\\u0627\\u0644\\u0627\\u0631\\u0628\\u0639\\u0627", "tests/parsers/test_time.py::test_specific_next_weekday[9-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_specific_next_weekday[9-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_previous_weekday[31-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_previous_weekday[25-\\u0627\\u0644\\u0623\\u0631\\u0628\\u0639\\u0627", "tests/parsers/test_time.py::test_specific_previous_weekday[26-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_specific_previous_weekday[29-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_previous_weekday[27-\\u0627\\u0644\\u062c\\u0645\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_previous_weekday[28-\\u0627\\u0644\\u0633\\u0628\\u062a", "tests/parsers/test_time.py::test_specific_previous_weekday[30-\\u0627\\u0644\\u0625\\u062b\\u0646\\u064a\\u0646", "tests/parsers/test_time.py::test_specific_previous_weekday[18-\\u0627\\u0644\\u0627\\u0631\\u0628\\u0639\\u0627", "tests/parsers/test_time.py::test_specific_previous_weekday[24-\\u0627\\u0644\\u062b\\u0644\\u0627\\u062b\\u0627\\u0621", "tests/parsers/test_time.py::test_specific_previous_weekday[23-\\u064a\\u0648\\u0645", "tests/parsers/test_time.py::test_specific_hour[3-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_hour[5-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_hour[1-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_hour[10-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_hour[2-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_hour[12-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_after_hours[5-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_hours[6-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_hours[13-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_hours[1-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_hours[2-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_hours[2-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_after_hours[1-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_after_hours[0-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_after_hours[0-\\u0647\\u0630\\u0647", "tests/parsers/test_time.py::test_after_hours[0-\\u0647\\u0630\\u064a", "tests/parsers/test_time.py::test_before_hours[-5-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_hours[-6-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_hours[-10-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_hours[-1-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_hours[-2-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_hours[-2-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_before_hours[-1-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_specific_minute[3-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[3-\\u062b\\u0644\\u0627\\u062b", "tests/parsers/test_time.py::test_specific_minute[10-\\u0639\\u0634\\u0631\\u0629", "tests/parsers/test_time.py::test_specific_minute[5-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[1-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[10-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[59-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[59-", "tests/parsers/test_time.py::test_specific_minute[2-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_specific_minute[12-12", "tests/parsers/test_time.py::test_specific_minute[12-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_after_minutes[5-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_minutes[6-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_minutes[21-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_minutes[1-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_minutes[2-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_after_minutes[2-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0647", "tests/parsers/test_time.py::test_after_minutes[1-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0647", "tests/parsers/test_time.py::test_after_minutes[0-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0647", "tests/parsers/test_time.py::test_after_minutes[0-\\u0647\\u0630\\u0647", "tests/parsers/test_time.py::test_after_minutes[0-\\u0647\\u0630\\u064a", "tests/parsers/test_time.py::test_before_minutes[-5-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_minutes[-30-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_minutes[-21-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_minutes[-1-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_minutes[-2-\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_before_minutes[-2-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_before_minutes[-1-\\u0627\\u0644\\u062f\\u0642\\u064a\\u0642\\u0629", "tests/parsers/test_time.py::test_am[\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_am[\\u0627\\u0644\\u0641\\u062c\\u0631]", "tests/parsers/test_time.py::test_am[\\u0627\\u0644\\u0638\\u0647\\u0631]", "tests/parsers/test_time.py::test_am[\\u0627\\u0644\\u0635\\u0628\\u062d]", "tests/parsers/test_time.py::test_am[\\u0641\\u064a", "tests/parsers/test_time.py::test_am[\\u0635\\u0628\\u0627\\u062d\\u0627]", "tests/parsers/test_time.py::test_am[\\u0638\\u0647\\u0631\\u0627]", "tests/parsers/test_time.py::test_am[\\u0641\\u062c\\u0631\\u0627]", "tests/parsers/test_time.py::test_am[\\u0641\\u062c\\u0631]", "tests/parsers/test_time.py::test_pm[\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0639\\u0635\\u0631]", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628]", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0639\\u0634\\u0627\\u0621]", "tests/parsers/test_time.py::test_pm[\\u0642\\u0628\\u0644", "tests/parsers/test_time.py::test_pm[\\u0641\\u064a", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0644\\u064a\\u0644\\u0629]", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0644\\u064a\\u0644\\u0647]", "tests/parsers/test_time.py::test_pm[\\u0627\\u0644\\u0645\\u0633\\u0627]", "tests/parsers/test_time.py::test_pm[\\u0645\\u0633\\u0627\\u0621]", "tests/parsers/test_time.py::test_pm[\\u0645\\u0633\\u0627\\u0621\\u0627]", "tests/parsers/test_time.py::test_now[\\u062d\\u0627\\u0644\\u0627]", "tests/parsers/test_time.py::test_now[\\u0641\\u064a", "tests/parsers/test_time.py::test_now[\\u0647\\u0633\\u0629]", "tests/parsers/test_time.py::test_now[\\u0627\\u0644\\u0622\\u0646]", "tests/parsers/test_time.py::test_now[\\u0647\\u0627\\u064a", "tests/parsers/test_time.py::test_now[\\u0647\\u0630\\u0627", "tests/parsers/test_time.py::test_first_day_and_month[\\u062e\\u0644\\u0627\\u0644", "tests/parsers/test_time.py::test_first_day_and_month[\\u0627\\u0648\\u0644", "tests/parsers/test_time.py::test_first_day_and_month[1", "tests/parsers/test_time.py::test_first_day_and_month[\\u0627\\u0644\\u0623\\u0648\\u0644", "tests/parsers/test_time.py::test_first_day_and_month[1/9]", "tests/parsers/test_time.py::test_month_and_year[\\u0634\\u0647\\u0631", "tests/parsers/test_time.py::test_month_and_year[", "tests/parsers/test_time.py::test_month_and_year[9/2021]", "tests/parsers/test_time.py::test_time[expected0-\\u0628\\u0643\\u0631\\u0629", "tests/parsers/test_time.py::test_time[expected1-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_time[expected2-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_time[expected3-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_time[expected4-\\u0627\\u0644\\u062e\\u0645\\u064a\\u0633", "tests/parsers/test_time.py::test_time[expected5-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_time[expected6-\\u0627\\u0644\\u062c\\u0645\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected7-\\u0627\\u0644\\u0633\\u0628\\u062a", "tests/parsers/test_time.py::test_time[expected8-\\u0627\\u0644\\u062b\\u0627\\u0646\\u064a", "tests/parsers/test_time.py::test_time[expected9-\\u0627\\u0644\\u0639\\u0627\\u0634\\u0631", "tests/parsers/test_time.py::test_time[expected10-10", "tests/parsers/test_time.py::test_time[expected11-10", "tests/parsers/test_time.py::test_time[expected12-\\u0627\\u0644\\u0623\\u0631\\u0628\\u0639\\u0627", "tests/parsers/test_time.py::test_time[expected13-\\u0627\\u0644\\u0633\\u0628\\u062a", "tests/parsers/test_time.py::test_time[expected14-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_time[expected15-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_time[expected16-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_time[expected17-\\u0627\\u0648\\u0644", "tests/parsers/test_time.py::test_time[expected18-\\u0627\\u062e\\u0631", "tests/parsers/test_time.py::test_time[expected19-\\u062b\\u0627\\u0644\\u062b", "tests/parsers/test_time.py::test_time[expected20-\\u062b\\u0627\\u0644\\u062b", "tests/parsers/test_time.py::test_time[expected21-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected22-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected23-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected24-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected25-12", "tests/parsers/test_time.py::test_time[expected26-\\u0627\\u0644\\u0633\\u0627\\u0639\\u0629", "tests/parsers/test_time.py::test_time[expected27-\\u0641\\u064a", "tests/parsers/test_time.py::test_time[expected28-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_time[expected29-\\u0628\\u0639\\u062f", "tests/parsers/test_time.py::test_time[expected30-3:20]", "tests/parsers/test_time.py::test_time[expected31-\\u0627\\u0648\\u0644", "tests/parsers/test_time.py::test_time[expected32-1/9/2021]", "tests/parsers/test_time.py::test_time[expected33-\\u0627\\u0644\\u0627\\u062b\\u0646\\u064a\\u0646", "tests/parsers/test_time.py::test_time[expected34-\\u0627\\u0644\\u0633\\u0628\\u062a", "tests/parsers/test_time.py::test_last_specific_day_of_specific_month[expected0-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_last_specific_day_of_specific_month[expected1-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_last_specific_day_of_specific_month[expected3-\\u0622\\u062e\\u0631", "tests/parsers/test_time.py::test_negative_cases[11]", "tests/parsers/test_time.py::test_negative_cases[\\u0627\\u0644\\u062d\\u0627\\u062f\\u064a", "tests/parsers/test_time.py::test_negative_cases[\\u0627\\u062d\\u062f", "tests/parsers/test_time.py::test_negative_cases[\\u0627\\u062b\\u0646\\u064a\\u0646]", "tests/parsers/test_time.py::test_negative_cases[\\u062b\\u0644\\u0627\\u062b\\u0629]", "tests/parsers/test_time.py::test_negative_cases[\\u064a\\u0648\\u0645]", "tests/parsers/test_time.py::test_negative_cases[\\u0627\\u0631\\u0628\\u0639\\u0629", "tests/parsers/test_time.py::test_negative_cases[\\u062c\\u0645\\u0639]", "tests/parsers/test_time.py::test_negative_cases[\\u0627\\u0644\\u0633\\u0628\\u062a\\u062a]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-09-23 17:54:50+00:00
bsd-3-clause
738
TTitcombe__PrivacyPanda-20
diff --git a/privacypanda/__init__.py b/privacypanda/__init__.py index ab09290..16ccf12 100644 --- a/privacypanda/__init__.py +++ b/privacypanda/__init__.py @@ -1,5 +1,6 @@ from .addresses import * from .anonymize import * +from .email import * from .report import * __version__ = "0.1.0dev" diff --git a/privacypanda/anonymize.py b/privacypanda/anonymize.py index 44596a7..7904b9e 100644 --- a/privacypanda/anonymize.py +++ b/privacypanda/anonymize.py @@ -5,6 +5,7 @@ import pandas as pd from numpy import unique as np_unique from .addresses import check_addresses +from .email import check_emails def anonymize(df: pd.DataFrame) -> pd.DataFrame: @@ -27,7 +28,7 @@ def anonymize(df: pd.DataFrame) -> pd.DataFrame: """ private_cols = [] - checks = [check_addresses] + checks = [check_addresses, check_emails] for check in checks: new_private_cols = check(df) private_cols += new_private_cols diff --git a/privacypanda/email.py b/privacypanda/email.py new file mode 100644 index 0000000..822f081 --- /dev/null +++ b/privacypanda/email.py @@ -0,0 +1,55 @@ +""" +Code for identifying emails +""" +import re +from typing import List + +import pandas as pd +from numpy import dtype as np_dtype + +__all__ = ["check_emails"] + +OBJECT_DTYPE = np_dtype("O") + +# Whitelisted email suffix. +# TODO extend this +WHITELIST_EMAIL_SUFFIXES = [".co.uk", ".com", ".org", ".edu"] +EMAIL_SUFFIX_REGEX = "[" + r"|".join(WHITELIST_EMAIL_SUFFIXES) + "]" + +# Simple email pattern +SIMPLE_EMAIL_PATTERN = re.compile(".*@.*" + EMAIL_SUFFIX_REGEX, re.I) + + +def check_emails(df: pd.DataFrame) -> List: + """ + Check a dataframe for columns containing emails. Returns a list of column + names which contain at least one emails + + "Emails" currently only concerns common emails, with one of the following + suffixes: ".co.uk", ".com", ".org", ".edu" + + Parameters + ---------- + df : pandas.DataFrame + The dataframe to check + + Returns + ------- + List + The names of columns which contain at least one email + """ + private_cols = [] + + for col in df: + row = df[col] + + # Only check column if it may contain strings + if row.dtype == OBJECT_DTYPE: + for item in row: + item = str(item) # convert incase column has mixed data types + + if SIMPLE_EMAIL_PATTERN.match(item): + private_cols.append(col) + break # 1 failure is enough + + return private_cols diff --git a/privacypanda/report.py b/privacypanda/report.py index e8af3a3..7f3b1c7 100644 --- a/privacypanda/report.py +++ b/privacypanda/report.py @@ -5,6 +5,7 @@ from collections import defaultdict from typing import TYPE_CHECKING, List, Union from .addresses import check_addresses +from .email import check_emails if TYPE_CHECKING: import pandas @@ -57,7 +58,7 @@ class Report: def report_privacy(df: "pandas.DataFrame") -> Report: report = Report() - checks = {"address": check_addresses} + checks = {"address": check_addresses, "email": check_emails} for breach, check in checks.items(): columns = check(df)
TTitcombe/PrivacyPanda
22804d3aa0f076a6ad914b514c0dbee65b1ff991
diff --git a/tests/test_anonymization.py b/tests/test_anonymization.py index 916ba93..e0c26ee 100644 --- a/tests/test_anonymization.py +++ b/tests/test_anonymization.py @@ -39,6 +39,33 @@ def test_removes_columns_containing_addresses(address): pd.testing.assert_frame_equal(actual_df, expected_df) [email protected]( + "email", + [ + "[email protected]", + "[email protected]", + "[email protected]", + "[email protected]", + ], +) +def test_removes_columns_containing_emails(email): + df = pd.DataFrame( + { + "privateData": ["a", "b", "c", email], + "nonPrivateData": ["a", "b", "c", "d"], + "nonPrivataData2": [1, 2, 3, 4], + } + ) + + expected_df = pd.DataFrame( + {"nonPrivateData": ["a", "b", "c", "d"], "nonPrivataData2": [1, 2, 3, 4]} + ) + + actual_df = pp.anonymize(df) + + pd.testing.assert_frame_equal(actual_df, expected_df) + + def test_returns_empty_dataframe_if_all_columns_contain_private_information(): df = pd.DataFrame( { diff --git a/tests/test_email_identification.py b/tests/test_email_identification.py new file mode 100644 index 0000000..dd23f7b --- /dev/null +++ b/tests/test_email_identification.py @@ -0,0 +1,48 @@ +""" +Test functions for identifying emails in dataframes +""" +import pandas as pd +import pytest + +import privacypanda as pp + + [email protected]( + "email", + ["[email protected]", "[email protected]", "[email protected]", "[email protected]"], +) +def test_can_identify_column_whitelisted_suffixes(email): + df = pd.DataFrame( + {"privateColumn": ["a", email, "c"], "nonPrivateColumn": ["a", "b", "c"]} + ) + + actual_private_columns = pp.check_emails(df) + expected_private_columns = ["privateColumn"] + + assert actual_private_columns == expected_private_columns + + +def test_address_check_returns_empty_list_if_no_emails_found(): + df = pd.DataFrame( + {"nonPrivateColumn1": ["a", "b", "c"], "nonPrivateColumn2": ["a", "b", "c"]} + ) + + actual_private_columns = pp.check_emails(df) + expected_private_columns = [] + + assert actual_private_columns == expected_private_columns + + +def test_check_emails_can_handle_mixed_dtype_columns(): + df = pd.DataFrame( + { + "privateColumn": [True, "[email protected]", "c"], + "privateColumn2": [1, "b", "[email protected]"], + "nonPrivateColumn": [0, True, "test"], + } + ) + + actual_private_columns = pp.check_emails(df) + expected_private_columns = ["privateColumn", "privateColumn2"] + + assert actual_private_columns == expected_private_columns diff --git a/tests/test_report.py b/tests/test_report.py index ced0754..93a1229 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -29,12 +29,42 @@ def test_can_report_addresses(): assert actual_string == expected_string -def test_report_can_accept_multiple_breaches_per_column(): - report = pp.report.Report() +def test_can_report_emails(): + df = pd.DataFrame( + { + "col1": ["a", "b", "[email protected]"], + "col2": [1, 2, 3], + "col3": ["[email protected]", "b", "c"], + } + ) - report.add_breach("col1", "address") - report.add_breach("col1", "phone number") + # Check correct breaches have been logged + report = pp.report_privacy(df) + expected_breaches = {"col1": ["email"], "col3": ["email"]} + + assert report._breaches == expected_breaches + + # Check string report + actual_string = str(report) + expected_string = "col1: ['email']\ncol3: ['email']\n" + + assert actual_string == expected_string + + +def test_report_can_accept_multiple_breaches_per_column(): + df = pd.DataFrame( + { + "col1": ["a", "10 Downing Street", "[email protected]"], + "col2": [1, 2, "AB1 1AB"], + "col3": ["[email protected]", "b", "c"], + } + ) + report = pp.report_privacy(df) - expected_breaches = {"col1": ["address", "phone number"]} + expected_breaches = { + "col1": ["address", "email"], + "col2": ["address"], + "col3": ["email"], + } assert report._breaches == expected_breaches
Identify emails Email addresses should be considered a breach of privacy. While we could naively assume `.*@.*` is an emaill, this would lead to a lot of false negatives. To begin with, we should identify emails using a whitelist of domains e.g. `gmail, hotmail` and `.co.uk, .com, .org, .edu` etc.
0.0
22804d3aa0f076a6ad914b514c0dbee65b1ff991
[ "tests/test_anonymization.py::test_removes_columns_containing_emails[[email protected]]", "tests/test_anonymization.py::test_removes_columns_containing_emails[[email protected]]", "tests/test_anonymization.py::test_removes_columns_containing_emails[[email protected]]", "tests/test_anonymization.py::test_removes_columns_containing_emails[[email protected]]", "tests/test_email_identification.py::test_can_identify_column_whitelisted_suffixes[[email protected]]", "tests/test_email_identification.py::test_can_identify_column_whitelisted_suffixes[[email protected]]", "tests/test_email_identification.py::test_can_identify_column_whitelisted_suffixes[[email protected]]", "tests/test_email_identification.py::test_can_identify_column_whitelisted_suffixes[[email protected]]", "tests/test_email_identification.py::test_address_check_returns_empty_list_if_no_emails_found", "tests/test_email_identification.py::test_check_emails_can_handle_mixed_dtype_columns", "tests/test_report.py::test_can_report_emails", "tests/test_report.py::test_report_can_accept_multiple_breaches_per_column" ]
[ "tests/test_anonymization.py::test_removes_columns_containing_addresses[10", "tests/test_anonymization.py::test_removes_columns_containing_addresses[1", "tests/test_anonymization.py::test_removes_columns_containing_addresses[01", "tests/test_anonymization.py::test_removes_columns_containing_addresses[1234", "tests/test_anonymization.py::test_removes_columns_containing_addresses[55", "tests/test_anonymization.py::test_removes_columns_containing_addresses[4", "tests/test_anonymization.py::test_removes_columns_containing_addresses[AB1", "tests/test_anonymization.py::test_removes_columns_containing_addresses[AB12", "tests/test_report.py::test_can_report_addresses" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-26 14:24:02+00:00
apache-2.0
739
TTitcombe__PrivacyPanda-23
diff --git a/.gitignore b/.gitignore index b6e4761..28049c9 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,6 @@ dmypy.json # Pyre type checker .pyre/ + +# PrivacyPanda specifics +images/*.svg diff --git a/privacypanda/addresses.py b/privacypanda/addresses.py index 53d3c82..2ec6753 100644 --- a/privacypanda/addresses.py +++ b/privacypanda/addresses.py @@ -20,7 +20,7 @@ UK_POSTCODE_PATTERN = re.compile( ) # Street names -STREET_ENDINGS = r"(street|road|way|avenue)" +STREET_ENDINGS = r"(street|road|way|avenue|st|rd|wy|ave)" # Simple address is up to a four digit number + street name with 1-10 characters # + one of "road", "street", "way", "avenue"
TTitcombe/PrivacyPanda
7f2f07b7f3148dbd15dea5a0f1a773c9bc288b28
diff --git a/tests/test_address_identification.py b/tests/test_address_identification.py index f16420a..2546756 100644 --- a/tests/test_address_identification.py +++ b/tests/test_address_identification.py @@ -24,11 +24,17 @@ def test_can_identify_column_containing_UK_postcode(postcode): [ "10 Downing Street", "10 downing street", + "11 Downing St.", + "9 downing St", "1 the Road", + "2 A Rd.", + "2 A Rd", "01 The Road", "1234 The Road", "55 Maple Avenue", + "55 Maple Ave", "4 Python Way", + "4 Python wy", ], ) def test_can_identify_column_containing_simple_street_names(address): @@ -42,17 +48,7 @@ def test_can_identify_column_containing_simple_street_names(address): assert actual_private_columns == expected_private_columns [email protected]( - "address", - [ - "10 Downing St", - "10 downing st", - "1 the rd", - "01 The Place", - "55 Maple Ave", - "4 Python Wy", - ], -) [email protected]("address", ["01 The Place"]) def test_does_not_identify_non_whitelisted_street_types_as_addresses(address): df = pd.DataFrame( {"privateColumn": ["a", address, "c"], "nonPrivateColumn": ["a", "b", "c"]}
Identify street name abbreviations #6 introduced the capability to detect full street names, with street types "street", "road", "avenue", "way". Addresses can be abbreviated e.g. 10 Downing St. instead of 10 Downing Street. Abbreviated street types should be included in an address search
0.0
7f2f07b7f3148dbd15dea5a0f1a773c9bc288b28
[ "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[11", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[9", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[2", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[55", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[4" ]
[ "tests/test_address_identification.py::test_can_identify_column_containing_UK_postcode[AB1", "tests/test_address_identification.py::test_can_identify_column_containing_UK_postcode[AB12", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[10", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[1", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[01", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[1234", "tests/test_address_identification.py::test_does_not_identify_non_whitelisted_street_types_as_addresses[01", "tests/test_address_identification.py::test_address_check_returns_empty_list_if_no_addresses_found", "tests/test_address_identification.py::test_check_addresses_can_handle_mixed_dtype_columns" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-03-03 19:38:43+00:00
apache-2.0
740
TTitcombe__PrivacyPanda-29
diff --git a/.gitignore b/.gitignore index 28049c9..62a7df8 100644 --- a/.gitignore +++ b/.gitignore @@ -128,5 +128,7 @@ dmypy.json # Pyre type checker .pyre/ +.idea/ + # PrivacyPanda specifics images/*.svg diff --git a/CHANGELOG.md b/CHANGELOG.md index 937211f..8d21a4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- Decorator which checks privacy of function output + - Raises `PrivacyError` if breaches are detected ## [0.1.0] - 2020-03-10 ### Added diff --git a/privacypanda/anonymize.py b/privacypanda/anonymize.py index bbaa617..1fb62ec 100644 --- a/privacypanda/anonymize.py +++ b/privacypanda/anonymize.py @@ -1,15 +1,19 @@ """ Code for cleaning a dataframe of private data """ -import pandas as pd +from typing import TYPE_CHECKING, Dict, Tuple + from numpy import unique as np_unique from .addresses import check_addresses from .email import check_emails from .phonenumbers import check_phonenumbers +if TYPE_CHECKING: + import pandas + -def anonymize(df: pd.DataFrame) -> pd.DataFrame: +def anonymize(df: "pandas.DataFrame") -> "pandas.DataFrame": """ Remove private data from a dataframe @@ -39,3 +43,49 @@ def anonymize(df: pd.DataFrame) -> pd.DataFrame: # Drop columns return df.drop(private_cols, axis=1) + + +def unique_id( + data: "pandas.DataFrame", column: str, id_mapping=None +) -> Tuple["pandas.DataFrame", Dict[str, int]]: + """ + Replace data in a given column of a dataframe with a unique id. + + Parameters + ---------- + data : pandas.DataFrame + The data to anonymise + column : str + The name of the column in data to be anonymised + id_mapping : dict, optional + Existing unique ID mappings to use. If not provided, start mapping from scratch + + Returns + ------- + pandas.DataFrame + The given data, but with the data in the given column mapped to a unique id + dict + The mapping of non-private data to unique IDs + """ + if id_mapping is None: + id_mapping = {} + + current_max_id = max(id_mapping.values()) + + for idx in data.shape[0]: + datum = data[idx, column] + + if isinstance(datum, str): + # Assume it's an ID already + continue + + try: + id = id_mapping[datum] + except KeyError: + current_max_id += 1 + id_mapping[datum] = current_max_id + data[idx, column] = current_max_id + else: + data[idx, column] = id + + return data, id_mapping diff --git a/privacypanda/errors.py b/privacypanda/errors.py new file mode 100644 index 0000000..96cb170 --- /dev/null +++ b/privacypanda/errors.py @@ -0,0 +1,8 @@ +""" +Custom errors used by PrivacyPanda +""" + + +class PrivacyError(RuntimeError): + def __init__(self, message): + super().__init__(message) diff --git a/privacypanda/report.py b/privacypanda/report.py index 7cff4f0..a844c35 100644 --- a/privacypanda/report.py +++ b/privacypanda/report.py @@ -2,17 +2,16 @@ Code for reporting the privacy of a dataframe """ from collections import defaultdict -from typing import TYPE_CHECKING, List, Union +from typing import TYPE_CHECKING, Callable, List, Union + +import pandas as pd from .addresses import check_addresses from .email import check_emails +from .errors import PrivacyError from .phonenumbers import check_phonenumbers -if TYPE_CHECKING: - import pandas - - -__all__ = ["report_privacy"] +__all__ = ["report_privacy", "check_privacy"] class Report: @@ -56,7 +55,20 @@ class Report: return report -def report_privacy(df: "pandas.DataFrame") -> Report: +def report_privacy(df: pd.DataFrame) -> Report: + """ + Create a Report on the privacy of a dataframe + + Parameters + ---------- + df : pandas.DataFrame + The data on which to create a report + + Returns + ------- + privacypanda.report.Report + The report object on the provided dataframe + """ report = Report() checks = { @@ -70,3 +82,44 @@ def report_privacy(df: "pandas.DataFrame") -> Report: report.add_breach(columns, breach) return report + + +# Privacy decorator +def check_privacy(func: Callable) -> Callable: + """ + A decorator which checks if the output of a function + breaches privacy + + Parameters + ---------- + func : function + The function to wrap + + Returns + ------- + The function, wrapped so function output + is checked for privacy breaches + + Raises + ------ + PrivacyError + If the output of the wrapped function breaches privacy + """ + + def inner_func(*args, **kwargs): + data = func(*args, **kwargs) + + if isinstance(data, pd.DataFrame): + privacy_report = report_privacy(data) + + if privacy_report._breaches.keys(): + # Output list of breaches + breaches = f"" + for breach_col, breach_type in privacy_report._breaches.items(): + breaches += f"\t{breach_col}: {breach_type}\n" + + raise PrivacyError("Privacy breach in data:\n" + breaches) + + return data + + return inner_func
TTitcombe/PrivacyPanda
1d1673fc74e805e42237735202917fcb21446784
diff --git a/tests/test_report.py b/tests/test_report.py index 9a899c0..aae6b58 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -1,10 +1,10 @@ """ Test reporting functionality """ +import numpy as np import pandas as pd -import pytest - import privacypanda as pp +import pytest def test_can_report_addresses(): @@ -90,3 +90,56 @@ def test_report_can_accept_multiple_breaches_per_column(): } assert report._breaches == expected_breaches + + +def test_check_privacy_wrapper_returns_data_if_no_privacy_breaches(): + df = pd.DataFrame({"col1": ["a", "b", "c", "d", "e"], "col2": [1, 2, 5, 10, 20]}) + + @pp.check_privacy + def return_data(): + return df + + data = return_data() + + pd.testing.assert_frame_equal(data, df) + + [email protected]( + "breach_type,breach", + [ + ("email", "[email protected]"), + ("address", "10 Downing St"), + ("phone number", "07123456789"), + ], +) +def test_check_privacy_wrapper_raises_if_data_contains_privacy_breaches( + breach_type, breach +): + df = pd.DataFrame({"col1": ["a", breach, "c", "d", "e"], "col2": [1, 2, 5, 10, 20]}) + + @pp.check_privacy + def return_data(): + return df + + with pytest.raises(pp.errors.PrivacyError): + data = return_data() + + [email protected]( + "output", + [ + 5, + [1, 2, 3], + ("a", "b"), + "output", + pd.Series([1, 2, 3, 10, 15]), + np.random.random((10, 3)), + ], +) +def test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe(output): + @pp.check_privacy + def return_data(): + return output + + data = return_data() + assert isinstance(data, type(output))
Create privacy check decorator There should be a function to check the privacy of a dataframe which can be used as a decorator. E.g. ``` >>> @checkprivacy >>> def func_that_returns_privacy_breach(): >>> return df_containing_private_data PrivacyError ```
0.0
1d1673fc74e805e42237735202917fcb21446784
[ "tests/test_report.py::test_check_privacy_wrapper_returns_data_if_no_privacy_breaches", "tests/test_report.py::test_check_privacy_wrapper_raises_if_data_contains_privacy_breaches[[email protected]]", "tests/test_report.py::test_check_privacy_wrapper_raises_if_data_contains_privacy_breaches[address-10", "tests/test_report.py::test_check_privacy_wrapper_raises_if_data_contains_privacy_breaches[phone", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[5]", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[output1]", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[output2]", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[output]", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[output4]", "tests/test_report.py::test_check_privacy_wrapper_returns_output_if_output_not_pandas_dataframe[output5]" ]
[ "tests/test_report.py::test_can_report_addresses", "tests/test_report.py::test_can_report_phonenumbers", "tests/test_report.py::test_can_report_emails", "tests/test_report.py::test_report_can_accept_multiple_breaches_per_column" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-13 08:11:23+00:00
apache-2.0
741
TTitcombe__PrivacyPanda-7
diff --git a/privacypanda/__init__.py b/privacypanda/__init__.py index a13b45a..5e891fe 100644 --- a/privacypanda/__init__.py +++ b/privacypanda/__init__.py @@ -1,3 +1,4 @@ from .addresses import * +from .anonymize import * __version__ = "0.1.0dev" diff --git a/privacypanda/addresses.py b/privacypanda/addresses.py index 5198ecc..6613cbc 100644 --- a/privacypanda/addresses.py +++ b/privacypanda/addresses.py @@ -4,12 +4,12 @@ Code for identifying addresses import re from typing import List -import numpy as np import pandas as pd +from numpy import dtype as np_dtype __all__ = ["check_addresses"] -OBJECT_DTYPE = np.dtype("O") +OBJECT_DTYPE = np_dtype("O") # ----- Regex constants ----- # LETTER = "[a-zA-Z]" @@ -55,6 +55,7 @@ def check_addresses(df: pd.DataFrame) -> List: # Only check column if it may contain strings if row.dtype == OBJECT_DTYPE: for item in row: + item = str(item) # convert incase column has mixed data types if UK_POSTCODE_PATTERN.match(item) or SIMPLE_ADDRESS_PATTERN.match( item diff --git a/privacypanda/anonymize.py b/privacypanda/anonymize.py new file mode 100644 index 0000000..44596a7 --- /dev/null +++ b/privacypanda/anonymize.py @@ -0,0 +1,39 @@ +""" +Code for cleaning a dataframe of private data +""" +import pandas as pd +from numpy import unique as np_unique + +from .addresses import check_addresses + + +def anonymize(df: pd.DataFrame) -> pd.DataFrame: + """ + Remove private data from a dataframe + + Any column containing at least one piece of private data is removed from + the dataframe. This is a naive solution but limits the possibility of + false negatives. + + Parameters + ---------- + df : pd.DataFrame + The dataframe to anonymize + + Returns + ------- + pd.DataFrame + The dataframe with columns containing private data removed + """ + private_cols = [] + + checks = [check_addresses] + for check in checks: + new_private_cols = check(df) + private_cols += new_private_cols + + # Get unique columns + private_cols = np_unique(private_cols).tolist() + + # Drop columns + return df.drop(private_cols, axis=1)
TTitcombe/PrivacyPanda
10176fccdedcc26629b4400b15222dec1474cb63
diff --git a/tests/test_address_identification.py b/tests/test_address_identification.py index f6100c0..396e172 100644 --- a/tests/test_address_identification.py +++ b/tests/test_address_identification.py @@ -51,3 +51,18 @@ def test_address_check_returns_empty_list_if_no_addresses_found(): expected_private_columns = [] assert actual_private_columns == expected_private_columns + + +def test_check_addresses_can_handle_mixed_dtype_columns(): + df = pd.DataFrame( + { + "privateColumn": [True, "AB1 1AB", "c"], + "privateColumn2": [1, "b", "10 Downing Street"], + "nonPrivateColumn": [0, True, "test"], + } + ) + + actual_private_columns = pp.check_addresses(df) + expected_private_columns = ["privateColumn", "privateColumn2"] + + assert actual_private_columns == expected_private_columns diff --git a/tests/test_anonymization.py b/tests/test_anonymization.py new file mode 100644 index 0000000..916ba93 --- /dev/null +++ b/tests/test_anonymization.py @@ -0,0 +1,53 @@ +""" +Test functions for anonymizing dataframes +""" +import pandas as pd +import pytest + +import privacypanda as pp + + [email protected]( + "address", + [ + "10 Downing Street", + "10 downing street", + "1 the Road", + "01 The Road", + "1234 The Road", + "55 Maple Avenue", + "4 Python Way", + "AB1 1AB", + "AB12 1AB", + ], +) +def test_removes_columns_containing_addresses(address): + df = pd.DataFrame( + { + "privateData": ["a", "b", "c", address], + "nonPrivateData": ["a", "b", "c", "d"], + "nonPrivataData2": [1, 2, 3, 4], + } + ) + + expected_df = pd.DataFrame( + {"nonPrivateData": ["a", "b", "c", "d"], "nonPrivataData2": [1, 2, 3, 4]} + ) + + actual_df = pp.anonymize(df) + + pd.testing.assert_frame_equal(actual_df, expected_df) + + +def test_returns_empty_dataframe_if_all_columns_contain_private_information(): + df = pd.DataFrame( + { + "nonPrivateData": ["a", "AB1 1AB", "c", "d"], + "PrivataData2": [1, 2, 3, "AB1 1AB"], + } + ) + + expected_df = pd.DataFrame(index=[0, 1, 2, 3]) + actual_df = pp.anonymize(df) + + pd.testing.assert_frame_equal(actual_df, expected_df)
Remove privacy-breaching columns **The issue** The simplest way to handle edge cases is to remove a column which contains _any_ breach of privacy. **Proposed solution** There should exist a function which identifies columns in a dataframe which contain privacy-breaching data and returns the dataframe with those columns removed
0.0
10176fccdedcc26629b4400b15222dec1474cb63
[ "tests/test_address_identification.py::test_check_addresses_can_handle_mixed_dtype_columns", "tests/test_anonymization.py::test_removes_columns_containing_addresses[10", "tests/test_anonymization.py::test_removes_columns_containing_addresses[1", "tests/test_anonymization.py::test_removes_columns_containing_addresses[01", "tests/test_anonymization.py::test_removes_columns_containing_addresses[1234", "tests/test_anonymization.py::test_removes_columns_containing_addresses[55", "tests/test_anonymization.py::test_removes_columns_containing_addresses[4", "tests/test_anonymization.py::test_removes_columns_containing_addresses[AB1", "tests/test_anonymization.py::test_removes_columns_containing_addresses[AB12" ]
[ "tests/test_address_identification.py::test_can_identify_column_containing_UK_postcode[AB1", "tests/test_address_identification.py::test_can_identify_column_containing_UK_postcode[AB12", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[10", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[1", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[01", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[1234", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[55", "tests/test_address_identification.py::test_can_identify_column_containing_simple_street_names[4", "tests/test_address_identification.py::test_address_check_returns_empty_list_if_no_addresses_found" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-02-25 10:17:01+00:00
apache-2.0
742
TabViewer__tabview-165
diff --git a/tabview/tabview.py b/tabview/tabview.py index c98188a..b7f441c 100644 --- a/tabview/tabview.py +++ b/tabview/tabview.py @@ -25,6 +25,11 @@ from textwrap import wrap import unicodedata import shlex +if sys.version_info.major < 3: + from urlparse import urlparse +else: + from urllib.parse import urlparse + if sys.version_info.major < 3: # Python 2.7 shim @@ -1356,7 +1361,8 @@ def view(data, enc=None, start_pos=(0, 0), column_width=20, column_gap=2, while True: try: if isinstance(data, basestring): - with open(data, 'rb') as fd: + parsed_path = parse_path(data) + with open(parsed_path, 'rb') as fd: new_data = fd.readlines() if info == "": info = data @@ -1395,3 +1401,8 @@ def view(data, enc=None, start_pos=(0, 0), column_width=20, column_gap=2, finally: if lc_all is not None: locale.setlocale(locale.LC_ALL, lc_all) + + +def parse_path(path): + parse_result = urlparse(path) + return parse_result.path
TabViewer/tabview
b73659ffa8469d132f91d7abf3c19e117fe8b145
diff --git a/test/test_tabview.py b/test/test_tabview.py index b82c38e..91f4409 100644 --- a/test/test_tabview.py +++ b/test/test_tabview.py @@ -107,6 +107,26 @@ class TestTabviewUnits(unittest.TestCase): i = str(i) self.assertEqual(i, res[0][j]) + def test_tabview_uri_parse(self): + # Strip 'file://' from uri (three slashes) + path = t.parse_path('file:///home/user/test.csv') + self.assertEqual(path, '/home/user/test.csv') + + # Two slashes + path = t.parse_path('file://localhost/test.csv') + self.assertEqual(path, '/test.csv') + + # Don't change if no 'file://' in string + path = t.parse_path('/home/user/test.csv') + self.assertEqual(path, '/home/user/test.csv') + + # Don't change if relative path + path = t.parse_path('../test.csv') + self.assertEqual(path, '../test.csv') + + path = t.parse_path('test.csv') + self.assertEqual(path, 'test.csv') + class TestTabviewIntegration(unittest.TestCase): """Integration tests for tabview. Run through the curses routines and some
File URI scheme not supported File URI scheme as filename is not supported: `$ tabview file://home/asparagii/test.csv` leads to a FileNotFoundException
0.0
b73659ffa8469d132f91d7abf3c19e117fe8b145
[ "test/test_tabview.py::TestTabviewUnits::test_tabview_uri_parse" ]
[ "test/test_tabview.py::TestTabviewUnits::test_tabview_encoding_latin1", "test/test_tabview.py::TestTabviewUnits::test_tabview_encoding_utf8", "test/test_tabview.py::TestTabviewUnits::test_tabview_file_annotated_comment", "test/test_tabview.py::TestTabviewUnits::test_tabview_file_latin1", "test/test_tabview.py::TestTabviewUnits::test_tabview_file_unicode" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-11-17 13:04:32+00:00
mit
743
Tadaboody__doctree-14
diff --git a/src/doctree.py b/src/doctree.py index 531c7c4..2923f89 100644 --- a/src/doctree.py +++ b/src/doctree.py @@ -4,11 +4,10 @@ from pathlib import Path from typing import Tuple, Generator from src.git_ignored_files import git_ignored_files -from src.py_comment_extractor import module_docstring, package_docstring +from src.py_comment_extractor import docstring from src.dfs import dfs, safe_iterdir BACKSLASH = '\\' -SLASH = '/' def ignored(filename: Path, starting_dir: Path, ignored_globs: Tuple[Path, ...]): @@ -40,8 +39,8 @@ def tree_dir(starting_dir: Path, ignored_globs=DEFAULT_IGNORE, max_depth=None) - for item, depth in dfs_walk: # item is all the things in the directory that does not ignored full_path = Path.resolve(item) - docstring = module_docstring(full_path) + package_docstring(full_path) - doc = f' # {module_docstring(full_path)}' if docstring else '' + doc = docstring(full_path) + doc = f' # {doc}' if doc else '' yield item, doc, depth diff --git a/src/py_comment_extractor.py b/src/py_comment_extractor.py index 17be1fc..9d31209 100644 --- a/src/py_comment_extractor.py +++ b/src/py_comment_extractor.py @@ -1,35 +1,36 @@ """Extracts comments from python files""" -from pathlib import Path -import importlib.util -from types import ModuleType -from typing import Any -import os import logging -INIT_FILE = '__init__.py' - - -def import_module(module_path: os.PathLike) -> ModuleType: - module_pathlib_path = Path(module_path) - spec:Any = importlib.util.spec_from_file_location( - module_pathlib_path.name, str(module_pathlib_path)) - module:Any = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - logging.debug(module) - return module +import os +from pathlib import Path +INIT_FILE = '__init__.py' def module_docstring(module_path: os.PathLike) -> str: - logging.debug(module_path) + import ast + import inspect + module_path = Path(module_path) try: - return import_module(module_path).__doc__ or '' - except Exception: # pylint: disable=broad-except + module_ast = ast.parse(module_path.read_text(),filename=module_path.name) + except SyntaxError: return '' + module_doc = ast.get_docstring(module_ast) + non_import_body = module_ast.body + non_import_body = [ node for node in module_ast.body if not isinstance(node, (ast.Import, ast.ImportFrom)) ] + if not module_doc and len( non_import_body ) == 1 and isinstance(non_import_body[0], (ast.ClassDef,ast.FunctionDef,ast.AsyncFunctionDef)): + module_doc = ast.get_docstring(non_import_body[0]) + if not module_doc: + return '' + return inspect.cleandoc(module_doc).splitlines()[0] - -def package_docstring(package_path: Path)->str: +def package_docstring(package_path: Path) -> str: """Returns the packages docstring, extracted by its `__init__.py` file""" logging.debug(package_path) - init_file =package_path/ INIT_FILE + init_file = package_path / INIT_FILE if package_path.is_dir() and init_file.exists(): return module_docstring(init_file) return '' +def docstring(path:Path): + try: + return package_docstring(path) if path.is_dir() else module_docstring(path) + except UnicodeDecodeError: # just in case. probably better to check that path is a python file with `inspect` + return ''
Tadaboody/doctree
a456abbbb7bafa561035adda3739ef9f02ac7ae3
diff --git a/tests/test_py_comment_extractor.py b/tests/test_py_comment_extractor.py index 2a50820..9ffb2e6 100644 --- a/tests/test_py_comment_extractor.py +++ b/tests/test_py_comment_extractor.py @@ -3,18 +3,11 @@ from pathlib import Path import pytest -from src.py_comment_extractor import (import_module, module_docstring, - package_docstring) +from src.py_comment_extractor import module_docstring, package_docstring FILE_DIR = Path(__file__).parent FILE_PATH = Path(__file__) - -def test_import_module(): - this_module = import_module(FILE_PATH) - assert 'test_import_module' in dir(this_module) - - def test_module_docstring(): assert __doc__ == module_docstring(FILE_PATH)
Extract package docstring If a dir is a python package i.e. it has an `__init__.py__` file, The docstring of `__init__.py` should be used as a doc
0.0
a456abbbb7bafa561035adda3739ef9f02ac7ae3
[ "tests/test_py_comment_extractor.py::test_package_docstring[path1-Creates" ]
[ "tests/test_py_comment_extractor.py::test_module_docstring", "tests/test_py_comment_extractor.py::test_non_module_docstring", "tests/test_py_comment_extractor.py::test_package_docstring[path0-Example" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-01-08 22:27:18+00:00
mit
744
Textualize__textual-1352
diff --git a/CHANGELOG.md b/CHANGELOG.md index d1641b1a3..42111addd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed issue with auto width/height and relative children https://github.com/Textualize/textual/issues/1319 - Fixed issue with offset applied to containers https://github.com/Textualize/textual/issues/1256 - Fixed default CSS retrieval for widgets with no `DEFAULT_CSS` that inherited from widgets with `DEFAULT_CSS` https://github.com/Textualize/textual/issues/1335 +- Fixed merging of `BINDINGS` when binding inheritance is set to `None` https://github.com/Textualize/textual/issues/1351 ## [0.5.0] - 2022-11-20 diff --git a/src/textual/dom.py b/src/textual/dom.py index 0bd45fcce..49057b67d 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -229,7 +229,7 @@ class DOMNode(MessagePump): if issubclass(base, DOMNode): if not base._inherit_bindings: bindings.clear() - bindings.append(Bindings(base.BINDINGS)) + bindings.append(Bindings(base.__dict__.get("BINDINGS", []))) keys = {} for bindings_ in bindings: keys.update(bindings_.keys)
Textualize/textual
9acdd70e365c41275c55e44ba91c5c30c09aa1fd
diff --git a/tests/test_dom.py b/tests/test_dom.py index 620984361..c1b5221c0 100644 --- a/tests/test_dom.py +++ b/tests/test_dom.py @@ -45,6 +45,39 @@ def test_validate(): node.toggle_class("1") +def test_inherited_bindings(): + """Test if binding merging is done correctly when (not) inheriting bindings.""" + class A(DOMNode): + BINDINGS = [("a", "a", "a")] + + class B(A): + BINDINGS = [("b", "b", "b")] + + class C(B, inherit_bindings=False): + BINDINGS = [("c", "c", "c")] + + class D(C, inherit_bindings=False): + pass + + class E(D): + BINDINGS = [("e", "e", "e")] + + a = A() + assert list(a._bindings.keys.keys()) == ["a"] + + b = B() + assert list(b._bindings.keys.keys()) == ["a", "b"] + + c = C() + assert list(c._bindings.keys.keys()) == ["c"] + + d = D() + assert not list(d._bindings.keys.keys()) + + e = E() + assert list(e._bindings.keys.keys()) == ["e"] + + def test_get_default_css(): class A(DOMNode): pass
A `Widget`-derived widget with `inherit_bindings=False`, but no `BINDINGS`, appears to still inherit bindings This is *very* much related to #1343, but I think merits an issue of its own to consider first. The reasons *why* this happens seem clear enough, but I feel the setup may cause confusion. With Textual as it is of 0.6.0 (with the bindings for movement keys being on `Widget`), consider this widget: ```python class Odradek( Widget, inherit_bindings=False ): pass ```` vs this: ```python class Odradek( Widget, inherit_bindings=False ): BINDINGS = [] ```` In the former case the bindings of `Widget` are still inherited. In the latter they're not.
0.0
9acdd70e365c41275c55e44ba91c5c30c09aa1fd
[ "tests/test_dom.py::test_inherited_bindings" ]
[ "tests/test_dom.py::test_display_default", "tests/test_dom.py::test_display_set_bool[True-block]", "tests/test_dom.py::test_display_set_bool[False-none]", "tests/test_dom.py::test_display_set_bool[block-block]", "tests/test_dom.py::test_display_set_bool[none-none]", "tests/test_dom.py::test_display_set_invalid_value", "tests/test_dom.py::test_validate", "tests/test_dom.py::test_get_default_css", "tests/test_dom.py::test_walk_children_depth", "tests/test_dom.py::test_walk_children_with_self_depth", "tests/test_dom.py::test_walk_children_breadth", "tests/test_dom.py::test_walk_children_with_self_breadth" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-12-13 16:21:03+00:00
mit
745
Textualize__textual-1359
diff --git a/CHANGELOG.md b/CHANGELOG.md index a8a4fa91e..96d5e88ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed +- Fixed validator not running on first reactive set https://github.com/Textualize/textual/pull/1359 - Ensure only printable characters are used as key_display https://github.com/Textualize/textual/pull/1361 ## [0.6.0] - 2022-12-11 diff --git a/docs/widgets/list_item.md b/docs/widgets/list_item.md index 1ceb65e31..5a9ed4435 100644 --- a/docs/widgets/list_item.md +++ b/docs/widgets/list_item.md @@ -2,8 +2,8 @@ `ListItem` is the type of the elements in a `ListView`. -- [] Focusable -- [] Container +- [ ] Focusable +- [ ] Container ## Example diff --git a/docs/widgets/text_log.md b/docs/widgets/text_log.md index 8a8f690d8..ccc7ea78c 100644 --- a/docs/widgets/text_log.md +++ b/docs/widgets/text_log.md @@ -41,4 +41,4 @@ This widget sends no messages. ## See Also -* [TextLog](../api/textlog.md) code reference +* [TextLog](../api/text_log.md) code reference diff --git a/mkdocs.yml b/mkdocs.yml index 4f3247d92..7f73787b3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -112,7 +112,6 @@ nav: - "api/color.md" - "api/containers.md" - "api/data_table.md" - - "api/text_log.md" - "api/directory_tree.md" - "api/dom_node.md" - "api/events.md" @@ -130,6 +129,7 @@ nav: - "api/reactive.md" - "api/screen.md" - "api/static.md" + - "api/text_log.md" - "api/timer.md" - "api/walk.md" - "api/widget.md" diff --git a/src/textual/reactive.py b/src/textual/reactive.py index c71070ba3..88b10cd04 100644 --- a/src/textual/reactive.py +++ b/src/textual/reactive.py @@ -177,8 +177,8 @@ class Reactive(Generic[ReactiveType]): validate_function = getattr(obj, f"validate_{name}", None) # Check if this is the first time setting the value first_set = getattr(obj, f"__first_set_{self.internal_name}", True) - # Call validate, but not on first set. - if callable(validate_function) and not first_set: + # Call validate + if callable(validate_function): value = validate_function(value) # If the value has changed, or this is the first time setting the value if current_value != value or first_set or self._always_update:
Textualize/textual
b9f2382f96e4ce96a859b6c4baccde70cfb8dc53
diff --git a/tests/test_reactive.py b/tests/test_reactive.py index dc3ca9958..6ccfa0656 100644 --- a/tests/test_reactive.py +++ b/tests/test_reactive.py @@ -2,9 +2,8 @@ import asyncio import pytest -from textual.app import App, ComposeResult +from textual.app import App from textual.reactive import reactive, var -from textual.widget import Widget OLD_VALUE = 5_000 NEW_VALUE = 1_000_000 @@ -81,14 +80,16 @@ async def test_watch_async_init_true(): try: await asyncio.wait_for(app.watcher_called_event.wait(), timeout=0.05) except TimeoutError: - pytest.fail("Async watcher wasn't called within timeout when reactive init = True") + pytest.fail( + "Async watcher wasn't called within timeout when reactive init = True") assert app.count == OLD_VALUE assert app.watcher_old_value == OLD_VALUE assert app.watcher_new_value == OLD_VALUE # The value wasn't changed [email protected](reason="Reactive watcher is incorrectly always called the first time it is set, even if value is same [issue#1230]") [email protected]( + reason="Reactive watcher is incorrectly always called the first time it is set, even if value is same [issue#1230]") async def test_watch_init_false_always_update_false(): class WatcherInitFalse(App): count = reactive(0, init=False) @@ -173,20 +174,45 @@ async def test_reactive_with_callable_default(): assert app.watcher_called_with == OLD_VALUE [email protected](reason="Validator methods not running when init=True [issue#1220]") async def test_validate_init_true(): """When init is True for a reactive attribute, Textual should call the validator AND the watch method when the app starts.""" + validator_call_count = 0 class ValidatorInitTrue(App): count = var(5, init=True) def validate_count(self, value: int) -> int: + nonlocal validator_call_count + validator_call_count += 1 return value + 1 app = ValidatorInitTrue() async with app.run_test(): + app.count = 5 assert app.count == 6 # Validator should run, so value should be 5+1=6 + assert validator_call_count == 1 + + +async def test_validate_init_true_set_before_dom_ready(): + """When init is True for a reactive attribute, Textual should call the validator + AND the watch method when the app starts.""" + validator_call_count = 0 + + class ValidatorInitTrue(App): + count = var(5, init=True) + + def validate_count(self, value: int) -> int: + nonlocal validator_call_count + validator_call_count += 1 + return value + 1 + + app = ValidatorInitTrue() + app.count = 5 + async with app.run_test(): + assert app.count == 6 # Validator should run, so value should be 5+1=6 + assert validator_call_count == 1 + @pytest.mark.xfail(reason="Compute methods not called when init=True [issue#1227]")
Validators and watchers should run hand-in-hand When `init=True` in a `reactive` attribute, the `watch_` method for that attribute run, but the `validate_` method does not. This seems rather confusing and we think that validators and watchers should always run hand-in-hand. If the watcher is called, you should be confident that the incoming `new_value` has already been validated by the `validate_` method.
0.0
b9f2382f96e4ce96a859b6c4baccde70cfb8dc53
[ "tests/test_reactive.py::test_validate_init_true", "tests/test_reactive.py::test_validate_init_true_set_before_dom_ready" ]
[ "tests/test_reactive.py::test_watch", "tests/test_reactive.py::test_watch_async_init_false", "tests/test_reactive.py::test_watch_async_init_true", "tests/test_reactive.py::test_watch_init_true", "tests/test_reactive.py::test_reactive_always_update", "tests/test_reactive.py::test_reactive_with_callable_default" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-14 11:28:31+00:00
mit
746
Textualize__textual-1423
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dc19b1ea..43062e425 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed issues with nested auto dimensions https://github.com/Textualize/textual/issues/1402 - Fixed watch method incorrectly running on first set when value hasn't changed and init=False https://github.com/Textualize/textual/pull/1367 - `App.dark` can now be set from `App.on_load` without an error being raised https://github.com/Textualize/textual/issues/1369 +- Fixed setting `visibility` changes needing a `refresh` https://github.com/Textualize/textual/issues/1355 ### Added diff --git a/src/textual/css/styles.py b/src/textual/css/styles.py index 96a28b8ba..0cff4a39e 100644 --- a/src/textual/css/styles.py +++ b/src/textual/css/styles.py @@ -209,7 +209,7 @@ class StylesBase(ABC): node: DOMNode | None = None display = StringEnumProperty(VALID_DISPLAY, "block", layout=True) - visibility = StringEnumProperty(VALID_VISIBILITY, "visible") + visibility = StringEnumProperty(VALID_VISIBILITY, "visible", layout=True) layout = LayoutProperty() auto_color = BooleanProperty(default=False)
Textualize/textual
a4aa30ebeb1782efb6d5f45792c373cb45a4739a
diff --git a/tests/test_visibility_change.py b/tests/test_visibility_change.py new file mode 100644 index 000000000..b06ea0e17 --- /dev/null +++ b/tests/test_visibility_change.py @@ -0,0 +1,46 @@ +"""See https://github.com/Textualize/textual/issues/1355 as the motivation for these tests.""" + +from textual.app import App, ComposeResult +from textual.containers import Vertical +from textual.widget import Widget + + +class VisibleTester(App[None]): + """An app for testing visibility changes.""" + + CSS = """ + Widget { + height: 1fr; + } + .hidden { + visibility: hidden; + } + """ + + def compose(self) -> ComposeResult: + yield Vertical( + Widget(id="keep"), Widget(id="hide-via-code"), Widget(id="hide-via-css") + ) + + +async def test_visibility_changes() -> None: + """Test changing visibility via code and CSS.""" + async with VisibleTester().run_test() as pilot: + assert len(pilot.app.screen.visible_widgets) == 5 + assert pilot.app.query_one("#keep").visible is True + assert pilot.app.query_one("#hide-via-code").visible is True + assert pilot.app.query_one("#hide-via-css").visible is True + + pilot.app.query_one("#hide-via-code").styles.visibility = "hidden" + await pilot.pause(0) + assert len(pilot.app.screen.visible_widgets) == 4 + assert pilot.app.query_one("#keep").visible is True + assert pilot.app.query_one("#hide-via-code").visible is False + assert pilot.app.query_one("#hide-via-css").visible is True + + pilot.app.query_one("#hide-via-css").set_class(True, "hidden") + await pilot.pause(0) + assert len(pilot.app.screen.visible_widgets) == 3 + assert pilot.app.query_one("#keep").visible is True + assert pilot.app.query_one("#hide-via-code").visible is False + assert pilot.app.query_one("#hide-via-css").visible is False
UI doesn't react to visibility flag change I have an app that has a dialogue box that is invisible unless someone clicks a button. When they do, I want the dialogue to appear instantly so they can confirm their action. The dialogue is in a "higher" layer than the rest of the app, and it starts invisible based on CSS. When they click a button, I change it to visible, but it doesn't appear until something else makes the window redraw. For eg, if i resize the window, it appears instantly. starting CSS: ``` #confirm_panel { width: 30%; height: 16%; border: lime double; overflow: hidden; layer: above; offset: 50 20; visibility: hidden; } ``` Change to visible. I have tried it via styles and via the new visible flag. Both have the same behavior: ``` self.query_one('#confirm_panel').styles.visibility = 'visible' ``` Using 0.6.0
0.0
a4aa30ebeb1782efb6d5f45792c373cb45a4739a
[ "tests/test_visibility_change.py::test_visibility_changes" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-12-21 14:35:07+00:00
mit
747
Textualize__textual-1427
diff --git a/CHANGELOG.md b/CHANGELOG.md index aff340411..d0e5349c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [0.8.3] - Unreleased + +### Added + +- Added an option to clear columns in DataTable.clear() https://github.com/Textualize/textual/pull/1427 + ## [0.8.2] - 2022-12-28 ### Fixed diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index 5d6d0a0e0..726e3e2b5 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -312,7 +312,7 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): cell_region = Region(x, y, width, height) return cell_region - def clear(self) -> None: + def clear(self, columns: bool = False) -> None: """Clear the table. Args: @@ -323,6 +323,8 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): self._y_offsets.clear() self.data.clear() self.rows.clear() + if columns: + self.columns.clear() self._line_no = 0 self._require_update_dimensions = True self.refresh()
Textualize/textual
cef386a40abcdf3ba8284ed07ca4689d8d97315d
diff --git a/tests/test_table.py b/tests/test_table.py index 8369efdef..827242e85 100644 --- a/tests/test_table.py +++ b/tests/test_table.py @@ -1,5 +1,7 @@ import asyncio +from rich.text import Text + from textual.app import App, ComposeResult from textual.widgets import DataTable @@ -18,13 +20,32 @@ async def test_table_clear() -> None: table.add_columns("foo", "bar") assert table.row_count == 0 table.add_row("Hello", "World!") + assert [col.label for col in table.columns] == [Text("foo"), Text("bar")] assert table.data == {0: ["Hello", "World!"]} assert table.row_count == 1 table.clear() + assert [col.label for col in table.columns] == [Text("foo"), Text("bar")] assert table.data == {} assert table.row_count == 0 +async def test_table_clear_with_columns() -> None: + """Check DataTable.clear(columns=True)""" + + app = TableApp() + async with app.run_test() as pilot: + table = app.query_one(DataTable) + table.add_columns("foo", "bar") + assert table.row_count == 0 + table.add_row("Hello", "World!") + assert [col.label for col in table.columns] == [Text("foo"), Text("bar")] + assert table.data == {0: ["Hello", "World!"]} + assert table.row_count == 1 + table.clear(columns=True) + assert [col.label for col in table.columns] == [] + assert table.data == {} + assert table.row_count == 0 + async def test_table_add_row() -> None: app = TableApp()
Support clearing columns via `DataTable.clear()` Looks like this feature must have gotten lost in the shuffle, since the docstring mentions it but the function doesn't support it: https://github.com/Textualize/textual/blob/3aaa4d3ec1cfd1be86c781a34da09e6bc99e8eff/src/textual/widgets/_data_table.py#L315-L328 Happy to do a PR for this. Is it as simple as running `self.columns.clear()` if the `columns` argument is `True`?
0.0
cef386a40abcdf3ba8284ed07ca4689d8d97315d
[ "tests/test_table.py::test_table_clear_with_columns" ]
[ "tests/test_table.py::test_table_clear", "tests/test_table.py::test_table_add_row" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-12-21 22:58:36+00:00
mit
748
Textualize__textual-1640
diff --git a/CHANGELOG.md b/CHANGELOG.md index e3ffc3dbe..01536dfaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [0.11.0] - Unreleased + +### Fixed + +- Fixed relative units in `grid-rows` and `grid-columns` being computed with respect to the wrong dimension https://github.com/Textualize/textual/issues/1406 + ## [0.10.1] - 2023-01-20 ### Added diff --git a/src/textual/cli/cli.py b/src/textual/cli/cli.py index 6c99811d7..b7048f807 100644 --- a/src/textual/cli/cli.py +++ b/src/textual/cli/cli.py @@ -1,7 +1,13 @@ from __future__ import annotations +import sys + +try: + import click +except ImportError: + print("Please install 'textual[dev]' to use the 'textual' command") + sys.exit(1) -import click from importlib_metadata import version from textual.pilot import Pilot diff --git a/src/textual/css/_style_properties.py b/src/textual/css/_style_properties.py index bfc9f90cb..6ec181b5c 100644 --- a/src/textual/css/_style_properties.py +++ b/src/textual/css/_style_properties.py @@ -202,6 +202,9 @@ class ScalarProperty: class ScalarListProperty: + def __init__(self, percent_unit: Unit) -> None: + self.percent_unit = percent_unit + def __set_name__(self, owner: Styles, name: str) -> None: self.name = name @@ -229,7 +232,7 @@ class ScalarListProperty: scalars.append(Scalar.from_number(parse_value)) else: scalars.append( - Scalar.parse(parse_value) + Scalar.parse(parse_value, self.percent_unit) if isinstance(parse_value, str) else parse_value ) diff --git a/src/textual/css/_styles_builder.py b/src/textual/css/_styles_builder.py index 9c45e14a1..14f1e5404 100644 --- a/src/textual/css/_styles_builder.py +++ b/src/textual/css/_styles_builder.py @@ -865,16 +865,12 @@ class StylesBuilder: def _process_grid_rows_or_columns(self, name: str, tokens: list[Token]) -> None: scalars: list[Scalar] = [] + percent_unit = Unit.WIDTH if name == "grid-columns" else Unit.HEIGHT for token in tokens: if token.name == "number": scalars.append(Scalar.from_number(float(token.value))) elif token.name == "scalar": - scalars.append( - Scalar.parse( - token.value, - percent_unit=Unit.WIDTH if name == "rows" else Unit.HEIGHT, - ) - ) + scalars.append(Scalar.parse(token.value, percent_unit=percent_unit)) else: self.error( name, diff --git a/src/textual/css/styles.py b/src/textual/css/styles.py index c04b24a48..1100b7320 100644 --- a/src/textual/css/styles.py +++ b/src/textual/css/styles.py @@ -277,8 +277,8 @@ class StylesBase(ABC): content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top") content_align = AlignProperty() - grid_rows = ScalarListProperty() - grid_columns = ScalarListProperty() + grid_rows = ScalarListProperty(percent_unit=Unit.HEIGHT) + grid_columns = ScalarListProperty(percent_unit=Unit.WIDTH) grid_size_columns = IntegerProperty(default=1, layout=True) grid_size_rows = IntegerProperty(default=0, layout=True)
Textualize/textual
383ab1883103cdf769b89fd6eb362f412f12679d
diff --git a/tests/css/test_grid_rows_columns_relative_units.py b/tests/css/test_grid_rows_columns_relative_units.py new file mode 100644 index 000000000..e56bec65c --- /dev/null +++ b/tests/css/test_grid_rows_columns_relative_units.py @@ -0,0 +1,42 @@ +""" +Regression tests for #1406 https://github.com/Textualize/textual/issues/1406 + +The scalars in grid-rows and grid-columns were not aware of the dimension +they should be relative to. +""" + +from textual.css.parse import parse_declarations +from textual.css.scalar import Unit +from textual.css.styles import Styles + + +def test_grid_rows_columns_relative_units_are_correct(): + """Ensure correct relative dimensions for programmatic assignments.""" + + styles = Styles() + + styles.grid_columns = "1fr 5%" + fr, percent = styles.grid_columns + assert fr.percent_unit == Unit.WIDTH + assert percent.percent_unit == Unit.WIDTH + + styles.grid_rows = "1fr 5%" + fr, percent = styles.grid_rows + assert fr.percent_unit == Unit.HEIGHT + assert percent.percent_unit == Unit.HEIGHT + + +def test_styles_builder_uses_correct_relative_units_grid_rows_columns(): + """Ensure correct relative dimensions for CSS parsed from files.""" + + CSS = "grid-rows: 1fr 5%; grid-columns: 1fr 5%;" + + styles = parse_declarations(CSS, "test") + + fr, percent = styles.grid_columns + assert fr.percent_unit == Unit.WIDTH + assert percent.percent_unit == Unit.WIDTH + + fr, percent = styles.grid_rows + assert fr.percent_unit == Unit.HEIGHT + assert percent.percent_unit == Unit.HEIGHT
Grid columns with multiple units resolves percent unit to wrong value In a grid layout with mixed units in the style `grid-columns`, the column associated with `25%` gets the wrong size. However, using `25w` or `25vw` instead of `25%` produces the correct result. Here is the screenshot of the app where the middle column should take up 25% of the total width and the 1st and 4th columns should accommodate that: ![Screenshot at Dec 19 17-30-02](https://user-images.githubusercontent.com/5621605/208485031-2864c964-b7c6-496b-a173-8618f6a3ba70.png) <details> <summary><code>grid_columns.py</code></summary> ```py from textual.app import App from textual.containers import Grid from textual.widgets import Label class MyApp(App): def compose(self): yield Grid( Label("1fr"), Label("width = 16"), Label("middle"), Label("1fr"), Label("width = 16"), ) app = MyApp(css_path="grid_columns.css") ``` </details> <details> <summary><code>grid_columns.css</code></summary> ```css Grid { grid-size: 5 1; grid-columns: 1fr 16 25%; } Label { border: round white; content-align-horizontal: center; width: 100%; height: 100%; } ``` </details> Try running the app with `textual run --dev grid_columns.css` and change the value `25%` to `25w` or `25vw` and notice it gets set to the correct value.
0.0
383ab1883103cdf769b89fd6eb362f412f12679d
[ "tests/css/test_grid_rows_columns_relative_units.py::test_grid_rows_columns_relative_units_are_correct", "tests/css/test_grid_rows_columns_relative_units.py::test_styles_builder_uses_correct_relative_units_grid_rows_columns" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-23 15:09:12+00:00
mit
749
Textualize__textual-1926
diff --git a/CHANGELOG.md b/CHANGELOG.md index 76fb3117a..a6305e842 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Added `switch` attribute to `Switch` events https://github.com/Textualize/textual/pull/1940 - Breaking change: Added `toggle_button` attribute to RadioButton and Checkbox events, replaces `input` https://github.com/Textualize/textual/pull/1940 +### Fixed + +- Fixed bug that prevented app pilot to press some keys https://github.com/Textualize/textual/issues/1815 + ## [0.13.0] - 2023-03-02 ### Added diff --git a/src/textual/_xterm_parser.py b/src/textual/_xterm_parser.py index fc4258390..d232c5a9d 100644 --- a/src/textual/_xterm_parser.py +++ b/src/textual/_xterm_parser.py @@ -8,7 +8,7 @@ from . import events, messages from ._ansi_sequences import ANSI_SEQUENCES_KEYS from ._parser import Awaitable, Parser, TokenCallback from ._types import MessageTarget -from .keys import KEY_NAME_REPLACEMENTS +from .keys import KEY_NAME_REPLACEMENTS, _character_to_key # When trying to determine whether the current sequence is a supported/valid # escape sequence, at which length should we give up and consider our search @@ -241,12 +241,7 @@ class XTermParser(Parser[events.Event]): elif len(sequence) == 1: try: if not sequence.isalnum(): - name = ( - _unicode_name(sequence) - .lower() - .replace("-", "_") - .replace(" ", "_") - ) + name = _character_to_key(sequence) else: name = sequence name = KEY_NAME_REPLACEMENTS.get(name, name) diff --git a/src/textual/app.py b/src/textual/app.py index a17a5825b..e7785379a 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -70,7 +70,12 @@ from .features import FeatureFlag, parse_features from .file_monitor import FileMonitor from .filter import LineFilter, Monochrome from .geometry import Offset, Region, Size -from .keys import REPLACED_KEYS, _get_key_display +from .keys import ( + REPLACED_KEYS, + _character_to_key, + _get_key_display, + _get_unicode_name_from_key, +) from .messages import CallbackType from .reactive import Reactive from .renderables.blank import Blank @@ -865,16 +870,11 @@ class App(Generic[ReturnType], DOMNode): await asyncio.sleep(float(wait_ms) / 1000) else: if len(key) == 1 and not key.isalnum(): - key = ( - unicodedata.name(key) - .lower() - .replace("-", "_") - .replace(" ", "_") - ) + key = _character_to_key(key) original_key = REPLACED_KEYS.get(key, key) char: str | None try: - char = unicodedata.lookup(original_key.upper().replace("_", " ")) + char = unicodedata.lookup(_get_unicode_name_from_key(original_key)) except KeyError: char = key if len(key) == 1 else None print(f"press {key!r} (char={char!r})") diff --git a/src/textual/keys.py b/src/textual/keys.py index 1c5fe219d..ef32404d1 100644 --- a/src/textual/keys.py +++ b/src/textual/keys.py @@ -211,6 +211,37 @@ KEY_NAME_REPLACEMENTS = { } REPLACED_KEYS = {value: key for key, value in KEY_NAME_REPLACEMENTS.items()} +# Convert the friendly versions of character key Unicode names +# back to their original names. +# This is because we go from Unicode to friendly by replacing spaces and dashes +# with underscores, which cannot be undone by replacing underscores with spaces/dashes. +KEY_TO_UNICODE_NAME = { + "exclamation_mark": "EXCLAMATION MARK", + "quotation_mark": "QUOTATION MARK", + "number_sign": "NUMBER SIGN", + "dollar_sign": "DOLLAR SIGN", + "percent_sign": "PERCENT SIGN", + "left_parenthesis": "LEFT PARENTHESIS", + "right_parenthesis": "RIGHT PARENTHESIS", + "plus_sign": "PLUS SIGN", + "hyphen_minus": "HYPHEN-MINUS", + "full_stop": "FULL STOP", + "less_than_sign": "LESS-THAN SIGN", + "equals_sign": "EQUALS SIGN", + "greater_than_sign": "GREATER-THAN SIGN", + "question_mark": "QUESTION MARK", + "commercial_at": "COMMERCIAL AT", + "left_square_bracket": "LEFT SQUARE BRACKET", + "reverse_solidus": "REVERSE SOLIDUS", + "right_square_bracket": "RIGHT SQUARE BRACKET", + "circumflex_accent": "CIRCUMFLEX ACCENT", + "low_line": "LOW LINE", + "grave_accent": "GRAVE ACCENT", + "left_curly_bracket": "LEFT CURLY BRACKET", + "vertical_line": "VERTICAL LINE", + "right_curly_bracket": "RIGHT CURLY BRACKET", +} + # Some keys have aliases. For example, if you press `ctrl+m` on your keyboard, # it's treated the same way as if you press `enter`. Key handlers `key_ctrl_m` and # `key_enter` are both valid in this case. @@ -235,6 +266,14 @@ KEY_DISPLAY_ALIASES = { } +def _get_unicode_name_from_key(key: str) -> str: + """Get the best guess for the Unicode name of the char corresponding to the key. + + This function can be seen as a pseudo-inverse of the function `_character_to_key`. + """ + return KEY_TO_UNICODE_NAME.get(key, key.upper()) + + def _get_key_aliases(key: str) -> list[str]: """Return all aliases for the given key, including the key itself""" return [key] + KEY_ALIASES.get(key, []) @@ -249,22 +288,24 @@ def _get_key_display(key: str) -> str: return display_alias original_key = REPLACED_KEYS.get(key, key) - upper_original = original_key.upper().replace("_", " ") + tentative_unicode_name = _get_unicode_name_from_key(original_key) try: - unicode_character = unicodedata.lookup(upper_original) + unicode_character = unicodedata.lookup(tentative_unicode_name) except KeyError: - return upper_original + return tentative_unicode_name # Check if printable. `delete` for example maps to a control sequence # which we don't want to write to the terminal. if unicode_character.isprintable(): return unicode_character - return upper_original + return tentative_unicode_name def _character_to_key(character: str) -> str: - """Convert a single character to a key value.""" - assert len(character) == 1 + """Convert a single character to a key value. + + This transformation can be undone by the function `_get_unicode_name_from_key`. + """ if not character.isalnum(): key = unicodedata.name(character).lower().replace("-", "_").replace(" ", "_") else:
Textualize/textual
623b70d4ac8983ac104b27062abab3cb2bbdbdfa
diff --git a/tests/test_pilot.py b/tests/test_pilot.py new file mode 100644 index 000000000..2ca527895 --- /dev/null +++ b/tests/test_pilot.py @@ -0,0 +1,23 @@ +from string import punctuation + +from textual import events +from textual.app import App + +KEY_CHARACTERS_TO_TEST = "akTW03" + punctuation.replace("_", "") +"""Test some "simple" characters (letters + digits) and all punctuation. +Ignore the underscore because that is an alias to add a pause in the pilot. +""" + + +async def test_pilot_press_ascii_chars(): + """Test that the pilot can press most ASCII characters as keys.""" + keys_pressed = [] + + class TestApp(App[None]): + def on_key(self, event: events.Key) -> None: + keys_pressed.append(event.character) + + async with TestApp().run_test() as pilot: + for char in KEY_CHARACTERS_TO_TEST: + await pilot.press(char) + assert keys_pressed[-1] == char
Pilot cannot press key minus The way `App._press_keys` is implemented is flawed in here: https://github.com/Textualize/textual/blob/ba6c8afac6ffb78dffeab9ebdc7c115fd28cd40b/src/textual/app.py#L830-L842 There is a clear bug because the transformation done on `key` with two consecutive replacements cannot be undone in line 840 with a single replacement. In particular, the keys HYPHEN-MINUS and REVERSE SOLIDUS show that the underscores that we get after the two consecutive replacements cannot be unambiguously reverted. On top of that, I have to understand what is the issue with a key that has length 1 and is not "alnum". For example, `"-"` has length 1, is not "alnum", and could very well be pressed as is. Maybe we want to check if `key.isprintable` instead?
0.0
623b70d4ac8983ac104b27062abab3cb2bbdbdfa
[ "tests/test_pilot.py::test_pilot_press_ascii_chars" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-02 17:34:37+00:00
mit
750
Textualize__textual-2038
diff --git a/CHANGELOG.md b/CHANGELOG.md index 66273dcfe..49d764f65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). + +## Unreleased + +### Fixed + +- Fixed how the namespace for messages is calculated to facilitate inheriting messages https://github.com/Textualize/textual/issues/1814 + ## [0.15.0] - 2023-03-13 ### Fixed diff --git a/src/textual/message_pump.py b/src/textual/message_pump.py index 3a1ac9eb2..0ce2b981b 100644 --- a/src/textual/message_pump.py +++ b/src/textual/message_pump.py @@ -62,7 +62,7 @@ class MessagePumpMeta(type): isclass = inspect.isclass for value in class_dict.values(): if isclass(value) and issubclass(value, Message): - if not value.namespace: + if "namespace" not in value.__dict__: value.namespace = namespace class_obj = super().__new__(cls, name, bases, class_dict, **kwargs) return class_obj
Textualize/textual
a3887dfcbb7fe47cc6e10da7645d01cffe1a91e3
diff --git a/tests/test_message_handling.py b/tests/test_message_handling.py new file mode 100644 index 000000000..31edeb2cf --- /dev/null +++ b/tests/test_message_handling.py @@ -0,0 +1,45 @@ +from textual.app import App, ComposeResult +from textual.message import Message +from textual.widget import Widget + + +async def test_message_inheritance_namespace(): + """Inherited messages get their correct namespaces. + + Regression test for https://github.com/Textualize/textual/issues/1814. + """ + + class BaseWidget(Widget): + class Fired(Message): + pass + + def trigger(self) -> None: + self.post_message(self.Fired()) + + class Left(BaseWidget): + class Fired(BaseWidget.Fired): + pass + + class Right(BaseWidget): + class Fired(BaseWidget.Fired): + pass + + handlers_called = [] + + class MessageInheritanceApp(App[None]): + def compose(self) -> ComposeResult: + yield Left() + yield Right() + + def on_left_fired(self): + handlers_called.append("left") + + def on_right_fired(self): + handlers_called.append("right") + + app = MessageInheritanceApp() + async with app.run_test(): + app.query_one(Left).trigger() + app.query_one(Right).trigger() + + assert handlers_called == ["left", "right"]
Investigate an improvement to how the namespace of messages is calculated Consider the following code, where there is a base class for two widgets that share a *lot* in common but have slightly different uses/APIs/reasons-to-exist. They both have a `value` in common and so will have a `Changed` message (consider this almost pseudocode to save me trying out *all* of the details): ```python class MyBaseWidget( Widget ): value: reactive[bool] = reactive( False ) class Changed( Message ): pass def watch_value( self ) -> None: self.post_message_no_wait( self.Changed() ) class HelloWidget( MyBaseWidget ): ... class GoodbyeWidget( MyBaseWidget ): ... ``` To allow for sharing the bulk of the `Changed` message code between the two child classes, it would be useful if they could be declared something like this: ```python class HelloWidget( MyBaseWidget ): class Changed( MyBaseWidget.Changed ): pass class GoodbyeWidget( MyBaseWidget ): class Changed( MyBaseWidget.Changed ): pass ``` This almost works perfectly, expect that the message handlers that are looked for end up always being called `on_my_base_widget_changed` when we would want them to be `on_hello_widget_changed` and `on_goodbye_widget_changed`. This can be achieved and works perfectly if you do the following: ```python class HelloWidget( MyBaseWidget ): class Changed( MyBaseWidget.Changed ): namespace = "hello_widget" class GoodbyeWidget( MyBaseWidget ): class Changed( MyBaseWidget.Changed ): namespace = "goodbye_widget" ``` With this setup the parent widget can be "internal" and do almost all of the work and the two child classes can just handle their own differences *and* the events end up with the right names. So... so far so good, it works fine, there's no issue here. However, in conversation about this with Will, we believe that the Textual internals that work out the namespace for a given message *should* get the above right without the need to declare the `namespace`. So the purpose of this issue is, at some point, to dive into [this code or thereabouts](https://github.com/Textualize/textual/blob/ba6c8afac6ffb78dffeab9ebdc7c115fd28cd40b/src/textual/message_pump.py#L54-L61) and see if there's a reason why the `namespace` isn't worked out as we'd expect here.
0.0
a3887dfcbb7fe47cc6e10da7645d01cffe1a91e3
[ "tests/test_message_handling.py::test_message_inheritance_namespace" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-03-13 15:18:25+00:00
mit
751
Textualize__textual-219
diff --git a/examples/dev_sandbox.css b/examples/dev_sandbox.css new file mode 100644 index 000000000..2e348e134 --- /dev/null +++ b/examples/dev_sandbox.css @@ -0,0 +1,49 @@ +/* CSS file for dev_sandbox.py */ + +App > View { + docks: side=left/1; + text: on #20639b; +} + +Widget:hover { + outline: heavy; + text: bold !important; +} + +#sidebar { + text: #09312e on #3caea3; + dock: side; + width: 30; + offset-x: -100%; + transition: offset 500ms in_out_cubic; + border-right: outer #09312e; +} + +#sidebar.-active { + offset-x: 0; +} + +#header { + text: white on #173f5f; + height: 3; + border: hkey; +} + +#header.-visible { + visibility: hidden; +} + +#content { + text: white on #20639b; + border-bottom: hkey #0f2b41; + offset-y: -3; +} + +#content.-content-visible { + visibility: hidden; +} + +#footer { + text: #3a3009 on #f6d55c; + height: 3; +} diff --git a/examples/dev_sandbox.py b/examples/dev_sandbox.py new file mode 100644 index 000000000..d53946fb3 --- /dev/null +++ b/examples/dev_sandbox.py @@ -0,0 +1,32 @@ +from rich.console import RenderableType +from rich.panel import Panel + +from textual.app import App +from textual.widget import Widget + + +class PanelWidget(Widget): + def render(self) -> RenderableType: + return Panel("hello world!", title="Title") + + +class BasicApp(App): + """Sandbox application used for testing/development by Textual developers""" + + def on_load(self): + """Bind keys here.""" + self.bind("tab", "toggle_class('#sidebar', '-active')") + self.bind("a", "toggle_class('#header', '-visible')") + self.bind("c", "toggle_class('#content', '-content-visible')") + + def on_mount(self): + """Build layout here.""" + self.mount( + header=Widget(), + content=PanelWidget(), + footer=Widget(), + sidebar=Widget(), + ) + + +BasicApp.run(css_file="test_app.css", watch_css=True, log="textual.log") diff --git a/src/textual/dom.py b/src/textual/dom.py index 8b17700ed..566f62858 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -9,7 +9,7 @@ from rich.style import Style from rich.tree import Tree from .css._error_tools import friendly_list -from .css.constants import VALID_DISPLAY +from .css.constants import VALID_DISPLAY, VALID_VISIBILITY from .css.errors import StyleValueError from .css.styles import Styles from .message_pump import MessagePump @@ -160,6 +160,22 @@ class DOMNode(MessagePump): f"expected {friendly_list(VALID_DISPLAY)})", ) + @property + def visible(self) -> bool: + return self.styles.visibility != "hidden" + + @visible.setter + def visible(self, new_value: bool) -> None: + if isinstance(new_value, bool): + self.styles.visibility = "visible" if new_value else "hidden" + elif new_value in VALID_VISIBILITY: + self.styles.visibility = new_value + else: + raise StyleValueError( + f"invalid value for visibility (received {new_value!r}, " + f"expected {friendly_list(VALID_VISIBILITY)})" + ) + @property def z(self) -> tuple[int, ...]: """Get the z index tuple for this node. diff --git a/src/textual/layout.py b/src/textual/layout.py index 72f5e1422..8542e5942 100644 --- a/src/textual/layout.py +++ b/src/textual/layout.py @@ -199,6 +199,15 @@ class Layout(ABC): raise NoWidget(f"No widget under screen coordinate ({x}, {y})") def get_style_at(self, x: int, y: int) -> Style: + """Get the Style at the given cell or Style.null() + + Args: + x (int): X position within the Layout + y (int): Y position within the Layout + + Returns: + Style: The Style at the cell (x, y) within the Layout + """ try: widget, region = self.get_widget_at(x, y) except NoWidget: @@ -217,6 +226,18 @@ class Layout(ABC): return Style.null() def get_widget_region(self, widget: Widget) -> Region: + """Get the Region of a Widget contained in this Layout. + + Args: + widget (Widget): The Widget in this layout you wish to know the Region of. + + Raises: + NoWidget: If the Widget is not contained in this Layout. + + Returns: + Region: The Region of the Widget. + + """ try: region, *_ = self.map[widget] except KeyError: @@ -270,7 +291,7 @@ class Layout(ABC): for widget, region, _order, clip in widget_regions: - if not widget.is_visual: + if not (widget.is_visual and widget.visible): continue lines = widget._get_lines() diff --git a/src/textual/view.py b/src/textual/view.py index d6cd03784..220551eb7 100644 --- a/src/textual/view.py +++ b/src/textual/view.py @@ -1,26 +1,19 @@ from __future__ import annotations -from itertools import chain -from typing import Callable, Iterable, ClassVar, TYPE_CHECKING +from typing import Callable, Iterable -from rich.console import RenderableType import rich.repr +from rich.console import RenderableType from rich.style import Style -from . import events from . import errors -from . import log +from . import events from . import messages +from .geometry import Size, Offset, Region from .layout import Layout, NoWidget, WidgetPlacement from .layouts.factory import get_layout -from .geometry import Size, Offset, Region from .reactive import Reactive, watch - -from .widget import Widget, Widget - - -if TYPE_CHECKING: - from .app import App +from .widget import Widget class LayoutProperty: diff --git a/src/textual/widget.py b/src/textual/widget.py index 51c7e97ab..94d768129 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -1,6 +1,6 @@ from __future__ import annotations -from logging import PercentStyle, getLogger +from logging import getLogger from typing import ( Any, Awaitable, @@ -11,35 +11,29 @@ from typing import ( NamedTuple, cast, ) + import rich.repr -from rich import box from rich.align import Align -from rich.console import Console, RenderableType, ConsoleOptions -from rich.measure import Measurement -from rich.panel import Panel +from rich.console import Console, RenderableType from rich.padding import Padding -from rich.pretty import Pretty -from rich.segment import Segment -from rich.style import Style, StyleType +from rich.style import Style from rich.styled import Styled -from rich.text import Text, TextType +from rich.text import Text -from . import events from . import errors +from . import events from ._animator import BoundAnimator -from ._border import Border, BORDER_STYLES +from ._border import Border from ._callback import invoke -from .blank import Blank -from .dom import DOMNode from ._context import active_app -from .geometry import Size, Spacing, SpacingDimensions +from ._types import Lines +from .dom import DOMNode +from .geometry import Size, Spacing from .message import Message from .messages import Layout, Update -from .reactive import Reactive, watch -from ._types import Lines +from .reactive import watch if TYPE_CHECKING: - from .app import App from .view import View log = getLogger("rich") @@ -163,34 +157,29 @@ class Widget(DOMNode): styles = self.styles parent_text_style = self.parent.text_style - if styles.visibility == "hidden": - renderable = Blank(parent_text_style) - else: - text_style = styles.text - renderable_text_style = parent_text_style + text_style - if renderable_text_style: - renderable = Styled(renderable, renderable_text_style) - - if styles.has_padding: - renderable = Padding( - renderable, styles.padding, style=renderable_text_style - ) - - if styles.has_border: - renderable = Border( - renderable, styles.border, style=renderable_text_style - ) - - if styles.has_margin: - renderable = Padding(renderable, styles.margin, style=parent_text_style) - - if styles.has_outline: - renderable = Border( - renderable, - styles.outline, - outline=True, - style=renderable_text_style, - ) + text_style = styles.text + renderable_text_style = parent_text_style + text_style + if renderable_text_style: + renderable = Styled(renderable, renderable_text_style) + + if styles.has_padding: + renderable = Padding( + renderable, styles.padding, style=renderable_text_style + ) + + if styles.has_border: + renderable = Border(renderable, styles.border, style=renderable_text_style) + + if styles.has_margin: + renderable = Padding(renderable, styles.margin, style=parent_text_style) + + if styles.has_outline: + renderable = Border( + renderable, + styles.outline, + outline=True, + style=renderable_text_style, + ) return renderable
Textualize/textual
185788b7607266cc2e7609fb237be82cd3efb8b0
diff --git a/tests/test_widget.py b/tests/test_widget.py new file mode 100644 index 000000000..7eee43a54 --- /dev/null +++ b/tests/test_widget.py @@ -0,0 +1,28 @@ +import pytest + +from textual.css.errors import StyleValueError +from textual.widget import Widget + + [email protected]( + "set_val, get_val, style_str", [ + [True, True, "visible"], + [False, False, "hidden"], + ["hidden", False, "hidden"], + ["visible", True, "visible"], + ]) +def test_widget_set_visible_true(set_val, get_val, style_str): + widget = Widget() + widget.visible = set_val + + assert widget.visible is get_val + assert widget.styles.visibility == style_str + + +def test_widget_set_visible_invalid_string(): + widget = Widget() + + with pytest.raises(StyleValueError): + widget.visible = "nope! no widget for me!" + + assert widget.visible
Invisible widgets should allow background to be rendered Currently when a widget is set as invisible, it draws a blank rectangle in place of the content. It would be better to not render anything and allow any background to show through.
0.0
185788b7607266cc2e7609fb237be82cd3efb8b0
[ "tests/test_widget.py::test_widget_set_visible_true[False-False-hidden]", "tests/test_widget.py::test_widget_set_visible_true[hidden-False-hidden]", "tests/test_widget.py::test_widget_set_visible_true[visible-True-visible]", "tests/test_widget.py::test_widget_set_visible_invalid_string" ]
[ "tests/test_widget.py::test_widget_set_visible_true[True-True-visible]" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-20 11:41:22+00:00
mit
752
Textualize__textual-2464
diff --git a/CHANGELOG.md b/CHANGELOG.md index c4acf4a76..56b6aff24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Unreleased + +### Changed + +- The DataTable cursor is now scrolled into view when the cursor coordinate is changed programmatically https://github.com/Textualize/textual/issues/2459 + ## [0.23.0] - 2023-05-03 ### Fixed diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index 0681c3993..5991c98db 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -950,6 +950,7 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): elif self.cursor_type == "column": self.refresh_column(old_coordinate.column) self._highlight_column(new_coordinate.column) + self._scroll_cursor_into_view() def _highlight_coordinate(self, coordinate: Coordinate) -> None: """Apply highlighting to the cell at the coordinate, and post event."""
Textualize/textual
e5c54a36832b69e30da01f66fcfe629ec3c3b8c9
diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 56b148d56..0bba677cf 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -991,3 +991,28 @@ def test_key_string_lookup(): assert dictionary[RowKey("foo")] == "bar" assert dictionary["hello"] == "world" assert dictionary[RowKey("hello")] == "world" + + +async def test_scrolling_cursor_into_view(): + """Regression test for https://github.com/Textualize/textual/issues/2459""" + + class TableApp(App): + CSS = "DataTable { height: 100%; }" + + def compose(self): + yield DataTable() + + def on_mount(self) -> None: + table = self.query_one(DataTable) + table.add_column("n") + table.add_rows([(n,) for n in range(300)]) + + def key_c(self): + self.query_one(DataTable).cursor_coordinate = Coordinate(200, 0) + + app = TableApp() + + async with app.run_test() as pilot: + await pilot.press("c") + await pilot.pause() + assert app.query_one(DataTable).scroll_y > 100
DataTable - When cursor_coordinate updates, we should scroll_cursor_visible When the cursor moves out of the screen, we should scroll the cursor into visibility. It seems like there is already code to do this, but because of #2458 the scrolling doesn't work.
0.0
e5c54a36832b69e30da01f66fcfe629ec3c3b8c9
[ "tests/test_data_table.py::test_scrolling_cursor_into_view" ]
[ "tests/test_data_table.py::test_datatable_message_emission", "tests/test_data_table.py::test_empty_table_interactions", "tests/test_data_table.py::test_cursor_movement_with_home_pagedown_etc", "tests/test_data_table.py::test_add_rows", "tests/test_data_table.py::test_add_rows_user_defined_keys", "tests/test_data_table.py::test_add_row_duplicate_key", "tests/test_data_table.py::test_add_column_duplicate_key", "tests/test_data_table.py::test_add_column_with_width", "tests/test_data_table.py::test_add_columns", "tests/test_data_table.py::test_add_columns_user_defined_keys", "tests/test_data_table.py::test_remove_row", "tests/test_data_table.py::test_clear", "tests/test_data_table.py::test_column_labels", "tests/test_data_table.py::test_initial_column_widths", "tests/test_data_table.py::test_get_cell_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_invalid_row_key", "tests/test_data_table.py::test_get_cell_invalid_column_key", "tests/test_data_table.py::test_get_cell_at_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_at_exception", "tests/test_data_table.py::test_get_row", "tests/test_data_table.py::test_get_row_invalid_row_key", "tests/test_data_table.py::test_get_row_at", "tests/test_data_table.py::test_get_row_at_invalid_index[-1]", "tests/test_data_table.py::test_get_row_at_invalid_index[2]", "tests/test_data_table.py::test_get_column", "tests/test_data_table.py::test_get_column_invalid_key", "tests/test_data_table.py::test_get_column_at", "tests/test_data_table.py::test_get_column_at_invalid_index[-1]", "tests/test_data_table.py::test_get_column_at_invalid_index[5]", "tests/test_data_table.py::test_update_cell_cell_exists", "tests/test_data_table.py::test_update_cell_cell_doesnt_exist", "tests/test_data_table.py::test_update_cell_at_coordinate_exists", "tests/test_data_table.py::test_update_cell_at_coordinate_doesnt_exist", "tests/test_data_table.py::test_update_cell_at_column_width[A-BB-3]", "tests/test_data_table.py::test_update_cell_at_column_width[1234567-1234-7]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123-5]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123456789-9]", "tests/test_data_table.py::test_coordinate_to_cell_key", "tests/test_data_table.py::test_coordinate_to_cell_key_invalid_coordinate", "tests/test_data_table.py::test_datatable_click_cell_cursor", "tests/test_data_table.py::test_click_row_cursor", "tests/test_data_table.py::test_click_column_cursor", "tests/test_data_table.py::test_hover_coordinate", "tests/test_data_table.py::test_hover_mouse_leave", "tests/test_data_table.py::test_header_selected", "tests/test_data_table.py::test_row_label_selected", "tests/test_data_table.py::test_sort_coordinate_and_key_access", "tests/test_data_table.py::test_sort_reverse_coordinate_and_key_access", "tests/test_data_table.py::test_cell_cursor_highlight_events", "tests/test_data_table.py::test_row_cursor_highlight_events", "tests/test_data_table.py::test_column_cursor_highlight_events", "tests/test_data_table.py::test_reuse_row_key_after_clear", "tests/test_data_table.py::test_reuse_column_key_after_clear", "tests/test_data_table.py::test_key_equals_equivalent_string", "tests/test_data_table.py::test_key_doesnt_match_non_equal_string", "tests/test_data_table.py::test_key_equals_self", "tests/test_data_table.py::test_key_string_lookup" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-05-03 10:38:45+00:00
mit
753
Textualize__textual-2530
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d6821f92..aeaaf466a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed - App `title` and `sub_title` attributes can be set to any type https://github.com/Textualize/textual/issues/2521 +- Using `Widget.move_child` where the target and the child being moved are the same is now a no-op https://github.com/Textualize/textual/issues/1743 ### Fixed diff --git a/src/textual/widget.py b/src/textual/widget.py index 4fc364ebf..b116f5393 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -795,19 +795,15 @@ class Widget(DOMNode): Args: child: The child widget to move. - before: Optional location to move before. An `int` is the index - of the child to move before, a `str` is a `query_one` query to - find the widget to move before. - after: Optional location to move after. An `int` is the index - of the child to move after, a `str` is a `query_one` query to - find the widget to move after. + before: Child widget or location index to move before. + after: Child widget or location index to move after. Raises: WidgetError: If there is a problem with the child or target. Note: - Only one of ``before`` or ``after`` can be provided. If neither - or both are provided a ``WidgetError`` will be raised. + Only one of `before` or `after` can be provided. If neither + or both are provided a `WidgetError` will be raised. """ # One or the other of before or after are required. Can't do @@ -817,6 +813,10 @@ class Widget(DOMNode): elif before is not None and after is not None: raise WidgetError("Only one of `before` or `after` can be handled.") + # We short-circuit the no-op, otherwise it will error later down the road. + if child is before or child is after: + return + def _to_widget(child: int | Widget, called: str) -> Widget: """Ensure a given child reference is a Widget.""" if isinstance(child, int):
Textualize/textual
d266e3685f37353eb3e201a6538d28e4cc5d7025
diff --git a/tests/test_widget_child_moving.py b/tests/test_widget_child_moving.py index 520ef7810..f2d40a4aa 100644 --- a/tests/test_widget_child_moving.py +++ b/tests/test_widget_child_moving.py @@ -42,22 +42,18 @@ async def test_move_child_to_outside() -> None: pilot.app.screen.move_child(child, before=Widget()) [email protected]( - strict=True, reason="https://github.com/Textualize/textual/issues/1743" -) async def test_move_child_before_itself() -> None: """Test moving a widget before itself.""" + async with App().run_test() as pilot: child = Widget(Widget()) await pilot.app.mount(child) pilot.app.screen.move_child(child, before=child) [email protected]( - strict=True, reason="https://github.com/Textualize/textual/issues/1743" -) async def test_move_child_after_itself() -> None: """Test moving a widget after itself.""" + # Regression test for https://github.com/Textualize/textual/issues/1743 async with App().run_test() as pilot: child = Widget(Widget()) await pilot.app.mount(child)
Make moving a child before or after itself, a no-op If we try to use `move_child` to move a widget to after/before itself, should we get an error or is that a no-op? (Add tests to tests/test_widget_child_moving.py accordingly.) Context: this arose from writing some functionality in a TODO app that sorts TODO items according to their due date and reorders them when the due date is edited. From this point of view, it makes sense for moving to after/before itself to be a no-op. Otherwise, the sorting code needs to take extra steps to make sure we don't try to move things to where they already are.
0.0
d266e3685f37353eb3e201a6538d28e4cc5d7025
[ "tests/test_widget_child_moving.py::test_move_child_before_itself", "tests/test_widget_child_moving.py::test_move_child_after_itself" ]
[ "tests/test_widget_child_moving.py::test_move_child_no_direction", "tests/test_widget_child_moving.py::test_move_child_both_directions", "tests/test_widget_child_moving.py::test_move_child_not_our_child", "tests/test_widget_child_moving.py::test_move_child_to_outside", "tests/test_widget_child_moving.py::test_move_past_end_of_child_list", "tests/test_widget_child_moving.py::test_move_before_end_of_child_list", "tests/test_widget_child_moving.py::test_move_before_permutations", "tests/test_widget_child_moving.py::test_move_after_permutations", "tests/test_widget_child_moving.py::test_move_child_after_last_child", "tests/test_widget_child_moving.py::test_move_child_after_last_numeric_location" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-05-09 14:57:44+00:00
mit
754
Textualize__textual-2532
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e65e54e2..2992a923b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## Unreleased + +## Unrealeased + +### Changed + +- App `title` and `sub_title` attributes can be set to any type https://github.com/Textualize/textual/issues/2521 ### Fixed diff --git a/src/textual/app.py b/src/textual/app.py index 113a7a220..12f66cf04 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -316,6 +316,7 @@ class App(Generic[ReturnType], DOMNode): the name of the app if it doesn't. Assign a new value to this attribute to change the title. + The new value is always converted to string. """ self.sub_title = self.SUB_TITLE if self.SUB_TITLE is not None else "" @@ -328,6 +329,7 @@ class App(Generic[ReturnType], DOMNode): the file being worker on. Assign a new value to this attribute to change the sub-title. + The new value is always converted to string. """ self._logger = Logger(self._log) @@ -406,6 +408,14 @@ class App(Generic[ReturnType], DOMNode): self.set_class(self.dark, "-dark-mode") self.set_class(not self.dark, "-light-mode") + def validate_title(self, title: Any) -> str: + """Make sure the title is set to a string.""" + return str(title) + + def validate_sub_title(self, sub_title: Any) -> str: + """Make sure the sub-title is set to a string.""" + return str(sub_title) + @property def workers(self) -> WorkerManager: """The [worker](guide/workers/) manager.
Textualize/textual
f19f46bba0e5fa164bbd2abcc02913b0a856203a
diff --git a/tests/test_app.py b/tests/test_app.py index e529cfbd7..54bde8221 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -36,3 +36,33 @@ async def test_hover_update_styles(): # We've hovered, so ensure the pseudoclass is present and background changed assert button.pseudo_classes == {"enabled", "hover"} assert button.styles.background != initial_background + + +def test_setting_title(): + app = MyApp() + app.title = None + assert app.title == "None" + + app.title = "" + assert app.title == "" + + app.title = 0.125 + assert app.title == "0.125" + + app.title = [True, False, 2] + assert app.title == "[True, False, 2]" + + +def test_setting_sub_title(): + app = MyApp() + app.sub_title = None + assert app.sub_title == "None" + + app.sub_title = "" + assert app.sub_title == "" + + app.sub_title = 0.125 + assert app.sub_title == "0.125" + + app.sub_title = [True, False, 2] + assert app.sub_title == "[True, False, 2]"
App title and sub_title should be converted to strings I'm thinking that `App.title` and `App.sub_title` should be converted to strings. Balancing convenience with hiding errors, this is probably the right thing to do 90% of the time.
0.0
f19f46bba0e5fa164bbd2abcc02913b0a856203a
[ "tests/test_app.py::test_setting_title", "tests/test_app.py::test_setting_sub_title" ]
[ "tests/test_app.py::test_batch_update", "tests/test_app.py::test_hover_update_styles" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-09 15:57:46+00:00
mit
755
Textualize__textual-2568
diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e7cdebf4..5991f818d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed `TreeNode.collapse` and `TreeNode.collapse_all` not posting a `Tree.NodeCollapsed` message https://github.com/Textualize/textual/issues/2535 - Fixed `TreeNode.toggle` and `TreeNode.toggle_all` not posting a `Tree.NodeExpanded` or `Tree.NodeCollapsed` message https://github.com/Textualize/textual/issues/2535 - `footer--description` component class was being ignored https://github.com/Textualize/textual/issues/2544 +- Pasting empty selection in `Input` would raise an exception https://github.com/Textualize/textual/issues/2563 ### Added diff --git a/src/textual/widgets/_input.py b/src/textual/widgets/_input.py index 9e5bf2d07..e14dcdf10 100644 --- a/src/textual/widgets/_input.py +++ b/src/textual/widgets/_input.py @@ -332,8 +332,9 @@ class Input(Widget, can_focus=True): event.prevent_default() def _on_paste(self, event: events.Paste) -> None: - line = event.text.splitlines()[0] - self.insert_text_at_cursor(line) + if event.text: + line = event.text.splitlines()[0] + self.insert_text_at_cursor(line) event.stop() async def _on_click(self, event: events.Click) -> None:
Textualize/textual
83618db642187a77ab13d0585c9ab56d60877dd7
diff --git a/tests/test_paste.py b/tests/test_paste.py index 774ad5038..45be6d536 100644 --- a/tests/test_paste.py +++ b/tests/test_paste.py @@ -1,5 +1,6 @@ from textual import events from textual.app import App +from textual.widgets import Input async def test_paste_app(): @@ -16,3 +17,28 @@ async def test_paste_app(): assert len(paste_events) == 1 assert paste_events[0].text == "Hello" + + +async def test_empty_paste(): + """Regression test for https://github.com/Textualize/textual/issues/2563.""" + + paste_events = [] + + class MyInput(Input): + def on_paste(self, event): + super()._on_paste(event) + paste_events.append(event) + + class PasteApp(App): + def compose(self): + yield MyInput() + + def key_p(self): + self.query_one(MyInput).post_message(events.Paste("")) + + app = PasteApp() + async with app.run_test() as pilot: + await pilot.press("p") + assert app.query_one(MyInput).value == "" + assert len(paste_events) == 1 + assert paste_events[0].text == ""
Pasting in Input with an empty string crashes the program Pressing middle mouse button to paste causes this error in `Input._on_paste` if the clipboard is empty of text: ``` ╭───────────────────────────────────────────────────────────────────────── Traceback (most recent call last) ─────────────────────────────────────────────────────────────────────────╮ │ /home/io/Projects/textual-paint/.venv/lib/python3.10/site-packages/textual/widgets/_input.py:335 in _on_paste │ │ │ │ 332 │ │ │ event.prevent_default() │ │ 333 │ │ │ 334 │ def _on_paste(self, event: events.Paste) -> None: │ │ ❱ 335 │ │ line = event.text.splitlines()[0] │ │ 336 │ │ self.insert_text_at_cursor(line) │ │ 337 │ │ event.stop() │ │ 338 │ │ │ │ ╭──────────────────────────────────────────────────────────── locals ────────────────────────────────────────────────────────────╮ │ │ │ event = Paste(text='') │ │ │ │ self = CharInput(id='selected_color_char_input', classes={'color_well'}, pseudo_classes={'focus', 'focus-within', 'enabled'}) │ │ │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ IndexError: list index out of range ``` To reproduce, use `printf "" | xsel` before pasting with MMB. # Textual Diagnostics ## Versions | Name | Value | |---------|--------| | Textual | 0.22.3 | | Rich | 13.3.5 | ## Python | Name | Value | |----------------|--------------------------------------------------| | Version | 3.10.6 | | Implementation | CPython | | Compiler | GCC 11.3.0 | | Executable | /home/io/Projects/textual-paint/.venv/bin/python | ## Operating System | Name | Value | |---------|------------------------------------------------------------------| | System | Linux | | Release | 5.19.0-41-generic | | Version | #42~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue Apr 18 17:40:00 UTC 2 | ## Terminal | Name | Value | |----------------------|-----------------| | Terminal Application | vscode (1.77.3) | | TERM | xterm-256color | | COLORTERM | truecolor | | FORCE_COLOR | *Not set* | | NO_COLOR | *Not set* | ## Rich Console options | Name | Value | |----------------|----------------------| | size | width=183, height=32 | | legacy_windows | False | | min_width | 1 | | max_width | 183 | | is_terminal | True | | encoding | utf-8 | | max_height | 32 | | justify | None | | overflow | None | | no_wrap | False | | highlight | None | | markup | None | | height | None |
0.0
83618db642187a77ab13d0585c9ab56d60877dd7
[ "tests/test_paste.py::test_empty_paste" ]
[ "tests/test_paste.py::test_paste_app" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-05-15 12:23:11+00:00
mit
756
Textualize__textual-2580
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5991f818d..bce29efda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - App `title` and `sub_title` attributes can be set to any type https://github.com/Textualize/textual/issues/2521 - Using `Widget.move_child` where the target and the child being moved are the same is now a no-op https://github.com/Textualize/textual/issues/1743 +- Calling `dismiss` on a screen that is not at the top of the stack now raises an exception https://github.com/Textualize/textual/issues/2575 ### Fixed diff --git a/src/textual/app.py b/src/textual/app.py index 12f66cf04..c1376cd22 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -156,7 +156,7 @@ class ScreenError(Exception): class ScreenStackError(ScreenError): - """Raised when attempting to pop the last screen from the stack.""" + """Raised when trying to manipulate the screen stack incorrectly.""" class CssPathError(Exception): diff --git a/src/textual/screen.py b/src/textual/screen.py index af0b006be..09505cc53 100644 --- a/src/textual/screen.py +++ b/src/textual/screen.py @@ -771,6 +771,10 @@ class Screen(Generic[ScreenResultType], Widget): Args: result: The optional result to be passed to the result callback. + Raises: + ScreenStackError: If trying to dismiss a screen that is not at the top of + the stack. + Note: If the screen was pushed with a callback, the callback will be called with the given result and then a call to @@ -778,6 +782,12 @@ class Screen(Generic[ScreenResultType], Widget): no callback was provided calling this method is the same as simply calling [`App.pop_screen`][textual.app.App.pop_screen]. """ + if self is not self.app.screen: + from .app import ScreenStackError + + raise ScreenStackError( + f"Can't dismiss screen {self} that's not at the top of the stack." + ) if result is not self._NoResult and self._result_callbacks: self._result_callbacks[-1](cast(ScreenResultType, result)) self.app.pop_screen()
Textualize/textual
6147c28dbf86c0d09a75b179b68fae1aeae1b26c
diff --git a/tests/test_screens.py b/tests/test_screens.py index 2e3dbfcbe..5b29b1dd5 100644 --- a/tests/test_screens.py +++ b/tests/test_screens.py @@ -192,3 +192,17 @@ async def test_auto_focus(): assert app.focused is None app.pop_screen() assert app.focused.id == "two" + + +async def test_dismiss_non_top_screen(): + class MyApp(App[None]): + async def key_p(self) -> None: + self.bottom, top = Screen(), Screen() + await self.push_screen(self.bottom) + await self.push_screen(top) + + app = MyApp() + async with app.run_test() as pilot: + await pilot.press("p") + with pytest.raises(ScreenStackError): + app.bottom.dismiss()
Screen.dismiss should error if not the top-most screen At the moment if you call `dismiss` on a screen that is *not* the top-most on the stack, strange things will happen. I think the only solution here is for that to be an error. i.e. if I push screens A, B, C on to the stack. Then I call `B.dismiss()` that should raise a `DismissError` (name TBD). Only `C.dismiss()` is valid, because it is a the top of the stack.
0.0
6147c28dbf86c0d09a75b179b68fae1aeae1b26c
[ "tests/test_screens.py::test_dismiss_non_top_screen" ]
[ "tests/test_screens.py::test_screen_walk_children", "tests/test_screens.py::test_installed_screens", "tests/test_screens.py::test_screens", "tests/test_screens.py::test_auto_focus" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-16 10:15:16+00:00
mit
757
Textualize__textual-2621
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ba7ec153..d838c46f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed - `Placeholder` now sets its color cycle per app https://github.com/Textualize/textual/issues/2590 +- Footer now clears key highlight regardless of whether it's in the active screen or not https://github.com/Textualize/textual/issues/2606 ### Removed diff --git a/src/textual/app.py b/src/textual/app.py index 05ae29922..7e02572d4 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -159,6 +159,38 @@ class ScreenStackError(ScreenError): """Raised when trying to manipulate the screen stack incorrectly.""" +class ModeError(Exception): + """Base class for exceptions related to modes.""" + + +class InvalidModeError(ModeError): + """Raised if there is an issue with a mode name.""" + + +class UnknownModeError(ModeError): + """Raised when attempting to use a mode that is not known.""" + + +class ActiveModeError(ModeError): + """Raised when attempting to remove the currently active mode.""" + + +class ModeError(Exception): + """Base class for exceptions related to modes.""" + + +class InvalidModeError(ModeError): + """Raised if there is an issue with a mode name.""" + + +class UnknownModeError(ModeError): + """Raised when attempting to use a mode that is not known.""" + + +class ActiveModeError(ModeError): + """Raised when attempting to remove the currently active mode.""" + + class CssPathError(Exception): """Raised when supplied CSS path(s) are invalid.""" @@ -212,6 +244,35 @@ class App(Generic[ReturnType], DOMNode): } """ + MODES: ClassVar[dict[str, str | Screen | Callable[[], Screen]]] = {} + """Modes associated with the app and their base screens. + + The base screen is the screen at the bottom of the mode stack. You can think of + it as the default screen for that stack. + The base screens can be names of screens listed in [SCREENS][textual.app.App.SCREENS], + [`Screen`][textual.screen.Screen] instances, or callables that return screens. + + Example: + ```py + class HelpScreen(Screen[None]): + ... + + class MainAppScreen(Screen[None]): + ... + + class MyApp(App[None]): + MODES = { + "default": "main", + "help": HelpScreen, + } + + SCREENS = { + "main": MainAppScreen, + } + + ... + ``` + """ SCREENS: ClassVar[dict[str, Screen | Callable[[], Screen]]] = {} """Screens associated with the app for the lifetime of the app.""" _BASE_PATH: str | None = None @@ -296,7 +357,10 @@ class App(Generic[ReturnType], DOMNode): self._workers = WorkerManager(self) self.error_console = Console(markup=False, stderr=True) self.driver_class = driver_class or self.get_driver_class() - self._screen_stack: list[Screen] = [] + self._screen_stacks: dict[str, list[Screen]] = {"_default": []} + """A stack of screens per mode.""" + self._current_mode: str = "_default" + """The current mode the app is in.""" self._sync_available = False self.mouse_over: Widget | None = None @@ -528,7 +592,19 @@ class App(Generic[ReturnType], DOMNode): Returns: A snapshot of the current state of the screen stack. """ - return self._screen_stack.copy() + return self._screen_stacks[self._current_mode].copy() + + @property + def _screen_stack(self) -> list[Screen]: + """A reference to the current screen stack. + + Note: + Consider using [`screen_stack`][textual.app.App.screen_stack] instead. + + Returns: + A reference to the current screen stack. + """ + return self._screen_stacks[self._current_mode] def exit( self, result: ReturnType | None = None, message: RenderableType | None = None @@ -676,6 +752,8 @@ class App(Generic[ReturnType], DOMNode): """ try: return self._screen_stack[-1] + except KeyError: + raise UnknownModeError(f"No known mode {self._current_mode!r}") from None except IndexError: raise ScreenStackError("No screens on stack") from None @@ -1321,6 +1399,88 @@ class App(Generic[ReturnType], DOMNode): """ return self.mount(*widgets, before=before, after=after) + def _init_mode(self, mode: str) -> None: + """Do internal initialisation of a new screen stack mode.""" + + stack = self._screen_stacks.get(mode, []) + if not stack: + _screen = self.MODES[mode] + if callable(_screen): + screen, _ = self._get_screen(_screen()) + else: + screen, _ = self._get_screen(self.MODES[mode]) + stack.append(screen) + self._screen_stacks[mode] = [screen] + + def switch_mode(self, mode: str) -> None: + """Switch to a given mode. + + Args: + mode: The mode to switch to. + + Raises: + UnknownModeError: If trying to switch to an unknown mode. + """ + if mode not in self.MODES: + raise UnknownModeError(f"No known mode {mode!r}") + + self.screen.post_message(events.ScreenSuspend()) + self.screen.refresh() + + if mode not in self._screen_stacks: + self._init_mode(mode) + self._current_mode = mode + self.screen._screen_resized(self.size) + self.screen.post_message(events.ScreenResume()) + self.log.system(f"{self._current_mode!r} is the current mode") + self.log.system(f"{self.screen} is active") + + def add_mode( + self, mode: str, base_screen: str | Screen | Callable[[], Screen] + ) -> None: + """Adds a mode and its corresponding base screen to the app. + + Args: + mode: The new mode. + base_screen: The base screen associated with the given mode. + + Raises: + InvalidModeError: If the name of the mode is not valid/duplicated. + """ + if mode == "_default": + raise InvalidModeError("Cannot use '_default' as a custom mode.") + elif mode in self.MODES: + raise InvalidModeError(f"Duplicated mode name {mode!r}.") + + self.MODES[mode] = base_screen + + def remove_mode(self, mode: str) -> None: + """Removes a mode from the app. + + Screens that are running in the stack of that mode are scheduled for pruning. + + Args: + mode: The mode to remove. It can't be the active mode. + + Raises: + ActiveModeError: If trying to remove the active mode. + UnknownModeError: If trying to remove an unknown mode. + """ + if mode == self._current_mode: + raise ActiveModeError(f"Can't remove active mode {mode!r}") + elif mode not in self.MODES: + raise UnknownModeError(f"Unknown mode {mode!r}") + else: + del self.MODES[mode] + + if mode not in self._screen_stacks: + return + + stack = self._screen_stacks[mode] + del self._screen_stacks[mode] + for screen in reversed(stack): + self._replace_screen(screen) + def is_screen_installed(self, screen: Screen | str) -> bool: """Check if a given screen has been installed. @@ -1397,7 +1557,9 @@ class App(Generic[ReturnType], DOMNode): self.screen.refresh() screen.post_message(events.ScreenSuspend()) self.log.system(f"{screen} SUSPENDED") - if not self.is_screen_installed(screen) and screen not in self._screen_stack: + if not self.is_screen_installed(screen) and all( + screen not in stack for stack in self._screen_stacks.values() + ): screen.remove() self.log.system(f"{screen} REMOVED") return screen @@ -1498,13 +1660,13 @@ class App(Generic[ReturnType], DOMNode): if screen not in self._installed_screens: return None uninstall_screen = self._installed_screens[screen] - if uninstall_screen in self._screen_stack: + if any(uninstall_screen in stack for stack in self._screen_stacks.values()): raise ScreenStackError("Can't uninstall screen in screen stack") del self._installed_screens[screen] self.log.system(f"{uninstall_screen} UNINSTALLED name={screen!r}") return screen else: - if screen in self._screen_stack: + if any(screen in stack for stack in self._screen_stacks.values()): raise ScreenStackError("Can't uninstall screen in screen stack") for name, installed_screen in self._installed_screens.items(): if installed_screen is screen: @@ -1949,12 +2111,12 @@ class App(Generic[ReturnType], DOMNode): async def _close_all(self) -> None: """Close all message pumps.""" - # Close all screens on the stack. - for stack_screen in reversed(self._screen_stack): - if stack_screen._running: - await self._prune_node(stack_screen) - - self._screen_stack.clear() + # Close all screens on all stacks: + for stack in self._screen_stacks.values(): + for stack_screen in reversed(stack): + if stack_screen._running: + await self._prune_node(stack_screen) + stack.clear() # Close pre-defined screens. for screen in self.SCREENS.values(): @@ -2139,7 +2301,7 @@ class App(Generic[ReturnType], DOMNode): # Handle input events that haven't been forwarded # If the event has been forwarded it may have bubbled up back to the App if isinstance(event, events.Compose): - screen = Screen(id="_default") + screen = Screen(id=f"_default") self._register(self, screen) self._screen_stack.append(screen) screen.post_message(events.ScreenResume()) diff --git a/src/textual/widgets/_footer.py b/src/textual/widgets/_footer.py index a52e05785..b5e772ab6 100644 --- a/src/textual/widgets/_footer.py +++ b/src/textual/widgets/_footer.py @@ -79,8 +79,7 @@ class Footer(Widget): def _on_leave(self, _: events.Leave) -> None: """Clear any highlight when the mouse leaves the widget""" - if self.screen.is_current: - self.highlight_key = None + self.highlight_key = None def __rich_repr__(self) -> rich.repr.Result: yield from super().__rich_repr__()
Textualize/textual
5c1c62edd06741417f7640fbe92d52fffb1a2335
diff --git a/tests/test_footer.py b/tests/test_footer.py new file mode 100644 index 000000000..26e46cf29 --- /dev/null +++ b/tests/test_footer.py @@ -0,0 +1,28 @@ +from textual.app import App, ComposeResult +from textual.geometry import Offset +from textual.screen import ModalScreen +from textual.widgets import Footer, Label + + +async def test_footer_highlight_when_pushing_modal(): + """Regression test for https://github.com/Textualize/textual/issues/2606""" + + class MyModalScreen(ModalScreen): + def compose(self) -> ComposeResult: + yield Label("apple") + + class MyApp(App[None]): + BINDINGS = [("a", "p", "push")] + + def compose(self) -> ComposeResult: + yield Footer() + + def action_p(self): + self.push_screen(MyModalScreen()) + + app = MyApp() + async with app.run_test(size=(80, 2)) as pilot: + await pilot.hover(None, Offset(0, 1)) + await pilot.click(None, Offset(0, 1)) + assert isinstance(app.screen, MyModalScreen) + assert app.screen_stack[0].query_one(Footer).highlight_key is None diff --git a/tests/test_screen_modes.py b/tests/test_screen_modes.py new file mode 100644 index 000000000..6fd5c185d --- /dev/null +++ b/tests/test_screen_modes.py @@ -0,0 +1,277 @@ +from functools import partial +from itertools import cycle +from typing import Type + +import pytest + +from textual.app import ( + ActiveModeError, + App, + ComposeResult, + InvalidModeError, + UnknownModeError, +) +from textual.screen import ModalScreen, Screen +from textual.widgets import Footer, Header, Label, TextLog + +FRUITS = cycle("apple mango strawberry banana peach pear melon watermelon".split()) + + +class ScreenBindingsMixin(Screen[None]): + BINDINGS = [ + ("1", "one", "Mode 1"), + ("2", "two", "Mode 2"), + ("p", "push", "Push rnd scrn"), + ("o", "pop_screen", "Pop"), + ("r", "remove", "Remove mode 1"), + ] + + def action_one(self) -> None: + self.app.switch_mode("one") + + def action_two(self) -> None: + self.app.switch_mode("two") + + def action_fruits(self) -> None: + self.app.switch_mode("fruits") + + def action_push(self) -> None: + self.app.push_screen(FruitModal()) + + +class BaseScreen(ScreenBindingsMixin): + def __init__(self, label): + super().__init__() + self.label = label + + def compose(self) -> ComposeResult: + yield Header() + yield Label(self.label) + yield Footer() + + def action_remove(self) -> None: + self.app.remove_mode("one") + + +class FruitModal(ModalScreen[str], ScreenBindingsMixin): + BINDINGS = [("d", "dismiss_fruit", "Dismiss")] + + def compose(self) -> ComposeResult: + yield Label(next(FRUITS)) + + +class FruitsScreen(ScreenBindingsMixin): + def compose(self) -> ComposeResult: + yield TextLog() + + [email protected] +def ModesApp(): + class ModesApp(App[None]): + MODES = { + "one": lambda: BaseScreen("one"), + "two": "screen_two", + } + + SCREENS = { + "screen_two": lambda: BaseScreen("two"), + } + + def on_mount(self): + self.switch_mode("one") + + return ModesApp + + +async def test_mode_setup(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test(): + assert isinstance(app.screen, BaseScreen) + assert str(app.screen.query_one(Label).renderable) == "one" + + +async def test_switch_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test() as pilot: + await pilot.press("2") + assert str(app.screen.query_one(Label).renderable) == "two" + await pilot.press("1") + assert str(app.screen.query_one(Label).renderable) == "one" + + +async def test_switch_same_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test() as pilot: + await pilot.press("1") + assert str(app.screen.query_one(Label).renderable) == "one" + await pilot.press("1") + assert str(app.screen.query_one(Label).renderable) == "one" + + +async def test_switch_unknown_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test(): + with pytest.raises(UnknownModeError): + app.switch_mode("unknown mode here") + + +async def test_remove_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test() as pilot: + app.switch_mode("two") + await pilot.pause() + assert str(app.screen.query_one(Label).renderable) == "two" + app.remove_mode("one") + assert "one" not in app.MODES + + +async def test_remove_active_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test(): + with pytest.raises(ActiveModeError): + app.remove_mode("one") + + +async def test_add_mode(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test() as pilot: + app.add_mode("three", BaseScreen("three")) + app.switch_mode("three") + await pilot.pause() + assert str(app.screen.query_one(Label).renderable) == "three" + + +async def test_add_mode_duplicated(ModesApp: Type[App]): + app = ModesApp() + async with app.run_test(): + with pytest.raises(InvalidModeError): + app.add_mode("one", BaseScreen("one")) + + +async def test_screen_stack_preserved(ModesApp: Type[App]): + fruits = [] + N = 5 + + app = ModesApp() + async with app.run_test() as pilot: + # Build the stack up. + for _ in range(N): + await pilot.press("p") + fruits.append(str(app.query_one(Label).renderable)) + + assert len(app.screen_stack) == N + 1 + + # Switch out and back. + await pilot.press("2") + assert len(app.screen_stack) == 1 + await pilot.press("1") + + # Check the stack. + assert len(app.screen_stack) == N + 1 + for _ in range(N): + assert str(app.query_one(Label).renderable) == fruits.pop() + await pilot.press("o") + + +async def test_inactive_stack_is_alive(): + """This tests that timers in screens outside the active stack keep going.""" + pings = [] + + class FastCounter(Screen[None]): + def compose(self) -> ComposeResult: + yield Label("fast") + + def on_mount(self) -> None: + self.set_interval(0.01, self.ping) + + def ping(self) -> None: + pings.append(str(self.app.query_one(Label).renderable)) + + def key_s(self): + self.app.switch_mode("smile") + + class SmileScreen(Screen[None]): + def compose(self) -> ComposeResult: + yield Label(":)") + + def key_s(self): + self.app.switch_mode("fast") + + class ModesApp(App[None]): + MODES = { + "fast": FastCounter, + "smile": SmileScreen, + } + + def on_mount(self) -> None: + self.switch_mode("fast") + + app = ModesApp() + async with app.run_test() as pilot: + await pilot.press("s") + assert str(app.query_one(Label).renderable) == ":)" + await pilot.press("s") + assert ":)" in pings + + +async def test_multiple_mode_callbacks(): + written = [] + + class LogScreen(Screen[None]): + def __init__(self, value): + super().__init__() + self.value = value + + def key_p(self) -> None: + self.app.push_screen(ResultScreen(self.value), written.append) + + class ResultScreen(Screen[str]): + def __init__(self, value): + super().__init__() + self.value = value + + def key_p(self) -> None: + self.dismiss(self.value) + + def key_f(self) -> None: + self.app.switch_mode("first") + + def key_o(self) -> None: + self.app.switch_mode("other") + + class ModesApp(App[None]): + MODES = { + "first": lambda: LogScreen("first"), + "other": lambda: LogScreen("other"), + } + + def on_mount(self) -> None: + self.switch_mode("first") + + def key_f(self) -> None: + self.switch_mode("first") + + def key_o(self) -> None: + self.switch_mode("other") + + app = ModesApp() + async with app.run_test() as pilot: + # Push and dismiss ResultScreen("first") + await pilot.press("p") + await pilot.press("p") + assert written == ["first"] + + # Push ResultScreen("first") + await pilot.press("p") + # Switch to LogScreen("other") + await pilot.press("o") + # Push and dismiss ResultScreen("other") + await pilot.press("p") + await pilot.press("p") + assert written == ["first", "other"] + + # Go back to ResultScreen("first") + await pilot.press("f") + # Dismiss ResultScreen("first") + await pilot.press("p") + assert written == ["first", "other", "first"]
Pushing a screen should send Leave message If you have an action that opens a screen, it leaves the footer stuck in the highlight state. I think we need to call `_set_mouse_over(None)` on the current screen when pushing another screen.
0.0
5c1c62edd06741417f7640fbe92d52fffb1a2335
[ "tests/test_footer.py::test_footer_highlight_when_pushing_modal", "tests/test_screen_modes.py::test_mode_setup", "tests/test_screen_modes.py::test_switch_mode", "tests/test_screen_modes.py::test_switch_same_mode", "tests/test_screen_modes.py::test_switch_unknown_mode", "tests/test_screen_modes.py::test_remove_mode", "tests/test_screen_modes.py::test_remove_active_mode", "tests/test_screen_modes.py::test_add_mode", "tests/test_screen_modes.py::test_add_mode_duplicated", "tests/test_screen_modes.py::test_screen_stack_preserved", "tests/test_screen_modes.py::test_inactive_stack_is_alive", "tests/test_screen_modes.py::test_multiple_mode_callbacks" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-22 12:55:30+00:00
mit
758
Textualize__textual-2687
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc55decb..fe30a9778 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed zero division error https://github.com/Textualize/textual/issues/2673 - Fix `scroll_to_center` when there were nested layers out of view (Compositor full_map not populated fully) https://github.com/Textualize/textual/pull/2684 +- Issues with `switch_screen` not updating the results callback appropriately https://github.com/Textualize/textual/issues/2650 ### Added @@ -22,6 +23,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `SuggestFromList` class to let widgets get completions from a fixed set of options https://github.com/Textualize/textual/pull/2604 - `Input` has a new component class `input--suggestion` https://github.com/Textualize/textual/pull/2604 - Added `Widget.remove_children` https://github.com/Textualize/textual/pull/2657 +- Added `Validator` framework and validation for `Input` https://github.com/Textualize/textual/pull/2600 ### Changed @@ -35,6 +37,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `Tree` and `DirectoryTree` Messages no longer accept a `tree` parameter, using `self.node.tree` instead. https://github.com/Textualize/textual/issues/2529 - Keybinding <kbd>right</kbd> in `Input` is also used to accept a suggestion if the cursor is at the end of the input https://github.com/Textualize/textual/pull/2604 - `Input.__init__` now accepts a `suggester` attribute for completion suggestions https://github.com/Textualize/textual/pull/2604 +- Using `switch_screen` to switch to the currently active screen is now a no-op https://github.com/Textualize/textual/pull/2692 ### Removed diff --git a/src/textual/_compositor.py b/src/textual/_compositor.py index caf6d1e6e..bd2c75395 100644 --- a/src/textual/_compositor.py +++ b/src/textual/_compositor.py @@ -361,6 +361,11 @@ class Compositor: new_widgets = map.keys() + # Newly visible widgets + shown_widgets = new_widgets - old_widgets + # Newly hidden widgets + hidden_widgets = self.widgets - widgets + # Replace map and widgets self._full_map = map self.widgets = widgets @@ -389,10 +394,7 @@ class Compositor: for widget, (region, *_) in changes if (widget in common_widgets and old_map[widget].region[2:] != region[2:]) } - # Newly visible widgets - shown_widgets = new_widgets - old_widgets - # Newly hidden widgets - hidden_widgets = self.widgets - widgets + return ReflowResult( hidden=hidden_widgets, shown=shown_widgets, diff --git a/src/textual/app.py b/src/textual/app.py index 879edbad5..e9300f8c8 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -1611,15 +1611,19 @@ class App(Generic[ReturnType], DOMNode): raise TypeError( f"switch_screen requires a Screen instance or str; not {screen!r}" ) - if self.screen is not screen: - previous_screen = self._replace_screen(self._screen_stack.pop()) - previous_screen._pop_result_callback() - next_screen, await_mount = self._get_screen(screen) - self._screen_stack.append(next_screen) - self.screen.post_message(events.ScreenResume()) - self.log.system(f"{self.screen} is current (SWITCHED)") - return await_mount - return AwaitMount(self.screen, []) + + next_screen, await_mount = self._get_screen(screen) + if screen is self.screen or next_screen is self.screen: + self.log.system(f"Screen {screen} is already current.") + return AwaitMount(self.screen, []) + + previous_screen = self._replace_screen(self._screen_stack.pop()) + previous_screen._pop_result_callback() + self._screen_stack.append(next_screen) + self.screen.post_message(events.ScreenResume()) + self.screen._push_result_callback(self.screen, None) + self.log.system(f"{self.screen} is current (SWITCHED)") + return await_mount def install_screen(self, screen: Screen, name: str) -> None: """Install a screen. diff --git a/src/textual/css/_style_properties.py b/src/textual/css/_style_properties.py index 45ba9c423..a45813bfa 100644 --- a/src/textual/css/_style_properties.py +++ b/src/textual/css/_style_properties.py @@ -90,7 +90,7 @@ class GenericProperty(Generic[PropertyGetType, PropertySetType]): # Raise StyleValueError here return cast(PropertyGetType, value) - def __set_name__(self, owner: Styles, name: str) -> None: + def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__( @@ -138,7 +138,7 @@ class ScalarProperty: self.allow_auto = allow_auto super().__init__() - def __set_name__(self, owner: Styles, name: str) -> None: + def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__( @@ -227,7 +227,7 @@ class ScalarListProperty: self.percent_unit = percent_unit self.refresh_children = refresh_children - def __set_name__(self, owner: Styles, name: str) -> None: + def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__( @@ -294,7 +294,7 @@ class BoxProperty: obj.get_rule(self.name) or ("", self._default_color), ) - def __set__(self, obj: Styles, border: tuple[EdgeType, str | Color] | None): + def __set__(self, obj: StylesBase, border: tuple[EdgeType, str | Color] | None): """Set the box property. Args: @@ -928,7 +928,7 @@ class ColorProperty: class StyleFlagsProperty: """Descriptor for getting and set style flag properties (e.g. ``bold italic underline``).""" - def __set_name__(self, owner: Styles, name: str) -> None: + def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__( @@ -1008,7 +1008,9 @@ class TransitionsProperty: """ return cast("dict[str, Transition]", obj.get_rule("transitions", {})) - def __set__(self, obj: Styles, transitions: dict[str, Transition] | None) -> None: + def __set__( + self, obj: StylesBase, transitions: dict[str, Transition] | None + ) -> None: _rich_traceback_omit = True if transitions is None: obj.clear_rule("transitions")
Textualize/textual
a40300a6f5f78c5b2dd41bf36e282cbea2af7ff1
diff --git a/tests/test_screens.py b/tests/test_screens.py index 033891990..7f42a21a2 100644 --- a/tests/test_screens.py +++ b/tests/test_screens.py @@ -298,3 +298,55 @@ async def test_dismiss_non_top_screen(): await pilot.press("p") with pytest.raises(ScreenStackError): app.bottom.dismiss() + + +async def test_switch_screen_no_op(): + """Regression test for https://github.com/Textualize/textual/issues/2650""" + + class MyScreen(Screen): + pass + + class MyApp(App[None]): + SCREENS = {"screen": MyScreen()} + + def on_mount(self): + self.push_screen("screen") + + app = MyApp() + async with app.run_test(): + screen_id = id(app.screen) + app.switch_screen("screen") + assert screen_id == id(app.screen) + app.switch_screen("screen") + assert screen_id == id(app.screen) + + +async def test_switch_screen_updates_results_callback_stack(): + """Regression test for https://github.com/Textualize/textual/issues/2650""" + + class ScreenA(Screen): + pass + + class ScreenB(Screen): + pass + + class MyApp(App[None]): + SCREENS = { + "a": ScreenA(), + "b": ScreenB(), + } + + def callback(self, _): + return 42 + + def on_mount(self): + self.push_screen("a", self.callback) + + app = MyApp() + async with app.run_test(): + assert len(app.screen._result_callbacks) == 1 + assert app.screen._result_callbacks[-1].callback(None) == 42 + + app.switch_screen("b") + assert len(app.screen._result_callbacks) == 1 + assert app.screen._result_callbacks[-1].callback is None
It looks like `on_hide` is not called when a widget is hidden in some way I would expect the following application to crash when the button is pressed: ```python from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Button, Label class ShouldCrash( Label ): def on_hide( self ) -> None: _ = 1/0 class NoHideApp( App[ None ] ): CSS = """ Vertical { align: center middle; } """ def compose( self ) -> ComposeResult: with Vertical(): yield Button( "Press to hide the label below" ) yield ShouldCrash( "Press the button above me to hide me" ) def on_button_pressed( self ): self.query_one( ShouldCrash ).display = False if __name__ == "__main__": NoHideApp().run() ``` However, when the button is pressed; it doesn't. It would appear that the `Hide` message isn't being sent. Looking in the debug console I don't see the event. The same is true if I attempt to hide the widget using any of: ```python self.query_one( ShouldCrash ).display = "none" self.query_one( ShouldCrash ).visible = False self.query_one( ShouldCrash ).set_class( True, "hidden" ) # With appropriate CSS to back it up. ```
0.0
a40300a6f5f78c5b2dd41bf36e282cbea2af7ff1
[ "tests/test_screens.py::test_switch_screen_no_op", "tests/test_screens.py::test_switch_screen_updates_results_callback_stack" ]
[ "tests/test_screens.py::test_screen_walk_children", "tests/test_screens.py::test_installed_screens", "tests/test_screens.py::test_screens", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_none", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_disabled", "tests/test_screens.py::test_auto_focus_inheritance", "tests/test_screens.py::test_auto_focus_skips_non_focusable_widgets", "tests/test_screens.py::test_dismiss_non_top_screen" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-30 03:54:01+00:00
mit
759
Textualize__textual-269
diff --git a/src/textual/renderables/sparkline.py b/src/textual/renderables/sparkline.py new file mode 100644 index 000000000..22bc959f7 --- /dev/null +++ b/src/textual/renderables/sparkline.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import statistics +from typing import Sequence, Iterable, Callable, TypeVar + +from rich.color import Color +from rich.console import ConsoleOptions, Console, RenderResult +from rich.segment import Segment +from rich.style import Style + +T = TypeVar("T", int, float) + + +class Sparkline: + """A sparkline representing a series of data. + + Args: + data (Sequence[T]): The sequence of data to render. + width (int, optional): The width of the sparkline/the number of buckets to partition the data into. + min_color (Color, optional): The color of values equal to the min value in data. + max_color (Color, optional): The color of values equal to the max value in data. + summary_function (Callable[list[T]]): Function that will be applied to each bucket. + """ + + BARS = "▁▂▃▄▅▆▇█" + + def __init__( + self, + data: Sequence[T], + *, + width: int | None, + min_color: Color = Color.from_rgb(0, 255, 0), + max_color: Color = Color.from_rgb(255, 0, 0), + summary_function: Callable[[list[T]], float] = max, + ) -> None: + self.data = data + self.width = width + self.min_color = Style.from_color(min_color) + self.max_color = Style.from_color(max_color) + self.summary_function = summary_function + + @classmethod + def _buckets(cls, data: Sequence[T], num_buckets: int) -> Iterable[list[T]]: + """Partition ``data`` into ``num_buckets`` buckets. For example, the data + [1, 2, 3, 4] partitioned into 2 buckets is [[1, 2], [3, 4]]. + + Args: + data (Sequence[T]): The data to partition. + num_buckets (int): The number of buckets to partition the data into. + """ + num_steps, remainder = divmod(len(data), num_buckets) + for i in range(num_buckets): + start = i * num_steps + min(i, remainder) + end = (i + 1) * num_steps + min(i + 1, remainder) + partition = data[start:end] + if partition: + yield partition + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = self.width or options.max_width + len_data = len(self.data) + if len_data == 0: + yield Segment("▁" * width, style=self.min_color) + return + if len_data == 1: + yield Segment("█" * width, style=self.max_color) + return + + minimum, maximum = min(self.data), max(self.data) + extent = maximum - minimum or 1 + + buckets = list(self._buckets(self.data, num_buckets=self.width)) + + bucket_index = 0 + bars_rendered = 0 + step = len(buckets) / width + summary_function = self.summary_function + min_color, max_color = self.min_color.color, self.max_color.color + while bars_rendered < width: + partition = buckets[int(bucket_index)] + partition_summary = summary_function(partition) + height_ratio = (partition_summary - minimum) / extent + bar_index = int(height_ratio * (len(self.BARS) - 1)) + bar_color = _blend_colors(min_color, max_color, height_ratio) + bars_rendered += 1 + bucket_index += step + yield Segment(text=self.BARS[bar_index], style=Style.from_color(bar_color)) + + +def _blend_colors(color1: Color, color2: Color, ratio: float) -> Color: + """Given two RGB colors, return a color that sits some distance between + them in RGB color space. + + Args: + color1 (Color): The first color. + color2 (Color): The second color. + ratio (float): The ratio of color1 to color2. + + Returns: + Color: A Color representing the blending of the two supplied colors. + """ + r1, g1, b1 = color1.triplet + r2, g2, b2 = color2.triplet + dr = r2 - r1 + dg = g2 - g1 + db = b2 - b1 + return Color.from_rgb( + red=r1 + dr * ratio, green=g1 + dg * ratio, blue=b1 + db * ratio + ) + + +if __name__ == "__main__": + console = Console() + + def last(l): + return l[-1] + + funcs = min, max, last, statistics.median, statistics.mean + nums = [10, 2, 30, 60, 45, 20, 7, 8, 9, 10, 50, 13, 10, 6, 5, 4, 3, 7, 20] + console.print(f"data = {nums}\n") + for f in funcs: + console.print( + f"{f.__name__}:\t", Sparkline(nums, width=12, summary_function=f), end="" + ) + console.print("\n")
Textualize/textual
12bfe8c34acd9977495d2d36612af1241a6797b5
diff --git a/tests/renderables/test_sparkline.py b/tests/renderables/test_sparkline.py new file mode 100644 index 000000000..74f1f2f6b --- /dev/null +++ b/tests/renderables/test_sparkline.py @@ -0,0 +1,41 @@ +from tests.utilities.render import render +from textual.renderables.sparkline import Sparkline + +GREEN = "\x1b[38;2;0;255;0m" +RED = "\x1b[38;2;255;0;0m" +BLENDED = "\x1b[38;2;127;127;0m" # Color between red and green +STOP = "\x1b[0m" + + +def test_sparkline_no_data(): + assert render(Sparkline([], width=4)) == f"{GREEN}▁▁▁▁{STOP}" + + +def test_sparkline_single_datapoint(): + assert render(Sparkline([2.5], width=4)) == f"{RED}████{STOP}" + + +def test_sparkline_two_values_min_max(): + assert render(Sparkline([2, 4], width=2)) == f"{GREEN}▁{STOP}{RED}█{STOP}" + + +def test_sparkline_expand_data_to_width(): + assert render(Sparkline([2, 4], + width=4)) == f"{GREEN}▁{STOP}{GREEN}▁{STOP}{RED}█{STOP}{RED}█{STOP}" + + +def test_sparkline_expand_data_to_width_non_divisible(): + assert render(Sparkline([2, 4], width=3)) == f"{GREEN}▁{STOP}{GREEN}▁{STOP}{RED}█{STOP}" + + +def test_sparkline_shrink_data_to_width(): + assert render(Sparkline([2, 2, 4, 4, 6, 6], width=3)) == f"{GREEN}▁{STOP}{BLENDED}▄{STOP}{RED}█{STOP}" + + +def test_sparkline_shrink_data_to_width_non_divisible(): + assert render( + Sparkline([1, 2, 3, 4, 5], width=3, summary_function=min)) == f"{GREEN}▁{STOP}{BLENDED}▄{STOP}{RED}█{STOP}" + + +def test_sparkline_color_blend(): + assert render(Sparkline([1, 2, 3], width=3)) == f"{GREEN}▁{STOP}{BLENDED}▄{STOP}{RED}█{STOP}"
Sparkline renderable Implement a renderable that generates a sparkline. The input should be a list of floats of any size. The Sparkline renderable should use the same block characters as used in the scrollbar to render a minature graph. ```python class Sparkline: def __init__(self, data: list[float], width:int | None): ... ``` Should look something like the following: https://blog.jonudell.net/2021/08/05/the-tao-of-unicode-sparklines/ I think we should also color each bar by blending two colors. Note that the width may not match the data length, so you may need to pick the closes data point.
0.0
12bfe8c34acd9977495d2d36612af1241a6797b5
[ "tests/renderables/test_sparkline.py::test_sparkline_no_data", "tests/renderables/test_sparkline.py::test_sparkline_single_datapoint", "tests/renderables/test_sparkline.py::test_sparkline_two_values_min_max", "tests/renderables/test_sparkline.py::test_sparkline_expand_data_to_width", "tests/renderables/test_sparkline.py::test_sparkline_expand_data_to_width_non_divisible", "tests/renderables/test_sparkline.py::test_sparkline_shrink_data_to_width", "tests/renderables/test_sparkline.py::test_sparkline_shrink_data_to_width_non_divisible", "tests/renderables/test_sparkline.py::test_sparkline_color_blend" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-02-07 11:37:25+00:00
mit
760
Textualize__textual-2692
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7de004cfe..fe30a9778 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed zero division error https://github.com/Textualize/textual/issues/2673 - Fix `scroll_to_center` when there were nested layers out of view (Compositor full_map not populated fully) https://github.com/Textualize/textual/pull/2684 +- Issues with `switch_screen` not updating the results callback appropriately https://github.com/Textualize/textual/issues/2650 ### Added @@ -36,6 +37,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `Tree` and `DirectoryTree` Messages no longer accept a `tree` parameter, using `self.node.tree` instead. https://github.com/Textualize/textual/issues/2529 - Keybinding <kbd>right</kbd> in `Input` is also used to accept a suggestion if the cursor is at the end of the input https://github.com/Textualize/textual/pull/2604 - `Input.__init__` now accepts a `suggester` attribute for completion suggestions https://github.com/Textualize/textual/pull/2604 +- Using `switch_screen` to switch to the currently active screen is now a no-op https://github.com/Textualize/textual/pull/2692 ### Removed diff --git a/src/textual/app.py b/src/textual/app.py index 879edbad5..e9300f8c8 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -1611,15 +1611,19 @@ class App(Generic[ReturnType], DOMNode): raise TypeError( f"switch_screen requires a Screen instance or str; not {screen!r}" ) - if self.screen is not screen: - previous_screen = self._replace_screen(self._screen_stack.pop()) - previous_screen._pop_result_callback() - next_screen, await_mount = self._get_screen(screen) - self._screen_stack.append(next_screen) - self.screen.post_message(events.ScreenResume()) - self.log.system(f"{self.screen} is current (SWITCHED)") - return await_mount - return AwaitMount(self.screen, []) + + next_screen, await_mount = self._get_screen(screen) + if screen is self.screen or next_screen is self.screen: + self.log.system(f"Screen {screen} is already current.") + return AwaitMount(self.screen, []) + + previous_screen = self._replace_screen(self._screen_stack.pop()) + previous_screen._pop_result_callback() + self._screen_stack.append(next_screen) + self.screen.post_message(events.ScreenResume()) + self.screen._push_result_callback(self.screen, None) + self.log.system(f"{self.screen} is current (SWITCHED)") + return await_mount def install_screen(self, screen: Screen, name: str) -> None: """Install a screen.
Textualize/textual
3dea4337ace9fd0727d0f1d799f62a7e6a249023
diff --git a/tests/test_screens.py b/tests/test_screens.py index 033891990..7f42a21a2 100644 --- a/tests/test_screens.py +++ b/tests/test_screens.py @@ -298,3 +298,55 @@ async def test_dismiss_non_top_screen(): await pilot.press("p") with pytest.raises(ScreenStackError): app.bottom.dismiss() + + +async def test_switch_screen_no_op(): + """Regression test for https://github.com/Textualize/textual/issues/2650""" + + class MyScreen(Screen): + pass + + class MyApp(App[None]): + SCREENS = {"screen": MyScreen()} + + def on_mount(self): + self.push_screen("screen") + + app = MyApp() + async with app.run_test(): + screen_id = id(app.screen) + app.switch_screen("screen") + assert screen_id == id(app.screen) + app.switch_screen("screen") + assert screen_id == id(app.screen) + + +async def test_switch_screen_updates_results_callback_stack(): + """Regression test for https://github.com/Textualize/textual/issues/2650""" + + class ScreenA(Screen): + pass + + class ScreenB(Screen): + pass + + class MyApp(App[None]): + SCREENS = { + "a": ScreenA(), + "b": ScreenB(), + } + + def callback(self, _): + return 42 + + def on_mount(self): + self.push_screen("a", self.callback) + + app = MyApp() + async with app.run_test(): + assert len(app.screen._result_callbacks) == 1 + assert app.screen._result_callbacks[-1].callback(None) == 42 + + app.switch_screen("b") + assert len(app.screen._result_callbacks) == 1 + assert app.screen._result_callbacks[-1].callback is None
Report a bug about switch_screen ```python from textual.app import App, ComposeResult from textual.screen import Screen from textual.widgets import Static, Header, Footer class ScreenA(Screen): def compose(self) -> ComposeResult: yield Header() yield Static("A") yield Footer() class ScreenB(Screen): def compose(self) -> ComposeResult: yield Header() yield Static("B") yield Footer() class ModalApp(App): SCREENS = { "a": ScreenA(), "b": ScreenB(), } BINDINGS = [ ("1", "switch_screen('a')", "A"), ("2", "switch_screen('b')", "B"), ] def on_mount(self) -> None: self.push_screen("a") if __name__ == "__main__": app = ModalApp() app.run() ``` This is sample code. When '21' pressed, it will crash. Log below: ``` ╭──────────────────────────────────────────────────────────────────── Traceback (most recent call last) ─────────────────────────────────────────────────────────────────────╮ │ /home/tsing/.local/lib/python3.10/site-packages/textual/app.py:2488 in action_switch_screen │ │ │ │ 2485 │ │ Args: ╭────────────────────────── locals ───────────────────────────╮ │ │ 2486 │ │ │ screen: Name of the screen. │ screen = 'a' │ │ │ 2487 │ │ """ │ self = ModalApp(title='ModalApp', classes={'-dark-mode'}) │ │ │ ❱ 2488 │ │ self.switch_screen(screen) ╰─────────────────────────────────────────────────────────────╯ │ │ 2489 │ │ │ 2490 │ async def action_push_screen(self, screen: str) -> None: │ │ 2491 │ │ """An [action](/guide/actions) to push a new screen on to the stack and make it │ │ │ │ /home/tsing/.local/lib/python3.10/site-packages/textual/app.py:1446 in switch_screen │ │ │ │ 1443 │ │ │ ) ╭─────────────────────────────── locals ───────────────────────────────╮ │ │ 1444 │ │ if self.screen is not screen: │ previous_screen = ScreenB(pseudo_classes={'enabled'}) │ │ │ 1445 │ │ │ previous_screen = self._replace_screen(self._screen_stack.pop()) │ screen = 'a' │ │ │ ❱ 1446 │ │ │ previous_screen._pop_result_callback() │ self = ModalApp(title='ModalApp', classes={'-dark-mode'}) │ │ │ 1447 │ │ │ next_screen, await_mount = self._get_screen(screen) ╰──────────────────────────────────────────────────────────────────────╯ │ │ 1448 │ │ │ self._screen_stack.append(next_screen) │ │ 1449 │ │ │ self.screen.post_message(events.ScreenResume()) │ │ │ │ /home/tsing/.local/lib/python3.10/site-packages/textual/screen.py:572 in _pop_result_callback │ │ │ │ 569 │ ╭────────────────── locals ──────────────────╮ │ │ 570 │ def _pop_result_callback(self) -> None: │ self = ScreenB(pseudo_classes={'enabled'}) │ │ │ 571 │ │ """Remove the latest result callback from the stack.""" ╰────────────────────────────────────────────╯ │ │ ❱ 572 │ │ self._result_callbacks.pop() │ │ 573 │ │ │ 574 │ def _refresh_layout( │ │ 575 │ │ self, size: Size | None = None, full: bool = False, scroll: bool = False │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ IndexError: pop from empty list ``` The direct reason is `_ push_ result_ callback` not called when `switch_screen`, or check `self._result_callbacks` is empty when pop.
0.0
3dea4337ace9fd0727d0f1d799f62a7e6a249023
[ "tests/test_screens.py::test_switch_screen_no_op", "tests/test_screens.py::test_switch_screen_updates_results_callback_stack" ]
[ "tests/test_screens.py::test_screen_walk_children", "tests/test_screens.py::test_installed_screens", "tests/test_screens.py::test_screens", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_none", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_disabled", "tests/test_screens.py::test_auto_focus_inheritance", "tests/test_screens.py::test_auto_focus_skips_non_focusable_widgets", "tests/test_screens.py::test_dismiss_non_top_screen" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-05-30 12:55:51+00:00
mit
761
Textualize__textual-2776
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d887f32b..e9c9c2004 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed exceptions in Pilot tests being silently ignored https://github.com/Textualize/textual/pull/2754 - Fixed issue where internal data of `OptionList` could be invalid for short window after `clear_options` https://github.com/Textualize/textual/pull/2754 - Fixed `Tooltip` causing a `query_one` on a lone `Static` to fail https://github.com/Textualize/textual/issues/2723 +- Nested widgets wouldn't lose focus when parent is disabled https://github.com/Textualize/textual/issues/2772 ### Changed diff --git a/src/textual/widget.py b/src/textual/widget.py index 99e4b78eb..3306da7dd 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -2743,7 +2743,17 @@ class Widget(DOMNode): def watch_disabled(self) -> None: """Update the styles of the widget and its children when disabled is toggled.""" - self.blur() + from .app import ScreenStackError + + try: + if ( + self.disabled + and self.app.focused is not None + and self in self.app.focused.ancestors_with_self + ): + self.app.focused.blur() + except ScreenStackError: + pass self._update_styles() def _size_updated(
Textualize/textual
436b1184a9013295e903ce5d86641b9e57cfb014
diff --git a/tests/test_disabled.py b/tests/test_disabled.py index bc0692ad0..f5edb492c 100644 --- a/tests/test_disabled.py +++ b/tests/test_disabled.py @@ -1,15 +1,24 @@ """Test Widget.disabled.""" +import pytest + from textual.app import App, ComposeResult -from textual.containers import VerticalScroll +from textual.containers import Vertical, VerticalScroll from textual.widgets import ( Button, + Checkbox, DataTable, DirectoryTree, Input, + Label, + ListItem, ListView, Markdown, MarkdownViewer, + OptionList, + RadioButton, + RadioSet, + Select, Switch, TextLog, Tree, @@ -82,3 +91,59 @@ async def test_disable_via_container() -> None: node.has_pseudo_class("disabled") and not node.has_pseudo_class("enabled") for node in pilot.app.screen.query("#test-container > *") ) + + +class ChildrenNoFocusDisabledContainer(App[None]): + """App for regression test for https://github.com/Textualize/textual/issues/2772.""" + + def compose(self) -> ComposeResult: + with Vertical(): + with Vertical(): + yield Button() + yield Checkbox() + yield DataTable() + yield DirectoryTree(".") + yield Input() + with ListView(): + yield ListItem(Label("one")) + yield ListItem(Label("two")) + yield ListItem(Label("three")) + yield OptionList("one", "two", "three") + with RadioSet(): + yield RadioButton("one") + yield RadioButton("two") + yield RadioButton("three") + yield Select([("one", 1), ("two", 2), ("three", 3)]) + yield Switch() + + def on_mount(self): + dt = self.query_one(DataTable) + dt.add_columns("one", "two", "three") + dt.add_rows([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]) + + [email protected]( + "widget", + [ + Button, + Checkbox, + DataTable, + DirectoryTree, + Input, + ListView, + OptionList, + RadioSet, + Select, + Switch, + ], +) +async def test_children_loses_focus_if_container_is_disabled(widget): + """Regression test for https://github.com/Textualize/textual/issues/2772.""" + app = ChildrenNoFocusDisabledContainer() + async with app.run_test() as pilot: + app.query(widget).first().focus() + await pilot.pause() + assert isinstance(app.focused, widget) + app.query(Vertical).first().disabled = True + await pilot.pause() + assert app.focused is None
Shouldn't be able to type in to a disabled input If a widget is *enabled* and has focus, then subsequently *disabled*, you are still able to type. When an input is disabled, it should ignore all interactions.
0.0
436b1184a9013295e903ce5d86641b9e57cfb014
[ "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[Button]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[Checkbox]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[DataTable]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[DirectoryTree]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[Input]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[ListView]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[OptionList]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[RadioSet]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[Select]", "tests/test_disabled.py::test_children_loses_focus_if_container_is_disabled[Switch]" ]
[ "tests/test_disabled.py::test_all_initially_enabled", "tests/test_disabled.py::test_enabled_widgets_have_enabled_pseudo_class", "tests/test_disabled.py::test_all_individually_disabled", "tests/test_disabled.py::test_disabled_widgets_have_disabled_pseudo_class", "tests/test_disabled.py::test_disable_via_container" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-06-13 15:15:47+00:00
mit
762
Textualize__textual-2981
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d9b2b217..bf9a3b79b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - Fixed a crash when a `SelectionList` had a prompt wider than itself https://github.com/Textualize/textual/issues/2900 +- Fixed a bug where `Click` events were bubbling up from `Switch` widgets https://github.com/Textualize/textual/issues/2366 ## [0.30.0] - 2023-07-17 diff --git a/src/textual/widgets/_switch.py b/src/textual/widgets/_switch.py index d19ee168e..eb0568c61 100644 --- a/src/textual/widgets/_switch.py +++ b/src/textual/widgets/_switch.py @@ -154,8 +154,9 @@ class Switch(Widget, can_focus=True): def get_content_height(self, container: Size, viewport: Size, width: int) -> int: return 1 - async def _on_click(self, _: Click) -> None: + async def _on_click(self, event: Click) -> None: """Toggle the state of the switch.""" + event.stop() self.toggle() def action_toggle(self) -> None:
Textualize/textual
2f055f6234928a37207759bc48876965905dc966
diff --git a/tests/test_switch.py b/tests/test_switch.py new file mode 100644 index 000000000..e0868118f --- /dev/null +++ b/tests/test_switch.py @@ -0,0 +1,18 @@ +from textual.app import App, ComposeResult +from textual.widgets import Switch + + +async def test_switch_click_doesnt_bubble_up(): + """Regression test for https://github.com/Textualize/textual/issues/2366""" + + class SwitchApp(App[None]): + def compose(self) -> ComposeResult: + yield Switch() + + async def on_click(self) -> None: + raise AssertionError( + "The app should never receive a click event when Switch is clicked." + ) + + async with SwitchApp().run_test() as pilot: + await pilot.click(Switch)
`Switch` should stop the `Click` event from bubbling At the moment `Switch` handles `Click` but then lets it bubble; there's no good reason to do that and it also stops the ability to write something like this: ```python from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widgets import Header, Footer, Label, Switch class LabeledSwitch( Horizontal ): def on_click( self ) -> None: self.query_one(Switch).toggle() class ClickableLabelApp( App[ None ] ): def compose( self ) -> ComposeResult: yield Header() with LabeledSwitch(): yield Label( "Click me!" ) yield Switch() yield Footer() if __name__ == "__main__": ClickableLabelApp().run() ``` where the idea is to make a compound widget that lets you click on the `Label` or the `Switch` and the `Switch` will toggle -- only it doesn't work if you click on the `Switch` because it ends up double-toggling.
0.0
2f055f6234928a37207759bc48876965905dc966
[ "tests/test_switch.py::test_switch_click_doesnt_bubble_up" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-22 09:26:53+00:00
mit
763
Textualize__textual-2984
diff --git a/CHANGELOG.md b/CHANGELOG.md index bf9a3b79b..ec1c24b51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed a crash when a `SelectionList` had a prompt wider than itself https://github.com/Textualize/textual/issues/2900 - Fixed a bug where `Click` events were bubbling up from `Switch` widgets https://github.com/Textualize/textual/issues/2366 +- Fixed a crash when using empty CSS variables https://github.com/Textualize/textual/issues/1849 ## [0.30.0] - 2023-07-17 diff --git a/src/textual/css/parse.py b/src/textual/css/parse.py index 13aeea488..1b31e8b66 100644 --- a/src/textual/css/parse.py +++ b/src/textual/css/parse.py @@ -269,6 +269,7 @@ def substitute_references( break if token.name == "variable_name": variable_name = token.value[1:-1] # Trim the $ and the :, i.e. "$x:" -> "x" + variable_tokens = variables.setdefault(variable_name, []) yield token while True: @@ -284,7 +285,7 @@ def substitute_references( if not token: break elif token.name == "whitespace": - variables.setdefault(variable_name, []).append(token) + variable_tokens.append(token) yield token elif token.name == "variable_value_end": yield token @@ -293,7 +294,6 @@ def substitute_references( elif token.name == "variable_ref": ref_name = token.value[1:] if ref_name in variables: - variable_tokens = variables.setdefault(variable_name, []) reference_tokens = variables[ref_name] variable_tokens.extend(reference_tokens) ref_location = token.location @@ -307,7 +307,7 @@ def substitute_references( else: _unresolved(ref_name, variables.keys(), token) else: - variables.setdefault(variable_name, []).append(token) + variable_tokens.append(token) yield token token = next(iter_tokens, None) elif token.name == "variable_ref": diff --git a/src/textual/events.py b/src/textual/events.py index 4e2523535..3f6015dfb 100644 --- a/src/textual/events.py +++ b/src/textual/events.py @@ -4,7 +4,7 @@ Builtin events sent by Textual. Events may be marked as "Bubbles" and "Verbose". See the [events guide](/guide/events/#bubbling) for an explanation of bubbling. -Verbose events are excluded from the textual console, unless you explicit request them with the `-v` switch as follows: +Verbose events are excluded from the textual console, unless you explicitly request them with the `-v` switch as follows: ``` textual console -v
Textualize/textual
42dc3af34725245dca9b43608d0bbe8f636fdd4b
diff --git a/tests/css/test_parse.py b/tests/css/test_parse.py index fea7b3dad..cb6e6aad0 100644 --- a/tests/css/test_parse.py +++ b/tests/css/test_parse.py @@ -220,6 +220,22 @@ class TestVariableReferenceSubstitution: with pytest.raises(UnresolvedVariableError): list(substitute_references(tokenize(css, ""))) + def test_empty_variable(self): + css = "$x:\n* { background:$x; }" + result = list(substitute_references(tokenize(css, ""))) + assert [(t.name, t.value) for t in result] == [ + ("variable_name", "$x:"), + ("variable_value_end", "\n"), + ("selector_start_universal", "*"), + ("whitespace", " "), + ("declaration_set_start", "{"), + ("whitespace", " "), + ("declaration_name", "background:"), + ("declaration_end", ";"), + ("whitespace", " "), + ("declaration_set_end", "}"), + ] + def test_transitive_reference(self): css = "$x: 1\n$y: $x\n.thing { border: $y }" assert list(substitute_references(tokenize(css, ""))) == [
Allow for empty CSS variable definitions Consider the following CSS snippets: 1. ```sass $x: * { background: red; } ``` 2. ```sass $x: * { background: $x; } ``` 3. ```sass * { background: red; } $x: ``` All three should work with the following behaviour: - an empty variable definition is allowed; and - setting a style to an empty variable should unset that style. For example, 2. should unset the background of all widgets. As of now, 2. and 3. can't be parsed. 2. raises an error regarding an undefined variable and 3. raises an `AttributeError` inside `substitute_references` in `parse.py`.
0.0
42dc3af34725245dca9b43608d0bbe8f636fdd4b
[ "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_empty_variable" ]
[ "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_simple_reference", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_simple_reference_no_whitespace", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_undefined_variable", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_transitive_reference", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_multi_value_variable", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_used_inside_property_value", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_definition_eof", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_reference_whitespace_trimming", "tests/css/test_parse.py::TestParseLayout::test_valid_layout_name", "tests/css/test_parse.py::TestParseLayout::test_invalid_layout_name", "tests/css/test_parse.py::TestParseText::test_foreground", "tests/css/test_parse.py::TestParseText::test_background", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgb(1,255,50)-result0]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgb(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgba(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsl(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsl(180,50%,50%)-result5]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsla(180,50%,50%,0.25)-result6]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsla(", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[-5.5%-parsed_x0--30%-parsed_y0]", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[5%-parsed_x1-40%-parsed_y1]", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[10-parsed_x2-40-parsed_y2]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[-5.5%-parsed_x0--30%-parsed_y0]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[5%-parsed_x1-40%-parsed_y1]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[-10-parsed_x2-40-parsed_y2]", "tests/css/test_parse.py::TestParseOverflow::test_multiple_enum", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[5.57s-5.57]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.5s-0.5]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[1200ms-1.2]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.5ms-0.0005]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[20-20.0]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.1-0.1]", "tests/css/test_parse.py::TestParseTransition::test_no_delay_specified", "tests/css/test_parse.py::TestParseTransition::test_unknown_easing_function", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[-0.2-0.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[0.4-0.4]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[1.3-1.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[-20%-0.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[25%-0.25]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[128%-1.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_invalid_value", "tests/css/test_parse.py::TestParseMargin::test_margin_partial", "tests/css/test_parse.py::TestParsePadding::test_padding_partial", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[left]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[start]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[center]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[right]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[end]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[justify]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align_invalid", "tests/css/test_parse.py::TestParseTextAlign::test_text_align_empty_uses_default", "tests/css/test_parse.py::TestTypeNames::test_type_no_number", "tests/css/test_parse.py::TestTypeNames::test_type_with_number", "tests/css/test_parse.py::TestTypeNames::test_type_starts_with_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_no_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_with_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_starts_with_number", "tests/css/test_parse.py::test_parse_bad_psuedo_selector" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-22 09:52:46+00:00
mit
764
Textualize__textual-2987
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e9bfe956..5535d3101 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed unintuitive sizing behaviour of TabbedContent https://github.com/Textualize/textual/issues/2411 - Fixed relative units not always expanding auto containers https://github.com/Textualize/textual/pull/3059 - Fixed background refresh https://github.com/Textualize/textual/issues/3055 +- `MouseMove` events bubble up from widgets. `App` and `Screen` receive `MouseMove` events even if there's no Widget under the cursor. https://github.com/Textualize/textual/issues/2905 ### Added - Added an interface for replacing prompt of an individual option in an `OptionList` https://github.com/Textualize/textual/issues/2603 diff --git a/docs/events/mouse_move.md b/docs/events/mouse_move.md index 12cdca5f9..a781a2809 100644 --- a/docs/events/mouse_move.md +++ b/docs/events/mouse_move.md @@ -2,7 +2,7 @@ The `MouseMove` event is sent to a widget when the mouse pointer is moved over a widget. -- [ ] Bubbles +- [x] Bubbles - [x] Verbose ## Attributes diff --git a/src/textual/events.py b/src/textual/events.py index ccc2cc0cb..5c7ffaa2b 100644 --- a/src/textual/events.py +++ b/src/textual/events.py @@ -435,10 +435,10 @@ class MouseEvent(InputEvent, bubble=True): @rich.repr.auto -class MouseMove(MouseEvent, bubble=False, verbose=True): +class MouseMove(MouseEvent, bubble=True, verbose=True): """Sent when the mouse cursor moves. - - [ ] Bubbles + - [X] Bubbles - [X] Verbose """ diff --git a/src/textual/screen.py b/src/textual/screen.py index 1a9b9af2e..12514bdf3 100644 --- a/src/textual/screen.py +++ b/src/textual/screen.py @@ -825,22 +825,13 @@ class Screen(Generic[ScreenResultType], Widget): else: self.app._set_mouse_over(widget) - mouse_event = events.MouseMove( - event.x - region.x, - event.y - region.y, - event.delta_x, - event.delta_y, - event.button, - event.shift, - event.meta, - event.ctrl, - screen_x=event.screen_x, - screen_y=event.screen_y, - style=event.style, - ) widget.hover_style = event.style - mouse_event._set_forwarded() - widget._forward_event(mouse_event) + if widget is self: + self.post_message(event) + else: + mouse_event = self._translate_mouse_move_event(event, region) + mouse_event._set_forwarded() + widget._forward_event(mouse_event) if not self.app._disable_tooltips: try: @@ -861,6 +852,28 @@ class Screen(Generic[ScreenResultType], Widget): else: tooltip.display = False + @staticmethod + def _translate_mouse_move_event( + event: events.MouseMove, region: Region + ) -> events.MouseMove: + """ + Returns a mouse move event whose relative coordinates are translated to + the origin of the specified region. + """ + return events.MouseMove( + event.x - region.x, + event.y - region.y, + event.delta_x, + event.delta_y, + event.button, + event.shift, + event.meta, + event.ctrl, + screen_x=event.screen_x, + screen_y=event.screen_y, + style=event.style, + ) + def _forward_event(self, event: events.Event) -> None: if event.is_forwarded: return
Textualize/textual
49612e3aa5ddf3e16bd959199a8886c3f8d2328d
diff --git a/tests/test_screens.py b/tests/test_screens.py index d1d70ad4c..5f587fd0e 100644 --- a/tests/test_screens.py +++ b/tests/test_screens.py @@ -4,7 +4,9 @@ import threading import pytest -from textual.app import App, ScreenStackError +from textual.app import App, ScreenStackError, ComposeResult +from textual.events import MouseMove +from textual.geometry import Offset from textual.screen import Screen from textual.widgets import Button, Input, Label @@ -350,3 +352,59 @@ async def test_switch_screen_updates_results_callback_stack(): app.switch_screen("b") assert len(app.screen._result_callbacks) == 1 assert app.screen._result_callbacks[-1].callback is None + + +async def test_screen_receives_mouse_move_events(): + class MouseMoveRecordingScreen(Screen): + mouse_events = [] + + def on_mouse_move(self, event: MouseMove) -> None: + MouseMoveRecordingScreen.mouse_events.append(event) + + class SimpleApp(App[None]): + SCREENS = {"a": MouseMoveRecordingScreen()} + + def on_mount(self): + self.push_screen("a") + + mouse_offset = Offset(1, 1) + + async with SimpleApp().run_test() as pilot: + await pilot.hover(None, mouse_offset) + + assert len(MouseMoveRecordingScreen.mouse_events) == 1 + mouse_event = MouseMoveRecordingScreen.mouse_events[0] + assert mouse_event.x, mouse_event.y == mouse_offset + + +async def test_mouse_move_event_bubbles_to_screen_from_widget(): + class MouseMoveRecordingScreen(Screen): + mouse_events = [] + + DEFAULT_CSS = """ + Label { + offset: 10 10; + } + """ + + def compose(self) -> ComposeResult: + yield Label("Any label") + + def on_mouse_move(self, event: MouseMove) -> None: + MouseMoveRecordingScreen.mouse_events.append(event) + + class SimpleApp(App[None]): + SCREENS = {"a": MouseMoveRecordingScreen()} + + def on_mount(self): + self.push_screen("a") + + label_offset = Offset(10, 10) + mouse_offset = Offset(1, 1) + + async with SimpleApp().run_test() as pilot: + await pilot.hover(Label, mouse_offset) + + assert len(MouseMoveRecordingScreen.mouse_events) == 1 + mouse_event = MouseMoveRecordingScreen.mouse_events[0] + assert mouse_event.x, mouse_event.y == (label_offset.x + mouse_offset.x, label_offset.y + mouse_offset.y)
Send mouse move events to screen It look like mouse move events never make it to the Screen object. I think they should.
0.0
49612e3aa5ddf3e16bd959199a8886c3f8d2328d
[ "tests/test_screens.py::test_screen_receives_mouse_move_events", "tests/test_screens.py::test_mouse_move_event_bubbles_to_screen_from_widget" ]
[ "tests/test_screens.py::test_screen_walk_children", "tests/test_screens.py::test_installed_screens", "tests/test_screens.py::test_screens", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_none", "tests/test_screens.py::test_auto_focus_on_screen_if_app_auto_focus_is_disabled", "tests/test_screens.py::test_auto_focus_inheritance", "tests/test_screens.py::test_auto_focus_skips_non_focusable_widgets", "tests/test_screens.py::test_dismiss_non_top_screen", "tests/test_screens.py::test_switch_screen_no_op", "tests/test_screens.py::test_switch_screen_updates_results_callback_stack" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-22 14:22:57+00:00
mit
765
Textualize__textual-3050
diff --git a/CHANGELOG.md b/CHANGELOG.md index 705eb5dd3..8019a5f1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Ensuring `TextArea.SelectionChanged` message only sends when the updated selection is different https://github.com/Textualize/textual/pull/3933 - Fixed declaration after nested rule set causing a parse error https://github.com/Textualize/textual/pull/4012 - ID and class validation was too lenient https://github.com/Textualize/textual/issues/3954 +- Fixed display of keys when used in conjunction with other keys https://github.com/Textualize/textual/pull/3050 ## [0.47.1] - 2023-01-05 @@ -437,7 +438,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [0.33.0] - 2023-08-15 - ### Fixed - Fixed unintuitive sizing behaviour of TabbedContent https://github.com/Textualize/textual/issues/2411 diff --git a/src/textual/keys.py b/src/textual/keys.py index ef32404d1..36da438d2 100644 --- a/src/textual/keys.py +++ b/src/textual/keys.py @@ -283,6 +283,9 @@ def _get_key_display(key: str) -> str: """Given a key (i.e. the `key` string argument to Binding __init__), return the value that should be displayed in the app when referring to this key (e.g. in the Footer widget).""" + if "+" in key: + return "+".join([_get_key_display(key) for key in key.split("+")]) + display_alias = KEY_DISPLAY_ALIASES.get(key) if display_alias: return display_alias
Textualize/textual
81808d93c9fa122c4b3dd9ab1a6a934869937320
diff --git a/tests/test_keys.py b/tests/test_keys.py index 9f13e17d1..3aac179fc 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -52,3 +52,20 @@ async def test_character_bindings(): def test_get_key_display(): assert _get_key_display("minus") == "-" + + +def test_get_key_display_when_used_in_conjunction(): + """Test a key display is the same if used in conjunction with another key. + For example, "ctrl+right_square_bracket" should display the bracket as "]", + the same as it would without the ctrl modifier. + + Regression test for #3035 https://github.com/Textualize/textual/issues/3035 + """ + + right_square_bracket = _get_key_display("right_square_bracket") + ctrl_right_square_bracket = _get_key_display("ctrl+right_square_bracket") + assert ctrl_right_square_bracket == f"CTRL+{right_square_bracket}" + + left = _get_key_display("left") + ctrl_left = _get_key_display("ctrl+left") + assert ctrl_left == f"CTRL+{left}"
Binding for `]` renders incorrectly in `Footer` The binding `Binding("ctrl+right_square_bracket", "toggle_indent_width", "Cycle indent width")` renders like this: <img width="431" alt="image" src="https://github.com/Textualize/textual/assets/5740731/2c2bd6fa-288b-4205-aba0-48eb1b6c41e0"> It should probably render as `Ctrl+]`.
0.0
81808d93c9fa122c4b3dd9ab1a6a934869937320
[ "tests/test_keys.py::test_get_key_display_when_used_in_conjunction" ]
[ "tests/test_keys.py::test_character_to_key[1-1]", "tests/test_keys.py::test_character_to_key[2-2]", "tests/test_keys.py::test_character_to_key[a-a]", "tests/test_keys.py::test_character_to_key[z-z]", "tests/test_keys.py::test_character_to_key[_-underscore]", "tests/test_keys.py::test_character_to_key[", "tests/test_keys.py::test_character_to_key[~-tilde]", "tests/test_keys.py::test_character_to_key[?-question_mark]", "tests/test_keys.py::test_character_to_key[\\xa3-pound_sign]", "tests/test_keys.py::test_character_to_key[,-comma]", "tests/test_keys.py::test_character_bindings", "tests/test_keys.py::test_get_key_display" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-08-02 17:16:33+00:00
mit
766
Textualize__textual-319
diff --git a/.gitignore b/.gitignore index bc0dfdb71..a20548735 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .pytype .DS_Store .vscode +.idea mypy_report docs/build docs/source/_build diff --git a/src/textual/_region_group.py b/src/textual/_region_group.py new file mode 100644 index 000000000..096007987 --- /dev/null +++ b/src/textual/_region_group.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from collections import defaultdict +from operator import attrgetter +from typing import NamedTuple, Iterable + +from .geometry import Region + + +class InlineRange(NamedTuple): + """Represents a region on a single line.""" + + line_index: int + start: int + end: int + + +def regions_to_ranges(regions: Iterable[Region]) -> Iterable[InlineRange]: + """Converts the regions to non-overlapping horizontal strips, where each strip + represents the region on a single line. Combining the resulting strips therefore + results in a shape identical to the combined original regions. + + Args: + regions (Iterable[Region]): An iterable of Regions. + + Returns: + Iterable[InlineRange]: Yields InlineRange objects representing the content on + a single line, with overlaps removed. + """ + inline_ranges: dict[int, list[InlineRange]] = defaultdict(list) + for region_x, region_y, width, height in regions: + for y in range(region_y, region_y + height): + inline_ranges[y].append( + InlineRange(line_index=y, start=region_x, end=region_x + width - 1) + ) + + get_start = attrgetter("start") + for line_index, ranges in inline_ranges.items(): + sorted_ranges = iter(sorted(ranges, key=get_start)) + _, start, end = next(sorted_ranges) + for next_line_index, next_start, next_end in sorted_ranges: + if next_start <= end + 1: + end = max(end, next_end) + else: + yield InlineRange(line_index, start, end) + start = next_start + end = next_end + yield InlineRange(line_index, start, end)
Textualize/textual
d01a35dd5a75f480252cf441734b96b65dae2169
diff --git a/tests/test_region_group.py b/tests/test_region_group.py new file mode 100644 index 000000000..930489a89 --- /dev/null +++ b/tests/test_region_group.py @@ -0,0 +1,44 @@ +from textual._region_group import regions_to_ranges, InlineRange +from textual.geometry import Region + + +def test_regions_to_ranges_no_regions(): + assert list(regions_to_ranges([])) == [] + + +def test_regions_to_ranges_single_region(): + regions = [Region(0, 0, 3, 2)] + assert list(regions_to_ranges(regions)) == [InlineRange(0, 0, 2), InlineRange(1, 0, 2)] + + +def test_regions_to_ranges_partially_overlapping_regions(): + regions = [Region(0, 0, 2, 2), Region(1, 1, 2, 2)] + assert list(regions_to_ranges(regions)) == [ + InlineRange(0, 0, 1), InlineRange(1, 0, 2), InlineRange(2, 1, 2), + ] + + +def test_regions_to_ranges_fully_overlapping_regions(): + regions = [Region(1, 1, 3, 3), Region(2, 2, 1, 1), Region(0, 2, 3, 1)] + assert list(regions_to_ranges(regions)) == [ + InlineRange(1, 1, 3), InlineRange(2, 0, 3), InlineRange(3, 1, 3) + ] + + +def test_regions_to_ranges_disjoint_regions_different_lines(): + regions = [Region(0, 0, 2, 1), Region(2, 2, 2, 1)] + assert list(regions_to_ranges(regions)) == [InlineRange(0, 0, 1), InlineRange(2, 2, 3)] + + +def test_regions_to_ranges_disjoint_regions_same_line(): + regions = [Region(0, 0, 1, 2), Region(2, 0, 1, 1)] + assert list(regions_to_ranges(regions)) == [ + InlineRange(0, 0, 0), InlineRange(0, 2, 2), InlineRange(1, 0, 0) + ] + + +def test_regions_to_ranges_directly_adjacent_ranges_merged(): + regions = [Region(0, 0, 1, 2), Region(1, 0, 1, 2)] + assert list(regions_to_ranges(regions)) == [ + InlineRange(0, 0, 1), InlineRange(1, 0, 1) + ]
Overlapping region resolver We need a container class which manages overlapping regions. Internally it will act like a container of Region objects (probably a simple list). Additionally there will be a method which generates a sequence of Region objects which cover the same area, but with no overlapping. Discuss with @willmcgugan as this likely needs further explanation.
0.0
d01a35dd5a75f480252cf441734b96b65dae2169
[ "tests/test_region_group.py::test_regions_to_ranges_no_regions", "tests/test_region_group.py::test_regions_to_ranges_single_region", "tests/test_region_group.py::test_regions_to_ranges_partially_overlapping_regions", "tests/test_region_group.py::test_regions_to_ranges_fully_overlapping_regions", "tests/test_region_group.py::test_regions_to_ranges_disjoint_regions_different_lines", "tests/test_region_group.py::test_regions_to_ranges_disjoint_regions_same_line", "tests/test_region_group.py::test_regions_to_ranges_directly_adjacent_ranges_merged" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-03-02 15:46:23+00:00
mit
767
Textualize__textual-3334
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f29d01ec..65b8b69b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed the command palette crashing with a `TimeoutError` in any Python before 3.11 https://github.com/Textualize/textual/issues/3320 - Fixed `Input` event leakage from `CommandPalette` to `App`. +### Changed + +- Breaking change: Changed `Markdown.goto_anchor` to return a boolean (if the anchor was found) instead of `None` https://github.com/Textualize/textual/pull/3334 + ## [0.37.0] - 2023-09-15 ### Added diff --git a/src/textual/widgets/_markdown.py b/src/textual/widgets/_markdown.py index af125c4fa..f3deec3e2 100644 --- a/src/textual/widgets/_markdown.py +++ b/src/textual/widgets/_markdown.py @@ -660,7 +660,7 @@ class Markdown(Widget): location, _, anchor = location.partition("#") return Path(location), anchor - def goto_anchor(self, anchor: str) -> None: + def goto_anchor(self, anchor: str) -> bool: """Try and find the given anchor in the current document. Args: @@ -673,14 +673,18 @@ class Markdown(Widget): Note that the slugging method used is similar to that found on GitHub. + + Returns: + True when the anchor was found in the current document, False otherwise. """ if not self._table_of_contents or not isinstance(self.parent, Widget): - return + return False unique = TrackedSlugs() for _, title, header_id in self._table_of_contents: if unique.slug(title) == anchor: self.parent.scroll_to_widget(self.query_one(f"#{header_id}"), top=True) - return + return True + return False async def load(self, path: Path) -> None: """Load a new Markdown document.
Textualize/textual
79e9f3bc16cefd9a9b2bece2b11bfa3ce35422b9
diff --git a/tests/test_markdown.py b/tests/test_markdown.py index 5002430d7..da4c016aa 100644 --- a/tests/test_markdown.py +++ b/tests/test_markdown.py @@ -125,3 +125,18 @@ async def test_load_non_existing_file() -> None: await pilot.app.query_one(Markdown).load( Path("---this-does-not-exist---.it.is.not.a.md") ) + + [email protected]( + ("anchor", "found"), + [ + ("hello-world", False), + ("hello-there", True), + ] +) +async def test_goto_anchor(anchor: str, found: bool) -> None: + """Going to anchors should return a boolean: whether the anchor was found.""" + document = "# Hello There\n\nGeneral.\n" + async with MarkdownApp(document).run_test() as pilot: + markdown = pilot.app.query_one(Markdown) + assert markdown.goto_anchor(anchor) is found
Return boolean from Markdown.goto_anchor Hey again! I'm updating my code to work with Textual now that it has fixed going to anchors in a Markdown document. Textual is working well, however I'm facing an issue while trying to extend its behavior. Basically, in the Markdown documents I generate (in my API docs textual browser :wink:), I can have both anchors that exist within the document, and anchors that do not. When the anchor exist, I want to simply go to that anchor. When it doesn't exist, I want to generate the corresponding Markdown and update the viewer with it. The issue is that there's no easy way to know if the anchor exists. I'd have to either: - check somehow if the document scrolled to somewhere else after the anchor was clicked (no idea if that is possible, doesn't sound robust/efficient) - rebuild the list of slugs myself, accessing private variables like `Markdown._table_of_contents`, and slugify my anchor to check if it's within this list Instead, it would be super convenient if the `Markdown.goto_anchor` method returned a boolean: true when it found the anchor, false otherwise. That way I can simply do this in my own code: ```python class GriffeMarkdownViewer(MarkdownViewer): async def _on_markdown_link_clicked(self, message: Markdown.LinkClicked) -> None: message.prevent_default() anchor = message.href if anchor.startswith("#"): # Try going to the anchor in the current document. if not self.document.goto_anchor(anchor.lstrip("#").replace(".", "").lower()): try: # Anchor not on the page: it's another object, load it and render it. markdown = _to_markdown(self.griffe_loader, anchor.lstrip("#")) except Exception as error: # noqa: BLE001,S110 logger.exception(error) else: self.document.update(markdown) else: # Try default behavior of the viewer. await self.go(anchor) ``` Emphasis on `if not self.document.goto_anchor(...)` :slightly_smiling_face: The change is easy and backward-compatible: ```python def goto_anchor(self, anchor: str) -> bool: if not self._table_of_contents or not isinstance(self.parent, Widget): return False unique = TrackedSlugs() for _, title, header_id in self._table_of_contents: if unique.slug(title) == anchor: self.parent.scroll_to_widget(self.query_one(f"#{header_id}"), top=True) return True return False ``` If you think that is worth adding, I can send a PR! We can also discuss further, as there are probably other ways to make this possible/easier, for example by adding a `Markdown.anchor_exists` method :shrug:
0.0
79e9f3bc16cefd9a9b2bece2b11bfa3ce35422b9
[ "tests/test_markdown.py::test_goto_anchor[hello-world-False]", "tests/test_markdown.py::test_goto_anchor[hello-there-True]" ]
[ "tests/test_markdown.py::test_markdown_nodes[-expected_nodes0]", "tests/test_markdown.py::test_markdown_nodes[#", "tests/test_markdown.py::test_markdown_nodes[##", "tests/test_markdown.py::test_markdown_nodes[###", "tests/test_markdown.py::test_markdown_nodes[####", "tests/test_markdown.py::test_markdown_nodes[#####", "tests/test_markdown.py::test_markdown_nodes[######", "tests/test_markdown.py::test_markdown_nodes[----expected_nodes7]", "tests/test_markdown.py::test_markdown_nodes[Hello-expected_nodes8]", "tests/test_markdown.py::test_markdown_nodes[Hello\\nWorld-expected_nodes9]", "tests/test_markdown.py::test_markdown_nodes[>", "tests/test_markdown.py::test_markdown_nodes[-", "tests/test_markdown.py::test_markdown_nodes[1.", "tests/test_markdown.py::test_markdown_nodes[", "tests/test_markdown.py::test_markdown_nodes[```\\n1\\n```-expected_nodes14]", "tests/test_markdown.py::test_markdown_nodes[```python\\n1\\n```-expected_nodes15]", "tests/test_markdown.py::test_markdown_nodes[|", "tests/test_markdown.py::test_softbreak_split_links_rendered_correctly", "tests/test_markdown.py::test_load_non_existing_file" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-09-17 09:38:33+00:00
mit
768
Textualize__textual-3360
diff --git a/CHANGELOG.md b/CHANGELOG.md index c401104de..330dac5bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `Pilot.click`/`Pilot.hover` can't use `Screen` as a selector https://github.com/Textualize/textual/issues/3395 +### Added + +- `OutOfBounds` exception to be raised by `Pilot` https://github.com/Textualize/textual/pull/3360 + +### Changed + +- `Pilot.click`/`Pilot.hover` now raises `OutOfBounds` when clicking outside visible screen https://github.com/Textualize/textual/pull/3360 +- `Pilot.click`/`Pilot.hover` now return a Boolean indicating whether the click/hover landed on the widget that matches the selector https://github.com/Textualize/textual/pull/3360 + ## [0.38.1] - 2023-09-21 ### Fixed diff --git a/src/textual/pilot.py b/src/textual/pilot.py index c15441d0b..9069f61a3 100644 --- a/src/textual/pilot.py +++ b/src/textual/pilot.py @@ -16,6 +16,7 @@ import rich.repr from ._wait import wait_for_idle from .app import App, ReturnType from .events import Click, MouseDown, MouseMove, MouseUp +from .geometry import Offset from .widget import Widget @@ -44,6 +45,10 @@ def _get_mouse_message_arguments( return message_arguments +class OutOfBounds(Exception): + """Raised when the pilot mouse target is outside of the (visible) screen.""" + + class WaitForScreenTimeout(Exception): """Exception raised if messages aren't being processed quickly enough. @@ -83,19 +88,30 @@ class Pilot(Generic[ReturnType]): shift: bool = False, meta: bool = False, control: bool = False, - ) -> None: - """Simulate clicking with the mouse. + ) -> bool: + """Simulate clicking with the mouse at a specified position. + + The final position to be clicked is computed based on the selector provided and + the offset specified and it must be within the visible area of the screen. Args: - selector: The widget that should be clicked. If None, then the click - will occur relative to the screen. Note that this simply causes - a click to occur at the location of the widget. If the widget is - currently hidden or obscured by another widget, then the click may - not land on it. - offset: The offset to click within the selected widget. + selector: A selector to specify a widget that should be used as the reference + for the click offset. If this is not specified, the offset is interpreted + relative to the screen. You can use this parameter to try to click on a + specific widget. However, if the widget is currently hidden or obscured by + another widget, the click may not land on the widget you specified. + offset: The offset to click. The offset is relative to the selector provided + or to the screen, if no selector is provided. shift: Click with the shift key held down. meta: Click with the meta key held down. control: Click with the control key held down. + + Raises: + OutOfBounds: If the position to be clicked is outside of the (visible) screen. + + Returns: + True if no selector was specified or if the click landed on the selected + widget, False otherwise. """ app = self.app screen = app.screen @@ -107,27 +123,51 @@ class Pilot(Generic[ReturnType]): message_arguments = _get_mouse_message_arguments( target_widget, offset, button=1, shift=shift, meta=meta, control=control ) + + click_offset = Offset(message_arguments["x"], message_arguments["y"]) + if click_offset not in screen.region: + raise OutOfBounds( + "Target offset is outside of currently-visible screen region." + ) + app.post_message(MouseDown(**message_arguments)) - await self.pause(0.1) + await self.pause() app.post_message(MouseUp(**message_arguments)) - await self.pause(0.1) + await self.pause() + + # Figure out the widget under the click before we click because the app + # might react to the click and move things. + widget_at, _ = app.get_widget_at(*click_offset) app.post_message(Click(**message_arguments)) - await self.pause(0.1) + await self.pause() + + return selector is None or widget_at is target_widget async def hover( self, selector: type[Widget] | str | None | None = None, offset: tuple[int, int] = (0, 0), - ) -> None: - """Simulate hovering with the mouse cursor. + ) -> bool: + """Simulate hovering with the mouse cursor at a specified position. + + The final position to be hovered is computed based on the selector provided and + the offset specified and it must be within the visible area of the screen. Args: - selector: The widget that should be hovered. If None, then the click - will occur relative to the screen. Note that this simply causes - a hover to occur at the location of the widget. If the widget is - currently hidden or obscured by another widget, then the hover may - not land on it. - offset: The offset to hover over within the selected widget. + selector: A selector to specify a widget that should be used as the reference + for the hover offset. If this is not specified, the offset is interpreted + relative to the screen. You can use this parameter to try to hover a + specific widget. However, if the widget is currently hidden or obscured by + another widget, the hover may not land on the widget you specified. + offset: The offset to hover. The offset is relative to the selector provided + or to the screen, if no selector is provided. + + Raises: + OutOfBounds: If the position to be hovered is outside of the (visible) screen. + + Returns: + True if no selector was specified or if the hover landed on the selected + widget, False otherwise. """ app = self.app screen = app.screen @@ -139,10 +179,20 @@ class Pilot(Generic[ReturnType]): message_arguments = _get_mouse_message_arguments( target_widget, offset, button=0 ) + + hover_offset = Offset(message_arguments["x"], message_arguments["y"]) + if hover_offset not in screen.region: + raise OutOfBounds( + "Target offset is outside of currently-visible screen region." + ) + await self.pause() app.post_message(MouseMove(**message_arguments)) await self.pause() + widget_at, _ = app.get_widget_at(*hover_offset) + return selector is None or widget_at is target_widget + async def _wait_for_screen(self, timeout: float = 30.0) -> bool: """Wait for the current screen and its children to have processed all pending events.
Textualize/textual
819880124242e88019e59668b6bb84ffe97f3694
diff --git a/tests/input/test_input_mouse.py b/tests/input/test_input_mouse.py index 491f18fda..a5249e549 100644 --- a/tests/input/test_input_mouse.py +++ b/tests/input/test_input_mouse.py @@ -34,7 +34,7 @@ class InputApp(App[None]): (TEXT_SINGLE, 10, 10), (TEXT_SINGLE, len(TEXT_SINGLE) - 1, len(TEXT_SINGLE) - 1), (TEXT_SINGLE, len(TEXT_SINGLE), len(TEXT_SINGLE)), - (TEXT_SINGLE, len(TEXT_SINGLE) * 2, len(TEXT_SINGLE)), + (TEXT_SINGLE, len(TEXT_SINGLE) + 10, len(TEXT_SINGLE)), # Double-width characters (TEXT_DOUBLE, 0, 0), (TEXT_DOUBLE, 1, 0), @@ -55,7 +55,7 @@ class InputApp(App[None]): (TEXT_MIXED, 13, 9), (TEXT_MIXED, 14, 9), (TEXT_MIXED, 15, 10), - (TEXT_MIXED, 1000, 10), + (TEXT_MIXED, 60, 10), ), ) async def test_mouse_clicks_within(text, click_at, should_land): diff --git a/tests/snapshot_tests/test_snapshots.py b/tests/snapshot_tests/test_snapshots.py index d60b94c58..a5b38bb23 100644 --- a/tests/snapshot_tests/test_snapshots.py +++ b/tests/snapshot_tests/test_snapshots.py @@ -644,6 +644,7 @@ def test_blur_on_disabled(snap_compare): def test_tooltips_in_compound_widgets(snap_compare): # https://github.com/Textualize/textual/issues/2641 async def run_before(pilot) -> None: + await pilot.pause() await pilot.hover("ProgressBar") await pilot.pause(0.3) await pilot.pause() diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 8c10c3846..ebb5ab367 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -815,7 +815,7 @@ async def test_hover_mouse_leave(): await pilot.hover(DataTable, offset=Offset(1, 1)) assert table._show_hover_cursor # Move our cursor away from the DataTable, and the hover cursor is hidden - await pilot.hover(DataTable, offset=Offset(-1, -1)) + await pilot.hover(DataTable, offset=Offset(20, 20)) assert not table._show_hover_cursor diff --git a/tests/test_pilot.py b/tests/test_pilot.py index 322146127..43789bb20 100644 --- a/tests/test_pilot.py +++ b/tests/test_pilot.py @@ -5,12 +5,43 @@ import pytest from textual import events from textual.app import App, ComposeResult from textual.binding import Binding -from textual.widgets import Label +from textual.containers import Center, Middle +from textual.pilot import OutOfBounds +from textual.widgets import Button, Label KEY_CHARACTERS_TO_TEST = "akTW03" + punctuation """Test some "simple" characters (letters + digits) and all punctuation.""" +class CenteredButtonApp(App): + CSS = """ # Ensure the button is 16 x 3 + Button { + min-width: 16; + max-width: 16; + width: 16; + min-height: 3; + max-height: 3; + height: 3; + } + """ + + def compose(self): + with Center(): + with Middle(): + yield Button() + + +class ManyLabelsApp(App): + """Auxiliary app with a button following many labels.""" + + AUTO_FOCUS = None # So that there's no auto-scrolling. + + def compose(self): + for idx in range(100): + yield Label(f"label {idx}", id=f"label{idx}") + yield Button() + + async def test_pilot_press_ascii_chars(): """Test that the pilot can press most ASCII characters as keys.""" keys_pressed = [] @@ -70,3 +101,179 @@ async def test_pilot_hover_screen(): async with App().run_test() as pilot: await pilot.hover("Screen") + + [email protected]( + ["method", "screen_size", "offset"], + [ + # + ("click", (80, 24), (100, 12)), # Right of screen. + ("click", (80, 24), (100, 36)), # Bottom-right of screen. + ("click", (80, 24), (50, 36)), # Under screen. + ("click", (80, 24), (-10, 36)), # Bottom-left of screen. + ("click", (80, 24), (-10, 12)), # Left of screen. + ("click", (80, 24), (-10, -2)), # Top-left of screen. + ("click", (80, 24), (50, -2)), # Above screen. + ("click", (80, 24), (100, -2)), # Top-right of screen. + # + ("click", (5, 5), (7, 3)), # Right of screen. + ("click", (5, 5), (7, 7)), # Bottom-right of screen. + ("click", (5, 5), (3, 7)), # Under screen. + ("click", (5, 5), (-1, 7)), # Bottom-left of screen. + ("click", (5, 5), (-1, 3)), # Left of screen. + ("click", (5, 5), (-1, -1)), # Top-left of screen. + ("click", (5, 5), (3, -1)), # Above screen. + ("click", (5, 5), (7, -1)), # Top-right of screen. + # + ("hover", (80, 24), (100, 12)), # Right of screen. + ("hover", (80, 24), (100, 36)), # Bottom-right of screen. + ("hover", (80, 24), (50, 36)), # Under screen. + ("hover", (80, 24), (-10, 36)), # Bottom-left of screen. + ("hover", (80, 24), (-10, 12)), # Left of screen. + ("hover", (80, 24), (-10, -2)), # Top-left of screen. + ("hover", (80, 24), (50, -2)), # Above screen. + ("hover", (80, 24), (100, -2)), # Top-right of screen. + # + ("hover", (5, 5), (7, 3)), # Right of screen. + ("hover", (5, 5), (7, 7)), # Bottom-right of screen. + ("hover", (5, 5), (3, 7)), # Under screen. + ("hover", (5, 5), (-1, 7)), # Bottom-left of screen. + ("hover", (5, 5), (-1, 3)), # Left of screen. + ("hover", (5, 5), (-1, -1)), # Top-left of screen. + ("hover", (5, 5), (3, -1)), # Above screen. + ("hover", (5, 5), (7, -1)), # Top-right of screen. + ], +) +async def test_pilot_target_outside_screen_errors(method, screen_size, offset): + """Make sure that targeting a click/hover completely outside of the screen errors.""" + app = App() + async with app.run_test(size=screen_size) as pilot: + pilot_method = getattr(pilot, method) + with pytest.raises(OutOfBounds): + await pilot_method(offset=offset) + + [email protected]( + ["method", "offset"], + [ + ("click", (0, 0)), # Top-left corner. + ("click", (40, 0)), # Top edge. + ("click", (79, 0)), # Top-right corner. + ("click", (79, 12)), # Right edge. + ("click", (79, 23)), # Bottom-right corner. + ("click", (40, 23)), # Bottom edge. + ("click", (40, 23)), # Bottom-left corner. + ("click", (0, 12)), # Left edge. + ("click", (40, 12)), # Right in the middle. + # + ("hover", (0, 0)), # Top-left corner. + ("hover", (40, 0)), # Top edge. + ("hover", (79, 0)), # Top-right corner. + ("hover", (79, 12)), # Right edge. + ("hover", (79, 23)), # Bottom-right corner. + ("hover", (40, 23)), # Bottom edge. + ("hover", (40, 23)), # Bottom-left corner. + ("hover", (0, 12)), # Left edge. + ("hover", (40, 12)), # Right in the middle. + ], +) +async def test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system( + method, offset +): + """Make sure that the coordinate system for the click is the correct one. + + Especially relevant because I kept getting confused about the way it works. + """ + app = ManyLabelsApp() + async with app.run_test(size=(80, 24)) as pilot: + app.query_one("#label99").scroll_visible(animate=False) + await pilot.pause() + + pilot_method = getattr(pilot, method) + await pilot_method(offset=offset) + + [email protected]( + ["method", "target"], + [ + ("click", "#label0"), + ("click", "#label90"), + ("click", Button), + # + ("hover", "#label0"), + ("hover", "#label90"), + ("hover", Button), + ], +) +async def test_pilot_target_on_widget_that_is_not_visible_errors(method, target): + """Make sure that clicking a widget that is not scrolled into view raises an error.""" + app = ManyLabelsApp() + async with app.run_test(size=(80, 5)) as pilot: + app.query_one("#label50").scroll_visible(animate=False) + await pilot.pause() + + pilot_method = getattr(pilot, method) + with pytest.raises(OutOfBounds): + await pilot_method(target) + + [email protected]("method", ["click", "hover"]) +async def test_pilot_target_widget_under_another_widget(method): + """The targeting method should return False when the targeted widget is covered.""" + + class ObscuredButton(App): + CSS = """ + Label { + width: 30; + height: 5; + } + """ + + def compose(self): + yield Button() + yield Label() + + def on_mount(self): + self.query_one(Label).styles.offset = (0, -3) + + app = ObscuredButton() + async with app.run_test() as pilot: + await pilot.pause() + pilot_method = getattr(pilot, method) + assert (await pilot_method(Button)) is False + + [email protected]("method", ["click", "hover"]) +async def test_pilot_target_visible_widget(method): + """The targeting method should return True when the targeted widget is hit.""" + + class ObscuredButton(App): + def compose(self): + yield Button() + + app = ObscuredButton() + async with app.run_test() as pilot: + await pilot.pause() + pilot_method = getattr(pilot, method) + assert (await pilot_method(Button)) is True + + [email protected]( + ["method", "offset"], + [ + ("click", (0, 0)), + ("click", (2, 0)), + ("click", (10, 23)), + ("click", (70, 0)), + # + ("hover", (0, 0)), + ("hover", (2, 0)), + ("hover", (10, 23)), + ("hover", (70, 0)), + ], +) +async def test_pilot_target_screen_always_true(method, offset): + app = ManyLabelsApp() + async with app.run_test(size=(80, 24)) as pilot: + pilot_method = getattr(pilot, method) + assert (await pilot_method(offset=offset)) is True
Restrict Pilot.click to visible area I suspect that `Pilot.click` will allow clicking of widgets that may not be in the visible area of the screen. Since we are simulating a real user operating the mouse, we should make that not work. Probably by throwing an exception. It also looks like it is possible to supply an `offset` that would click outside of the visible area. This should probably also result in an exception.
0.0
819880124242e88019e59668b6bb84ffe97f3694
[ "tests/input/test_input_mouse.py::test_mouse_clicks_within[That", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-0-0]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-1-0]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-2-1]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-3-1]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-4-2]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-5-2]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-9-4]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-10-5]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[\\u3053\\u3093\\u306b\\u3061\\u306f-50-5]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-0-0]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-1-1]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-2-1]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-3-2]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-4-2]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-5-3]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-13-9]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-14-9]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-15-10]", "tests/input/test_input_mouse.py::test_mouse_clicks_within[a\\u3053\\u3093bc\\u306bd\\u3061e\\u306f-60-10]", "tests/input/test_input_mouse.py::test_mouse_click_outwith", "tests/test_data_table.py::test_datatable_message_emission", "tests/test_data_table.py::test_empty_table_interactions", "tests/test_data_table.py::test_cursor_movement_with_home_pagedown_etc[True]", "tests/test_data_table.py::test_cursor_movement_with_home_pagedown_etc[False]", "tests/test_data_table.py::test_add_rows", "tests/test_data_table.py::test_add_rows_user_defined_keys", "tests/test_data_table.py::test_add_row_duplicate_key", "tests/test_data_table.py::test_add_column_duplicate_key", "tests/test_data_table.py::test_add_column_with_width", "tests/test_data_table.py::test_add_columns", "tests/test_data_table.py::test_add_columns_user_defined_keys", "tests/test_data_table.py::test_remove_row", "tests/test_data_table.py::test_remove_column", "tests/test_data_table.py::test_clear", "tests/test_data_table.py::test_column_labels", "tests/test_data_table.py::test_initial_column_widths", "tests/test_data_table.py::test_get_cell_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_invalid_row_key", "tests/test_data_table.py::test_get_cell_invalid_column_key", "tests/test_data_table.py::test_get_cell_coordinate_returns_coordinate", "tests/test_data_table.py::test_get_cell_coordinate_invalid_row_key", "tests/test_data_table.py::test_get_cell_coordinate_invalid_column_key", "tests/test_data_table.py::test_get_cell_at_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_at_exception", "tests/test_data_table.py::test_get_row", "tests/test_data_table.py::test_get_row_invalid_row_key", "tests/test_data_table.py::test_get_row_at", "tests/test_data_table.py::test_get_row_at_invalid_index[-1]", "tests/test_data_table.py::test_get_row_at_invalid_index[2]", "tests/test_data_table.py::test_get_row_index_returns_index", "tests/test_data_table.py::test_get_row_index_invalid_row_key", "tests/test_data_table.py::test_get_column", "tests/test_data_table.py::test_get_column_invalid_key", "tests/test_data_table.py::test_get_column_at", "tests/test_data_table.py::test_get_column_at_invalid_index[-1]", "tests/test_data_table.py::test_get_column_at_invalid_index[5]", "tests/test_data_table.py::test_get_column_index_returns_index", "tests/test_data_table.py::test_get_column_index_invalid_column_key", "tests/test_data_table.py::test_update_cell_cell_exists", "tests/test_data_table.py::test_update_cell_cell_doesnt_exist", "tests/test_data_table.py::test_update_cell_at_coordinate_exists", "tests/test_data_table.py::test_update_cell_at_coordinate_doesnt_exist", "tests/test_data_table.py::test_update_cell_at_column_width[A-BB-3]", "tests/test_data_table.py::test_update_cell_at_column_width[1234567-1234-7]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123-5]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123456789-9]", "tests/test_data_table.py::test_coordinate_to_cell_key", "tests/test_data_table.py::test_coordinate_to_cell_key_invalid_coordinate", "tests/test_data_table.py::test_datatable_click_cell_cursor", "tests/test_data_table.py::test_click_row_cursor", "tests/test_data_table.py::test_click_column_cursor", "tests/test_data_table.py::test_hover_coordinate", "tests/test_data_table.py::test_hover_mouse_leave", "tests/test_data_table.py::test_header_selected", "tests/test_data_table.py::test_row_label_selected", "tests/test_data_table.py::test_sort_coordinate_and_key_access", "tests/test_data_table.py::test_sort_reverse_coordinate_and_key_access", "tests/test_data_table.py::test_cell_cursor_highlight_events", "tests/test_data_table.py::test_row_cursor_highlight_events", "tests/test_data_table.py::test_column_cursor_highlight_events", "tests/test_data_table.py::test_reuse_row_key_after_clear", "tests/test_data_table.py::test_reuse_column_key_after_clear", "tests/test_data_table.py::test_key_equals_equivalent_string", "tests/test_data_table.py::test_key_doesnt_match_non_equal_string", "tests/test_data_table.py::test_key_equals_self", "tests/test_data_table.py::test_key_string_lookup", "tests/test_data_table.py::test_scrolling_cursor_into_view", "tests/test_data_table.py::test_move_cursor", "tests/test_data_table.py::test_unset_hover_highlight_when_no_table_cell_under_mouse", "tests/test_data_table.py::test_add_row_auto_height[hey", "tests/test_data_table.py::test_add_row_auto_height[cell1-1]", "tests/test_data_table.py::test_add_row_auto_height[cell2-2]", "tests/test_data_table.py::test_add_row_auto_height[cell3-4]", "tests/test_data_table.py::test_add_row_auto_height[1\\n2\\n3\\n4\\n5\\n6\\n7-7]", "tests/test_data_table.py::test_add_row_expands_column_widths", "tests/test_pilot.py::test_pilot_press_ascii_chars", "tests/test_pilot.py::test_pilot_exception_catching_compose", "tests/test_pilot.py::test_pilot_exception_catching_action", "tests/test_pilot.py::test_pilot_click_screen", "tests/test_pilot.py::test_pilot_hover_screen", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size0-offset0]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size1-offset1]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size2-offset2]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size3-offset3]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size4-offset4]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size5-offset5]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size6-offset6]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size7-offset7]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size8-offset8]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size9-offset9]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size10-offset10]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size11-offset11]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size12-offset12]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size13-offset13]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size14-offset14]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[click-screen_size15-offset15]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size16-offset16]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size17-offset17]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size18-offset18]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size19-offset19]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size20-offset20]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size21-offset21]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size22-offset22]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size23-offset23]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size24-offset24]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size25-offset25]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size26-offset26]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size27-offset27]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size28-offset28]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size29-offset29]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size30-offset30]", "tests/test_pilot.py::test_pilot_target_outside_screen_errors[hover-screen_size31-offset31]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset0]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset1]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset2]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset3]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset4]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset5]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset6]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset7]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[click-offset8]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset9]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset10]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset11]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset12]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset13]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset14]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset15]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset16]", "tests/test_pilot.py::test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system[hover-offset17]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[click-#label0]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[click-#label90]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[click-Button]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[hover-#label0]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[hover-#label90]", "tests/test_pilot.py::test_pilot_target_on_widget_that_is_not_visible_errors[hover-Button]", "tests/test_pilot.py::test_pilot_target_widget_under_another_widget[click]", "tests/test_pilot.py::test_pilot_target_widget_under_another_widget[hover]", "tests/test_pilot.py::test_pilot_target_visible_widget[click]", "tests/test_pilot.py::test_pilot_target_visible_widget[hover]", "tests/test_pilot.py::test_pilot_target_screen_always_true[click-offset0]", "tests/test_pilot.py::test_pilot_target_screen_always_true[click-offset1]", "tests/test_pilot.py::test_pilot_target_screen_always_true[click-offset2]", "tests/test_pilot.py::test_pilot_target_screen_always_true[click-offset3]", "tests/test_pilot.py::test_pilot_target_screen_always_true[hover-offset4]", "tests/test_pilot.py::test_pilot_target_screen_always_true[hover-offset5]", "tests/test_pilot.py::test_pilot_target_screen_always_true[hover-offset6]", "tests/test_pilot.py::test_pilot_target_screen_always_true[hover-offset7]" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-20 16:42:54+00:00
mit
769
Textualize__textual-3396
diff --git a/CHANGELOG.md b/CHANGELOG.md index 35a0624f8..c401104de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Unreleased + +### Fixed + +- `Pilot.click`/`Pilot.hover` can't use `Screen` as a selector https://github.com/Textualize/textual/issues/3395 + ## [0.38.1] - 2023-09-21 ### Fixed diff --git a/src/textual/pilot.py b/src/textual/pilot.py index c3c64d2e9..c15441d0b 100644 --- a/src/textual/pilot.py +++ b/src/textual/pilot.py @@ -100,7 +100,7 @@ class Pilot(Generic[ReturnType]): app = self.app screen = app.screen if selector is not None: - target_widget = screen.query_one(selector) + target_widget = app.query_one(selector) else: target_widget = screen @@ -132,7 +132,7 @@ class Pilot(Generic[ReturnType]): app = self.app screen = app.screen if selector is not None: - target_widget = screen.query_one(selector) + target_widget = app.query_one(selector) else: target_widget = screen
Textualize/textual
4d1f057968fcef413e1ec4d4f210440a9b46db8a
diff --git a/tests/test_pilot.py b/tests/test_pilot.py index d631146c7..322146127 100644 --- a/tests/test_pilot.py +++ b/tests/test_pilot.py @@ -52,3 +52,21 @@ async def test_pilot_exception_catching_action(): with pytest.raises(ZeroDivisionError): async with FailingApp().run_test() as pilot: await pilot.press("b") + + +async def test_pilot_click_screen(): + """Regression test for https://github.com/Textualize/textual/issues/3395. + + Check we can use `Screen` as a selector for a click.""" + + async with App().run_test() as pilot: + await pilot.click("Screen") + + +async def test_pilot_hover_screen(): + """Regression test for https://github.com/Textualize/textual/issues/3395. + + Check we can use `Screen` as a selector for a hover.""" + + async with App().run_test() as pilot: + await pilot.hover("Screen")
Pilot.click can't use `Screen` as selector. If you try something like `pilot.click(Screen)`, you get a `NoMatches` exception from the query.
0.0
4d1f057968fcef413e1ec4d4f210440a9b46db8a
[ "tests/test_pilot.py::test_pilot_click_screen", "tests/test_pilot.py::test_pilot_hover_screen" ]
[ "tests/test_pilot.py::test_pilot_press_ascii_chars", "tests/test_pilot.py::test_pilot_exception_catching_compose", "tests/test_pilot.py::test_pilot_exception_catching_action" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-09-25 09:56:48+00:00
mit
770
Textualize__textual-3409
diff --git a/CHANGELOG.md b/CHANGELOG.md index 330dac5bf..6fbc58b44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - `Pilot.click`/`Pilot.hover` can't use `Screen` as a selector https://github.com/Textualize/textual/issues/3395 +- App exception when a `Tree` is initialized/mounted with `disabled=True` https://github.com/Textualize/textual/issues/3407 ### Added diff --git a/src/textual/widgets/_tree.py b/src/textual/widgets/_tree.py index b094f7568..c413d7910 100644 --- a/src/textual/widgets/_tree.py +++ b/src/textual/widgets/_tree.py @@ -597,8 +597,6 @@ class Tree(Generic[TreeDataType], ScrollView, can_focus=True): disabled: Whether the tree is disabled or not. """ - super().__init__(name=name, id=id, classes=classes, disabled=disabled) - text_label = self.process_label(label) self._updates = 0 @@ -610,6 +608,8 @@ class Tree(Generic[TreeDataType], ScrollView, can_focus=True): self._tree_lines_cached: list[_TreeLine] | None = None self._cursor_node: TreeNode[TreeDataType] | None = None + super().__init__(name=name, id=id, classes=classes, disabled=disabled) + @property def cursor_node(self) -> TreeNode[TreeDataType] | None: """The currently selected node, or ``None`` if no selection."""
Textualize/textual
d766bb95666e24e52b19e9e475e4f0931f1154d0
diff --git a/tests/tree/test_tree_availability.py b/tests/tree/test_tree_availability.py new file mode 100644 index 000000000..c3f509446 --- /dev/null +++ b/tests/tree/test_tree_availability.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +from typing import Any + +from textual import on +from textual.app import App, ComposeResult +from textual.widgets import Tree + + +class TreeApp(App[None]): + """Test tree app.""" + + def __init__(self, disabled: bool, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.disabled = disabled + self.messages: list[tuple[str, str]] = [] + + def compose(self) -> ComposeResult: + """Compose the child widgets.""" + yield Tree("Root", disabled=self.disabled, id="test-tree") + + def on_mount(self) -> None: + self.query_one(Tree).root.add("Child") + self.query_one(Tree).focus() + + def record( + self, + event: Tree.NodeSelected[None] + | Tree.NodeExpanded[None] + | Tree.NodeCollapsed[None] + | Tree.NodeHighlighted[None], + ) -> None: + self.messages.append( + (event.__class__.__name__, event.node.tree.id or "Unknown") + ) + + @on(Tree.NodeSelected) + def node_selected(self, event: Tree.NodeSelected[None]) -> None: + self.record(event) + + @on(Tree.NodeExpanded) + def node_expanded(self, event: Tree.NodeExpanded[None]) -> None: + self.record(event) + + @on(Tree.NodeCollapsed) + def node_collapsed(self, event: Tree.NodeCollapsed[None]) -> None: + self.record(event) + + @on(Tree.NodeHighlighted) + def node_highlighted(self, event: Tree.NodeHighlighted[None]) -> None: + self.record(event) + + +async def test_creating_disabled_tree(): + """Mounting a disabled `Tree` should result in the base `Widget` + having a `disabled` property equal to `True`""" + app = TreeApp(disabled=True) + async with app.run_test() as pilot: + tree = app.query_one(Tree) + assert not tree.focusable + assert tree.disabled + assert tree.cursor_line == 0 + await pilot.click("#test-tree") + await pilot.pause() + await pilot.press("down") + await pilot.pause() + assert tree.cursor_line == 0 + + +async def test_creating_enabled_tree(): + """Mounting an enabled `Tree` should result in the base `Widget` + having a `disabled` property equal to `False`""" + app = TreeApp(disabled=False) + async with app.run_test() as pilot: + tree = app.query_one(Tree) + assert tree.focusable + assert not tree.disabled + assert tree.cursor_line == 0 + await pilot.click("#test-tree") + await pilot.pause() + await pilot.press("down") + await pilot.pause() + assert tree.cursor_line == 1 + + +async def test_disabled_tree_node_selected_message() -> None: + """Clicking the root node disclosure triangle on a disabled tree + should result in no messages being emitted.""" + app = TreeApp(disabled=True) + async with app.run_test() as pilot: + tree = app.query_one(Tree) + # try clicking on a disabled tree + await pilot.click("#test-tree") + await pilot.pause() + assert not pilot.app.messages + # make sure messages DO flow after enabling a disabled tree + tree.disabled = False + await pilot.click("#test-tree") + await pilot.pause() + assert pilot.app.messages == [("NodeExpanded", "test-tree")] + + +async def test_enabled_tree_node_selected_message() -> None: + """Clicking the root node disclosure triangle on an enabled tree + should result in an `NodeExpanded` message being emitted.""" + app = TreeApp(disabled=False) + async with app.run_test() as pilot: + tree = app.query_one(Tree) + # try clicking on an enabled tree + await pilot.click("#test-tree") + await pilot.pause() + assert pilot.app.messages == [("NodeExpanded", "test-tree")] + tree.disabled = True + # make sure messages DO NOT flow after disabling an enabled tree + app.messages = [] + await pilot.click("#test-tree") + await pilot.pause() + assert not pilot.app.messages
Tree `disabled=True` breaks when setting at initialization Using the `Tree` example from the docs, if you pass in `disabled=True` during initialization the app break with 2 exceptions. **Thrown Exceptions:** 1. `AttributeError: 'Tree' object has no attribute '_line_cache'` 2. `ScreenStackError: No screens on stack` I can see in the source that the call to `super().__init__()` on the base `Widget` object is called before setting the `_line_cache` so I'm not sure if that is the problem or not. ```python from textual.app import App, ComposeResult from textual.widgets import Tree class TreeApp(App): def compose(self) -> ComposeResult: tree: Tree[dict] = Tree("Dune", disabled=True) tree.root.expand() characters = tree.root.add("Characters", expand=True) characters.add_leaf("Paul") characters.add_leaf("Jessica") characters.add_leaf("Chani") yield tree if __name__ == "__main__": app = TreeApp() app.run() ``` Enabling and disabling the Tree after the app is composed works just fine as can be seen using this example (using the 'D' keybinding). ```python from textual.app import App, ComposeResult from textual.widgets import Footer, Header, Tree class TreeApp(App): BINDINGS = [ ("d", "disable_tree", "Toggle Tree Availability"), ] def compose(self) -> ComposeResult: tree: Tree[dict] = Tree("Dune") tree.root.expand() characters = tree.root.add("Characters", expand=True) characters.add_leaf("Paul") characters.add_leaf("Jessica") characters.add_leaf("Chani") yield Header() yield Footer() yield tree def action_disable_tree(self) -> None: tree = self.query_one(Tree) tree.disabled = not tree.disabled if __name__ == "__main__": app = TreeApp() app.run() ```
0.0
d766bb95666e24e52b19e9e475e4f0931f1154d0
[ "tests/tree/test_tree_availability.py::test_creating_disabled_tree", "tests/tree/test_tree_availability.py::test_disabled_tree_node_selected_message" ]
[ "tests/tree/test_tree_availability.py::test_creating_enabled_tree", "tests/tree/test_tree_availability.py::test_enabled_tree_node_selected_message" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-09-27 02:55:55+00:00
mit
771
Textualize__textual-3659
diff --git a/CHANGELOG.md b/CHANGELOG.md index c2589f911..496739944 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed outline not rendering correctly in some scenarios (e.g. on Button widgets) https://github.com/Textualize/textual/issues/3628 - Fixed live-reloading of screen CSS https://github.com/Textualize/textual/issues/3454 - `Select.value` could be in an invalid state https://github.com/Textualize/textual/issues/3612 +- Off-by-one in CSS error reporting https://github.com/Textualize/textual/issues/3625 ### Added diff --git a/src/textual/css/tokenizer.py b/src/textual/css/tokenizer.py index d7cfc449d..875537eb7 100644 --- a/src/textual/css/tokenizer.py +++ b/src/textual/css/tokenizer.py @@ -34,9 +34,9 @@ class TokenError(Exception): Args: read_from: The location where the CSS was read from. code: The code being parsed. - start: Line number of the error. + start: Line and column number of the error (1-indexed). message: A message associated with the error. - end: End location of token, or None if not known. + end: End location of token (1-indexed), or None if not known. """ self.read_from = read_from @@ -60,9 +60,13 @@ class TokenError(Exception): line_numbers=True, indent_guides=True, line_range=(max(0, line_no - 2), line_no + 2), - highlight_lines={line_no + 1}, + highlight_lines={line_no}, + ) + syntax.stylize_range( + "reverse bold", + (self.start[0], self.start[1] - 1), + (self.end[0], self.end[1] - 1), ) - syntax.stylize_range("reverse bold", self.start, self.end) return Panel(syntax, border_style="red") def __rich__(self) -> RenderableType: @@ -136,19 +140,20 @@ class Token(NamedTuple): read_from: CSSLocation code: str location: tuple[int, int] + """Token starting location, 0-indexed.""" referenced_by: ReferencedBy | None = None @property def start(self) -> tuple[int, int]: - """Start line and column (1 indexed).""" + """Start line and column (1-indexed).""" line, offset = self.location - return (line + 1, offset) + return (line + 1, offset + 1) @property def end(self) -> tuple[int, int]: - """End line and column (1 indexed).""" + """End line and column (1-indexed).""" line, offset = self.location - return (line + 1, offset + len(self.value)) + return (line + 1, offset + len(self.value) + 1) def with_reference(self, by: ReferencedBy | None) -> "Token": """Return a copy of the Token, with reference information attached. @@ -199,7 +204,7 @@ class Tokenizer: "", self.read_from, self.code, - (line_no + 1, col_no + 1), + (line_no, col_no), None, ) else: @@ -217,7 +222,7 @@ class Tokenizer: raise TokenError( self.read_from, self.code, - (line_no, col_no), + (line_no + 1, col_no + 1), message, ) iter_groups = iter(match.groups()) @@ -251,14 +256,14 @@ class Tokenizer: raise TokenError( self.read_from, self.code, - (line_no, col_no), + (line_no + 1, col_no + 1), f"unknown pseudo-class {pseudo_class!r}; did you mean {suggestion!r}?; {all_valid}", ) else: raise TokenError( self.read_from, self.code, - (line_no, col_no), + (line_no + 1, col_no + 1), f"unknown pseudo-class {pseudo_class!r}; {all_valid}", )
Textualize/textual
7a25bb19980ba14c4a49e5e70d5fafc21caecd70
diff --git a/tests/css/test_parse.py b/tests/css/test_parse.py index 124f820d5..febe4f06b 100644 --- a/tests/css/test_parse.py +++ b/tests/css/test_parse.py @@ -1238,7 +1238,7 @@ class TestTypeNames: stylesheet.parse() -def test_parse_bad_psuedo_selector(): +def test_parse_bad_pseudo_selector(): """Check unknown selector raises a token error.""" bad_selector = """\ @@ -1248,9 +1248,27 @@ Widget:foo{ """ stylesheet = Stylesheet() - stylesheet.add_source(bad_selector, "foo") + stylesheet.add_source(bad_selector, None) with pytest.raises(TokenError) as error: stylesheet.parse() - assert error.value.start == (0, 6) + assert error.value.start == (1, 7) + + +def test_parse_bad_pseudo_selector_with_suggestion(): + """Check unknown pseudo selector raises token error with correct position.""" + + bad_selector = """ +Widget:blu { + border: red; +} +""" + + stylesheet = Stylesheet() + stylesheet.add_source(bad_selector, None) + + with pytest.raises(TokenError) as error: + stylesheet.parse() + + assert error.value.start == (2, 7)
CSS error reporting sometimes off by one See https://github.com/Textualize/textual/pull/3582#issuecomment-1787507687. Running the app at the bottom produces the error below, where the error reporting is off by one. See the line above the panel and the code lines in the code snippet printed. ``` Error in stylesheet: /Users/davep/develop/python/textual-upstream/sandbox/foo.py, CSSErrorApp.CSS:1:4 ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ 1 │ │ │ ❱ 2 │ : │ │ 3 │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ • Expected one of 'comment line', 'comment start', 'selector start', 'selector start class', 'selector start id', 'selector start universal', 'variable name', or 'whitespace'. • Did you forget a semicolon at the end of a line? ``` ```py from textual.app import App, ComposeResult from textual.widgets import Label class CSSErrorApp(App[None]): CSS = """ : """ def compose(self) -> ComposeResult: yield Label() if __name__ == "__main__": CSSErrorApp().run() ```
0.0
7a25bb19980ba14c4a49e5e70d5fafc21caecd70
[ "tests/css/test_parse.py::test_parse_bad_pseudo_selector", "tests/css/test_parse.py::test_parse_bad_pseudo_selector_with_suggestion" ]
[ "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_simple_reference", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_simple_reference_no_whitespace", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_undefined_variable", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_empty_variable", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_transitive_reference", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_multi_value_variable", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_used_inside_property_value", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_definition_eof", "tests/css/test_parse.py::TestVariableReferenceSubstitution::test_variable_reference_whitespace_trimming", "tests/css/test_parse.py::TestParseLayout::test_valid_layout_name", "tests/css/test_parse.py::TestParseLayout::test_invalid_layout_name", "tests/css/test_parse.py::TestParseText::test_foreground", "tests/css/test_parse.py::TestParseText::test_background", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgb(1,255,50)-result0]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgb(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[rgba(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsl(", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsl(180,50%,50%)-result5]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsla(180,50%,50%,0.25)-result6]", "tests/css/test_parse.py::TestParseColor::test_rgb_and_hsl[hsla(", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[-5.5%-parsed_x0--30%-parsed_y0]", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[5%-parsed_x1-40%-parsed_y1]", "tests/css/test_parse.py::TestParseOffset::test_composite_rule[10-parsed_x2-40-parsed_y2]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[-5.5%-parsed_x0--30%-parsed_y0]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[5%-parsed_x1-40%-parsed_y1]", "tests/css/test_parse.py::TestParseOffset::test_separate_rules[-10-parsed_x2-40-parsed_y2]", "tests/css/test_parse.py::TestParseOverflow::test_multiple_enum", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[5.57s-5.57]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.5s-0.5]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[1200ms-1.2]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.5ms-0.0005]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[20-20.0]", "tests/css/test_parse.py::TestParseTransition::test_various_duration_formats[0.1-0.1]", "tests/css/test_parse.py::TestParseTransition::test_no_delay_specified", "tests/css/test_parse.py::TestParseTransition::test_unknown_easing_function", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[-0.2-0.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[0.4-0.4]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[1.3-1.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[-20%-0.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[25%-0.25]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_to_styles[128%-1.0]", "tests/css/test_parse.py::TestParseOpacity::test_opacity_invalid_value", "tests/css/test_parse.py::TestParseMargin::test_margin_partial", "tests/css/test_parse.py::TestParsePadding::test_padding_partial", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[left]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[start]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[center]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[right]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[end]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align[justify]", "tests/css/test_parse.py::TestParseTextAlign::test_text_align_invalid", "tests/css/test_parse.py::TestTypeNames::test_type_no_number", "tests/css/test_parse.py::TestTypeNames::test_type_with_number", "tests/css/test_parse.py::TestTypeNames::test_type_starts_with_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_no_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_with_number", "tests/css/test_parse.py::TestTypeNames::test_combined_type_starts_with_number" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-09 17:49:08+00:00
mit
772
Textualize__textual-3863
diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 882da2b35..02e367aa4 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -17,7 +17,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] - python-version: ["3.8", "3.9", "3.10", "3.11"] + python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] defaults: run: shell: bash @@ -32,9 +32,18 @@ jobs: cache: 'poetry' - name: Install dependencies run: poetry install --no-interaction --extras syntax + if: ${{ matrix.python-version != '3.12' }} + - name: Install dependencies for 3.12 # https://github.com/Textualize/textual/issues/3491#issuecomment-1854156476 + run: poetry install --no-interaction + if: ${{ matrix.python-version == '3.12' }} - name: Test with pytest run: | poetry run pytest tests -v --cov=./src/textual --cov-report=xml:./coverage.xml --cov-report term-missing + if: ${{ matrix.python-version != '3.12' }} + - name: Test with pytest for 3.12 # https://github.com/Textualize/textual/issues/3491#issuecomment-1854156476 + run: | + poetry run pytest tests -v --cov=./src/textual --cov-report=xml:./coverage.xml --cov-report term-missing -m 'not syntax' + if: ${{ matrix.python-version == '3.12' }} - name: Upload snapshot report if: always() uses: actions/upload-artifact@v3 diff --git a/docs/getting_started.md b/docs/getting_started.md index 0e031a266..46addc0bc 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -2,7 +2,7 @@ All you need to get started building Textual apps. ## Requirements -Textual requires Python 3.7 or later (if you have a choice, pick the most recent Python). Textual runs on Linux, macOS, Windows and probably any OS where Python also runs. +Textual requires Python 3.8 or later (if you have a choice, pick the most recent Python). Textual runs on Linux, macOS, Windows and probably any OS where Python also runs. !!! info inline end "Your platform" diff --git a/docs/widgets/text_area.md b/docs/widgets/text_area.md index a8c648d64..bc3a5e25a 100644 --- a/docs/widgets/text_area.md +++ b/docs/widgets/text_area.md @@ -56,9 +56,6 @@ To update the parser used for syntax highlighting, set the [`language`][textual. text_area.language = "markdown" ``` -!!! note - Syntax highlighting is unavailable on Python 3.7. - !!! note More built-in languages will be added in the future. For now, you can [add your own](#adding-support-for-custom-languages). @@ -391,10 +388,6 @@ from tree_sitter_languages import get_language java_language = get_language("java") ``` -!!! note - - `py-tree-sitter-languages` may not be available on some architectures (e.g. Macbooks with Apple Silicon running Python 3.7). - The exact version of the parser used when you call `get_language` can be checked via the [`repos.txt` file](https://github.com/grantjenks/py-tree-sitter-languages/blob/a6d4f7c903bf647be1bdcfa504df967d13e40427/repos.txt) in the version of `py-tree-sitter-languages` you're using. This file contains links to the GitHub diff --git a/examples/merlin.py b/examples/merlin.py new file mode 100644 index 000000000..0a0287a4e --- /dev/null +++ b/examples/merlin.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import random +from datetime import timedelta +from time import monotonic + +from textual import events +from textual.app import App, ComposeResult +from textual.containers import Grid +from textual.reactive import var +from textual.renderables.gradient import LinearGradient +from textual.widget import Widget +from textual.widgets import Digits, Label, Switch + +# A nice rainbow of colors. +COLORS = [ + "#881177", + "#aa3355", + "#cc6666", + "#ee9944", + "#eedd00", + "#99dd55", + "#44dd88", + "#22ccbb", + "#00bbcc", + "#0099cc", + "#3366bb", + "#663399", +] + + +# Maps a switch number on to other switch numbers, which should be toggled. +TOGGLES: dict[int, tuple[int, ...]] = { + 1: (2, 4, 5), + 2: (1, 3), + 3: (2, 5, 6), + 4: (1, 7), + 5: (2, 4, 6, 8), + 6: (3, 9), + 7: (4, 5, 8), + 8: (7, 9), + 9: (5, 6, 8), +} + + +class LabelSwitch(Widget): + """Switch with a numeric label.""" + + DEFAULT_CSS = """ + LabelSwitch Label { + text-align: center; + width: 1fr; + text-style: bold; + } + + LabelSwitch Label#label-5 { + color: $text-disabled; + } + """ + + def __init__(self, switch_no: int) -> None: + self.switch_no = switch_no + super().__init__() + + def compose(self) -> ComposeResult: + """Compose the label and a switch.""" + yield Label(str(self.switch_no), id=f"label-{self.switch_no}") + yield Switch(id=f"switch-{self.switch_no}", name=str(self.switch_no)) + + +class Timer(Digits): + """Displays a timer that stops when you win.""" + + DEFAULT_CSS = """ + Timer { + text-align: center; + width: auto; + margin: 2 8; + color: $warning; + } + """ + start_time = var(0.0) + running = var(True) + + def on_mount(self) -> None: + """Start the timer on mount.""" + self.start_time = monotonic() + self.set_interval(1, self.tick) + self.tick() + + def tick(self) -> None: + """Called from `set_interval` to update the clock.""" + if self.start_time == 0 or not self.running: + return + time_elapsed = timedelta(seconds=int(monotonic() - self.start_time)) + self.update(str(time_elapsed)) + + +class MerlinApp(App): + """A simple reproduction of one game on the Merlin hand held console.""" + + CSS = """ + Screen { + align: center middle; + } + + Screen.-win { + background: transparent; + } + + Screen.-win Timer { + color: $success; + } + + Grid { + width: auto; + height: auto; + border: thick $primary; + padding: 1 2; + grid-size: 3 3; + grid-rows: auto; + grid-columns: auto; + grid-gutter: 1 1; + background: $surface; + } + """ + + def render(self) -> LinearGradient: + """Renders a gradient, when the background is transparent.""" + stops = [(i / (len(COLORS) - 1), c) for i, c in enumerate(COLORS)] + return LinearGradient(30.0, stops) + + def compose(self) -> ComposeResult: + """Compose a timer, and a grid of 9 switches.""" + yield Timer() + with Grid(): + for switch in (7, 8, 9, 4, 5, 6, 1, 2, 3): + yield LabelSwitch(switch) + + def on_mount(self) -> None: + """Randomize the switches on mount.""" + for switch_no in range(1, 10): + if random.randint(0, 1): + self.query_one(f"#switch-{switch_no}", Switch).toggle() + + def check_win(self) -> bool: + """Check for a win.""" + on_switches = { + int(switch.name or "0") for switch in self.query(Switch) if switch.value + } + return on_switches == {1, 2, 3, 4, 6, 7, 8, 9} + + def on_switch_changed(self, event: Switch.Changed) -> None: + """Called when a switch is toggled.""" + # The switch that was pressed + switch_no = int(event.switch.name or "0") + # Also toggle corresponding switches + with self.prevent(Switch.Changed): + for toggle_no in TOGGLES[switch_no]: + self.query_one(f"#switch-{toggle_no}", Switch).toggle() + # Check the win + if self.check_win(): + self.query_one("Screen").add_class("-win") + self.query_one(Timer).running = False + + def on_key(self, event: events.Key) -> None: + """Maps switches to keys, so we can use the keyboard as well.""" + if event.character and event.character.isdigit(): + self.query_one(f"#switch-{event.character}", Switch).toggle() + + +if __name__ == "__main__": + MerlinApp().run() diff --git a/pyproject.toml b/pyproject.toml index 581772683..a3469a5d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,6 +83,7 @@ testpaths = ["tests"] addopts = "--strict-markers" markers = [ "integration_test: marks tests as slow integration tests (deselect with '-m \"not integration_test\"')", + "syntax: marks tests that require syntax highlighting (deselect with '-m \"not syntax\"')", ] [build-system]
Textualize/textual
a85edb77f4cd7fd23b618e24119495c1de812963
diff --git a/tests/snapshot_tests/test_snapshots.py b/tests/snapshot_tests/test_snapshots.py index be8a4b4e8..66cbe6a53 100644 --- a/tests/snapshot_tests/test_snapshots.py +++ b/tests/snapshot_tests/test_snapshots.py @@ -795,6 +795,7 @@ def test_nested_fr(snap_compare) -> None: assert snap_compare(SNAPSHOT_APPS_DIR / "nested_fr.py") [email protected] @pytest.mark.parametrize("language", BUILTIN_LANGUAGES) def test_text_area_language_rendering(language, snap_compare): # This test will fail if we're missing a snapshot test for a valid @@ -846,6 +847,7 @@ I am the final line.""" ) [email protected] @pytest.mark.parametrize( "theme_name", [theme.name for theme in TextAreaTheme.builtin_themes()] ) diff --git a/tests/text_area/test_languages.py b/tests/text_area/test_languages.py index 6124da0cb..7e33fcf72 100644 --- a/tests/text_area/test_languages.py +++ b/tests/text_area/test_languages.py @@ -1,5 +1,3 @@ -import sys - import pytest from textual.app import App, ComposeResult @@ -61,7 +59,7 @@ async def test_setting_unknown_language(): text_area.language = "this-language-doesnt-exist" [email protected](sys.version_info < (3, 8), reason="tree-sitter requires python3.8 or higher") [email protected] async def test_register_language(): app = TextAreaApp() @@ -84,7 +82,7 @@ async def test_register_language(): assert text_area.language == "elm" [email protected](sys.version_info < (3, 8), reason="tree-sitter requires python3.8 or higher") [email protected] async def test_register_language_existing_language(): app = TextAreaApp() async with app.run_test():
Update dependancies to support Python 3.12 With Python 3.12: ```console pip install textual ``` Fails with: ``` ERROR: Could not find a version that satisfies the requirement tree_sitter_languages>=1.7.0; python_version >= "3.8" and python_version < "4.0" (from textual) (from versions: none) ERROR: No matching distribution found for tree_sitter_languages>=1.7.0; python_version >= "3.8" and python_version < "4.0" ```
0.0
a85edb77f4cd7fd23b618e24119495c1de812963
[ "tests/text_area/test_languages.py::test_setting_builtin_language_via_constructor", "tests/text_area/test_languages.py::test_setting_builtin_language_via_attribute", "tests/text_area/test_languages.py::test_setting_language_to_none", "tests/text_area/test_languages.py::test_setting_unknown_language" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-13 14:10:51+00:00
mit
773
Textualize__textual-3965
diff --git a/CHANGELOG.md b/CHANGELOG.md index e901d67b4..50dc3f19e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Unreleased + +### Fixed + +- Parameter `animate` from `DataTable.move_cursor` was being ignored https://github.com/Textualize/textual/issues/3840 + ## [0.47.1] - 2023-01-05 ### Fixed diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index eef090bfb..e2a5a0022 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -1094,7 +1094,7 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): self._highlight_column(new_coordinate.column) # If the coordinate was changed via `move_cursor`, give priority to its # scrolling because it may be animated. - self.call_next(self._scroll_cursor_into_view) + self.call_after_refresh(self._scroll_cursor_into_view) def move_cursor( self, @@ -1119,20 +1119,24 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): column: The new column to move the cursor to. animate: Whether to animate the change of coordinates. """ + cursor_row, cursor_column = self.cursor_coordinate if row is not None: cursor_row = row if column is not None: cursor_column = column destination = Coordinate(cursor_row, cursor_column) - self.cursor_coordinate = destination # Scroll the cursor after refresh to ensure the virtual height # (calculated in on_idle) has settled. If we tried to scroll before # the virtual size has been set, then it might fail if we added a bunch # of rows then tried to immediately move the cursor. + # We do this before setting `cursor_coordinate` because its watcher will also + # schedule a call to `_scroll_cursor_into_view` without optionally animating. self.call_after_refresh(self._scroll_cursor_into_view, animate=animate) + self.cursor_coordinate = destination + def _highlight_coordinate(self, coordinate: Coordinate) -> None: """Apply highlighting to the cell at the coordinate, and post event.""" self.refresh_coordinate(coordinate)
Textualize/textual
cf46d4e70f29cd7e8b7263954e9c7f1d431368eb
diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 70b6ffe47..e09a9c3f9 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -1382,3 +1382,41 @@ async def test_cell_padding_cannot_be_negative(): assert table.cell_padding == 0 table.cell_padding = -1234 assert table.cell_padding == 0 + + +async def test_move_cursor_respects_animate_parameter(): + """Regression test for https://github.com/Textualize/textual/issues/3840 + + Make sure that the call to `_scroll_cursor_into_view` from `move_cursor` happens + before the call from the watcher method from `cursor_coordinate`. + The former should animate because we call it with `animate=True` whereas the later + should not. + """ + + scrolls = [] + + class _DataTable(DataTable): + def _scroll_cursor_into_view(self, animate=False): + nonlocal scrolls + scrolls.append(animate) + super()._scroll_cursor_into_view(animate) + + class LongDataTableApp(App): + def compose(self): + yield _DataTable() + + def on_mount(self): + dt = self.query_one(_DataTable) + dt.add_columns("one", "two") + for _ in range(100): + dt.add_row("one", "two") + + def key_s(self): + table = self.query_one(_DataTable) + table.move_cursor(row=99, animate=True) + + app = LongDataTableApp() + async with app.run_test() as pilot: + await pilot.press("s") + + assert scrolls == [True, False]
DataTable move_cursor animate doesn't do anything? While working on: - https://github.com/Textualize/textual/discussions/3606 I wanted to check `animate` for `move_cursor` behaves correctly, but it doesn't seem to do anything? --- Repro: ```py from random import randint from textual.app import App, ComposeResult from textual.widgets import DataTable, Button from textual.widgets._data_table import RowKey from textual.containers import Horizontal from textual import on from textual.reactive import Reactive, reactive ROWS = [ ("lane", "swimmer", "country", "time"), (4, "Joseph Schooling", "Singapore", 50.39), (2, "Michael Phelps", "United States", 51.14), (5, "Chad le Clos", "South Africa", 51.14), (6, "László Cseh", "Hungary", 51.14), (3, "Li Zhuhao", "China", 51.26), (8, "Mehdy Metella", "France", 51.58), (7, "Tom Shields", "United States", 51.73), (1, "Aleksandr Sadovnikov", "Russia", 51.84), (10, "Darren Burns", "Scotland", 51.84), ] class TableApp(App): CSS = """ DataTable { height: 80%; } """ keys: Reactive[RowKey] = reactive([]) def compose(self) -> ComposeResult: yield DataTable(cursor_type="row") with Horizontal(): yield Button("True") yield Button("False") @on(Button.Pressed) def goto(self, event: Button.Pressed): row = randint(0, len(self.keys) - 1) print(row) animate = str(event.button.label) == "True" table = self.query_one(DataTable) table.move_cursor(row=row, animate=animate) def on_mount(self) -> None: table = self.query_one(DataTable) table.add_columns(*ROWS[0]) for _ in range(20): keys = table.add_rows(ROWS[1:]) self.keys.extend(keys) app = TableApp() if __name__ == "__main__": app.run() ``` --- <!-- This is valid Markdown, do not quote! --> # Textual Diagnostics ## Versions | Name | Value | |---------|--------| | Textual | 0.39.0 | | Rich | 13.3.3 | ## Python | Name | Value | |----------------|---------------------------------------------------| | Version | 3.11.4 | | Implementation | CPython | | Compiler | Clang 14.0.0 (clang-1400.0.29.202) | | Executable | /Users/dave/.pyenv/versions/3.11.4/bin/python3.11 | ## Operating System | Name | Value | |---------|---------------------------------------------------------------------------------------------------------| | System | Darwin | | Release | 21.6.0 | | Version | Darwin Kernel Version 21.6.0: Thu Mar 9 20:08:59 PST 2023; root:xnu-8020.240.18.700.8~1/RELEASE_X86_64 | ## Terminal | Name | Value | |----------------------|-----------------| | Terminal Application | vscode (1.85.0) | | TERM | xterm-256color | | COLORTERM | truecolor | | FORCE_COLOR | *Not set* | | NO_COLOR | *Not set* | ## Rich Console options | Name | Value | |----------------|---------------------| | size | width=90, height=68 | | legacy_windows | False | | min_width | 1 | | max_width | 90 | | is_terminal | True | | encoding | utf-8 | | max_height | 68 | | justify | None | | overflow | None | | no_wrap | False | | highlight | None | | markup | None | | height | None |
0.0
cf46d4e70f29cd7e8b7263954e9c7f1d431368eb
[ "tests/test_data_table.py::test_move_cursor_respects_animate_parameter" ]
[ "tests/test_data_table.py::test_datatable_message_emission", "tests/test_data_table.py::test_empty_table_interactions", "tests/test_data_table.py::test_cursor_movement_with_home_pagedown_etc[True]", "tests/test_data_table.py::test_cursor_movement_with_home_pagedown_etc[False]", "tests/test_data_table.py::test_add_rows", "tests/test_data_table.py::test_add_rows_user_defined_keys", "tests/test_data_table.py::test_add_row_duplicate_key", "tests/test_data_table.py::test_add_column_duplicate_key", "tests/test_data_table.py::test_add_column_with_width", "tests/test_data_table.py::test_add_columns", "tests/test_data_table.py::test_add_columns_user_defined_keys", "tests/test_data_table.py::test_remove_row", "tests/test_data_table.py::test_remove_row_and_update", "tests/test_data_table.py::test_remove_column", "tests/test_data_table.py::test_remove_column_and_update", "tests/test_data_table.py::test_clear", "tests/test_data_table.py::test_column_labels", "tests/test_data_table.py::test_initial_column_widths", "tests/test_data_table.py::test_get_cell_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_invalid_row_key", "tests/test_data_table.py::test_get_cell_invalid_column_key", "tests/test_data_table.py::test_get_cell_coordinate_returns_coordinate", "tests/test_data_table.py::test_get_cell_coordinate_invalid_row_key", "tests/test_data_table.py::test_get_cell_coordinate_invalid_column_key", "tests/test_data_table.py::test_get_cell_at_returns_value_at_cell", "tests/test_data_table.py::test_get_cell_at_exception", "tests/test_data_table.py::test_get_row", "tests/test_data_table.py::test_get_row_invalid_row_key", "tests/test_data_table.py::test_get_row_at", "tests/test_data_table.py::test_get_row_at_invalid_index[-1]", "tests/test_data_table.py::test_get_row_at_invalid_index[2]", "tests/test_data_table.py::test_get_row_index_returns_index", "tests/test_data_table.py::test_get_row_index_invalid_row_key", "tests/test_data_table.py::test_get_column", "tests/test_data_table.py::test_get_column_invalid_key", "tests/test_data_table.py::test_get_column_at", "tests/test_data_table.py::test_get_column_at_invalid_index[-1]", "tests/test_data_table.py::test_get_column_at_invalid_index[5]", "tests/test_data_table.py::test_get_column_index_returns_index", "tests/test_data_table.py::test_get_column_index_invalid_column_key", "tests/test_data_table.py::test_update_cell_cell_exists", "tests/test_data_table.py::test_update_cell_cell_doesnt_exist", "tests/test_data_table.py::test_update_cell_invalid_column_key", "tests/test_data_table.py::test_update_cell_at_coordinate_exists", "tests/test_data_table.py::test_update_cell_at_coordinate_doesnt_exist", "tests/test_data_table.py::test_update_cell_at_column_width[A-BB-3]", "tests/test_data_table.py::test_update_cell_at_column_width[1234567-1234-7]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123-5]", "tests/test_data_table.py::test_update_cell_at_column_width[12345-123456789-9]", "tests/test_data_table.py::test_coordinate_to_cell_key", "tests/test_data_table.py::test_coordinate_to_cell_key_invalid_coordinate", "tests/test_data_table.py::test_datatable_click_cell_cursor", "tests/test_data_table.py::test_click_row_cursor", "tests/test_data_table.py::test_click_column_cursor", "tests/test_data_table.py::test_hover_coordinate", "tests/test_data_table.py::test_hover_mouse_leave", "tests/test_data_table.py::test_header_selected", "tests/test_data_table.py::test_row_label_selected", "tests/test_data_table.py::test_sort_coordinate_and_key_access", "tests/test_data_table.py::test_sort_reverse_coordinate_and_key_access", "tests/test_data_table.py::test_cell_cursor_highlight_events", "tests/test_data_table.py::test_row_cursor_highlight_events", "tests/test_data_table.py::test_column_cursor_highlight_events", "tests/test_data_table.py::test_reuse_row_key_after_clear", "tests/test_data_table.py::test_reuse_column_key_after_clear", "tests/test_data_table.py::test_key_equals_equivalent_string", "tests/test_data_table.py::test_key_doesnt_match_non_equal_string", "tests/test_data_table.py::test_key_equals_self", "tests/test_data_table.py::test_key_string_lookup", "tests/test_data_table.py::test_scrolling_cursor_into_view", "tests/test_data_table.py::test_move_cursor", "tests/test_data_table.py::test_unset_hover_highlight_when_no_table_cell_under_mouse", "tests/test_data_table.py::test_sort_by_all_columns_no_key", "tests/test_data_table.py::test_sort_by_multiple_columns_no_key", "tests/test_data_table.py::test_sort_by_function_sum", "tests/test_data_table.py::test_add_row_auto_height[hey", "tests/test_data_table.py::test_add_row_auto_height[cell1-1]", "tests/test_data_table.py::test_add_row_auto_height[cell2-2]", "tests/test_data_table.py::test_add_row_auto_height[cell3-4]", "tests/test_data_table.py::test_add_row_auto_height[1\\n2\\n3\\n4\\n5\\n6\\n7-7]", "tests/test_data_table.py::test_add_row_expands_column_widths", "tests/test_data_table.py::test_cell_padding_updates_virtual_size", "tests/test_data_table.py::test_cell_padding_cannot_be_negative" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-01-05 17:55:54+00:00
mit
774
Textualize__textual-4030
diff --git a/CHANGELOG.md b/CHANGELOG.md index 302b617c4..a826849fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Unreleased + +### Fixed + +- Fixed duplicate watch methods being attached to DOM nodes https://github.com/Textualize/textual/pull/4030 +- Fixed using `watch` to create additional watchers would trigger other watch methods https://github.com/Textualize/textual/issues/3878 + ## [0.49.0] - 2024-02-07 ### Fixed diff --git a/src/textual/_types.py b/src/textual/_types.py index 4fe929f58..75a28e7c7 100644 --- a/src/textual/_types.py +++ b/src/textual/_types.py @@ -31,12 +31,24 @@ CallbackType = Union[Callable[[], Awaitable[None]], Callable[[], None]] """Type used for arbitrary callables used in callbacks.""" IgnoreReturnCallbackType = Union[Callable[[], Awaitable[Any]], Callable[[], Any]] """A callback which ignores the return type.""" -WatchCallbackType = Union[ - Callable[[], Awaitable[None]], - Callable[[Any], Awaitable[None]], +WatchCallbackBothValuesType = Union[ Callable[[Any, Any], Awaitable[None]], - Callable[[], None], - Callable[[Any], None], Callable[[Any, Any], None], ] +"""Type for watch methods that accept the old and new values of reactive objects.""" +WatchCallbackNewValueType = Union[ + Callable[[Any], Awaitable[None]], + Callable[[Any], None], +] +"""Type for watch methods that accept only the new value of reactive objects.""" +WatchCallbackNoArgsType = Union[ + Callable[[], Awaitable[None]], + Callable[[], None], +] +"""Type for watch methods that do not require the explicit value of the reactive.""" +WatchCallbackType = Union[ + WatchCallbackBothValuesType, + WatchCallbackNewValueType, + WatchCallbackNoArgsType, +] """Type used for callbacks passed to the `watch` method of widgets.""" diff --git a/src/textual/reactive.py b/src/textual/reactive.py index c23d5a56c..ec6703835 100644 --- a/src/textual/reactive.py +++ b/src/textual/reactive.py @@ -16,6 +16,7 @@ from typing import ( Generic, Type, TypeVar, + cast, overload, ) @@ -23,7 +24,13 @@ import rich.repr from . import events from ._callback import count_parameters -from ._types import MessageTarget, WatchCallbackType +from ._types import ( + MessageTarget, + WatchCallbackBothValuesType, + WatchCallbackNewValueType, + WatchCallbackNoArgsType, + WatchCallbackType, +) if TYPE_CHECKING: from .dom import DOMNode @@ -42,6 +49,43 @@ class TooManyComputesError(ReactiveError): """Raised when an attribute has public and private compute methods.""" +async def await_watcher(obj: Reactable, awaitable: Awaitable[object]) -> None: + """Coroutine to await an awaitable returned from a watcher""" + _rich_traceback_omit = True + await awaitable + # Watcher may have changed the state, so run compute again + obj.post_message(events.Callback(callback=partial(Reactive._compute, obj))) + + +def invoke_watcher( + watcher_object: Reactable, + watch_function: WatchCallbackType, + old_value: object, + value: object, +) -> None: + """Invoke a watch function. + + Args: + watcher_object: The object watching for the changes. + watch_function: A watch function, which may be sync or async. + old_value: The old value of the attribute. + value: The new value of the attribute. + """ + _rich_traceback_omit = True + param_count = count_parameters(watch_function) + if param_count == 2: + watch_result = cast(WatchCallbackBothValuesType, watch_function)( + old_value, value + ) + elif param_count == 1: + watch_result = cast(WatchCallbackNewValueType, watch_function)(value) + else: + watch_result = cast(WatchCallbackNoArgsType, watch_function)() + if isawaitable(watch_result): + # Result is awaitable, so we need to await it within an async context + watcher_object.call_next(partial(await_watcher, watcher_object, watch_result)) + + @rich.repr.auto class Reactive(Generic[ReactiveType]): """Reactive descriptor. @@ -239,7 +283,7 @@ class Reactive(Generic[ReactiveType]): obj.refresh(repaint=self._repaint, layout=self._layout) @classmethod - def _check_watchers(cls, obj: Reactable, name: str, old_value: Any): + def _check_watchers(cls, obj: Reactable, name: str, old_value: Any) -> None: """Check watchers, and call watch methods / computes Args: @@ -252,39 +296,6 @@ class Reactive(Generic[ReactiveType]): internal_name = f"_reactive_{name}" value = getattr(obj, internal_name) - async def await_watcher(awaitable: Awaitable) -> None: - """Coroutine to await an awaitable returned from a watcher""" - _rich_traceback_omit = True - await awaitable - # Watcher may have changed the state, so run compute again - obj.post_message(events.Callback(callback=partial(Reactive._compute, obj))) - - def invoke_watcher( - watcher_object: Reactable, - watch_function: Callable, - old_value: object, - value: object, - ) -> None: - """Invoke a watch function. - - Args: - watcher_object: The object watching for the changes. - watch_function: A watch function, which may be sync or async. - old_value: The old value of the attribute. - value: The new value of the attribute. - """ - _rich_traceback_omit = True - param_count = count_parameters(watch_function) - if param_count == 2: - watch_result = watch_function(old_value, value) - elif param_count == 1: - watch_result = watch_function(value) - else: - watch_result = watch_function() - if isawaitable(watch_result): - # Result is awaitable, so we need to await it within an async context - watcher_object.call_next(partial(await_watcher, watch_result)) - private_watch_function = getattr(obj, f"_watch_{name}", None) if callable(private_watch_function): invoke_watcher(obj, private_watch_function, old_value, value) @@ -294,7 +305,7 @@ class Reactive(Generic[ReactiveType]): invoke_watcher(obj, public_watch_function, old_value, value) # Process "global" watchers - watchers: list[tuple[Reactable, Callable]] + watchers: list[tuple[Reactable, WatchCallbackType]] watchers = getattr(obj, "__watchers", {}).get(name, []) # Remove any watchers for reactables that have since closed if watchers: @@ -404,11 +415,13 @@ def _watch( """ if not hasattr(obj, "__watchers"): setattr(obj, "__watchers", {}) - watchers: dict[str, list[tuple[Reactable, Callable]]] = getattr(obj, "__watchers") + watchers: dict[str, list[tuple[Reactable, WatchCallbackType]]] = getattr( + obj, "__watchers" + ) watcher_list = watchers.setdefault(attribute_name, []) - if callback in watcher_list: + if any(callback == callback_from_list for _, callback_from_list in watcher_list): return - watcher_list.append((node, callback)) if init: current_value = getattr(obj, attribute_name, None) - Reactive._check_watchers(obj, attribute_name, current_value) + invoke_watcher(obj, callback, current_value, current_value) + watcher_list.append((node, callback))
Textualize/textual
b28ad500a3da98bfcde25a71082303d82270491d
diff --git a/tests/test_reactive.py b/tests/test_reactive.py index df09b7969..7bddb3df7 100644 --- a/tests/test_reactive.py +++ b/tests/test_reactive.py @@ -598,3 +598,110 @@ async def test_set_reactive(): app = MyApp() async with app.run_test(): assert app.query_one(MyWidget).foo == "foobar" + + +async def test_no_duplicate_external_watchers() -> None: + """Make sure we skip duplicated watchers.""" + + counter = 0 + + class Holder(Widget): + attr = var(None) + + class MyApp(App[None]): + def __init__(self) -> None: + super().__init__() + self.holder = Holder() + + def on_mount(self) -> None: + self.watch(self.holder, "attr", self.callback) + self.watch(self.holder, "attr", self.callback) + + def callback(self) -> None: + nonlocal counter + counter += 1 + + app = MyApp() + async with app.run_test(): + assert counter == 1 + app.holder.attr = 73 + assert counter == 2 + + +async def test_external_watch_init_does_not_propagate() -> None: + """Regression test for https://github.com/Textualize/textual/issues/3878. + + Make sure that when setting an extra watcher programmatically and `init` is set, + we init only the new watcher and not the other ones, but at the same + time make sure both watchers work in regular circumstances. + """ + + logs: list[str] = [] + + class SomeWidget(Widget): + test_1: var[int] = var(0) + test_2: var[int] = var(0, init=False) + + def watch_test_1(self) -> None: + logs.append("test_1") + + def watch_test_2(self) -> None: + logs.append("test_2") + + class InitOverrideApp(App[None]): + def compose(self) -> ComposeResult: + yield SomeWidget() + + def on_mount(self) -> None: + def watch_test_2_extra() -> None: + logs.append("test_2_extra") + + self.watch(self.query_one(SomeWidget), "test_2", watch_test_2_extra) + + app = InitOverrideApp() + async with app.run_test(): + assert logs == ["test_1", "test_2_extra"] + app.query_one(SomeWidget).test_2 = 73 + assert logs.count("test_2_extra") == 2 + assert logs.count("test_2") == 1 + + +async def test_external_watch_init_does_not_propagate_to_externals() -> None: + """Regression test for https://github.com/Textualize/textual/issues/3878. + + Make sure that when setting an extra watcher programmatically and `init` is set, + we init only the new watcher and not the other ones (even if they were + added dynamically with `watch`), but at the same time make sure all watchers + work in regular circumstances. + """ + + logs: list[str] = [] + + class SomeWidget(Widget): + test_var: var[int] = var(0) + + class MyApp(App[None]): + def compose(self) -> ComposeResult: + yield SomeWidget() + + def add_first_watcher(self) -> None: + def first_callback() -> None: + logs.append("first") + + self.watch(self.query_one(SomeWidget), "test_var", first_callback) + + def add_second_watcher(self) -> None: + def second_callback() -> None: + logs.append("second") + + self.watch(self.query_one(SomeWidget), "test_var", second_callback) + + app = MyApp() + async with app.run_test(): + assert logs == [] + app.add_first_watcher() + assert logs == ["first"] + app.add_second_watcher() + assert logs == ["first", "second"] + app.query_one(SomeWidget).test_var = 73 + assert logs == ["first", "second", "first", "second"]
A `watch` on a reactive that is declared `init=False` fires watch method on init [Stemming from a question on Discord](https://discord.com/channels/1026214085173461072/1033754296224841768/1185161330462838784); consider this code: ```python from textual.app import App, ComposeResult from textual.reactive import var from textual.widgets import Label, Log class SomeWidget(Label): test_1: var[int] = var(0) test_2: var[int] = var(0, init=False) def watch_test_1(self, was: int, into: int) -> None: self.screen.query_one(Log).write_line(f"test_1 {was} -> {into}") def watch_test_2(self, was: int, into: int) -> None: self.screen.query_one(Log).write_line(f"test_2 {was} -> {into}") class InitOverrideApp(App[None]): def compose(self) -> ComposeResult: yield SomeWidget() yield Log() if __name__ == "__main__": InitOverrideApp().run() ``` when run, it correctly logs that `test_1` changed, and correctly doesn't log that `test_2` changed. Now, if we add a `watch` on `test_2`: ```python from textual.app import App, ComposeResult from textual.reactive import var from textual.widgets import Label, Log class SomeWidget(Label): test_1: var[int] = var(0) test_2: var[int] = var(0, init=False) def watch_test_1(self, was: int, into: int) -> None: self.screen.query_one(Log).write_line(f"test_1 {was} -> {into}") def watch_test_2(self, was: int, into: int) -> None: self.screen.query_one(Log).write_line(f"test_2 {was} -> {into}") class InitOverrideApp(App[None]): def compose(self) -> ComposeResult: yield SomeWidget() yield Log() def on_mount(self) -> None: def gndn() -> None: return self.watch(self.query_one(SomeWidget), "test_2", gndn) if __name__ == "__main__": InitOverrideApp().run() ``` this appears to override the `init=False` declared for `test_2`, and causes `SomeWidget.watch_test_2` to fire. This can be worked around by making the `watch` setup call like this: ```python self.watch(self.query_one(SomeWidget), "test_2", gndn, init=False) ``` but it seems like an unintended consequence that the watch method (`SomeWidget.watch_test_2`) gets called without that.
0.0
b28ad500a3da98bfcde25a71082303d82270491d
[ "tests/test_reactive.py::test_no_duplicate_external_watchers", "tests/test_reactive.py::test_external_watch_init_does_not_propagate", "tests/test_reactive.py::test_external_watch_init_does_not_propagate_to_externals" ]
[ "tests/test_reactive.py::test_watch", "tests/test_reactive.py::test_watch_async_init_false", "tests/test_reactive.py::test_watch_async_init_true", "tests/test_reactive.py::test_watch_init_false_always_update_false", "tests/test_reactive.py::test_watch_init_true", "tests/test_reactive.py::test_reactive_always_update", "tests/test_reactive.py::test_reactive_with_callable_default", "tests/test_reactive.py::test_validate_init_true", "tests/test_reactive.py::test_validate_init_true_set_before_dom_ready", "tests/test_reactive.py::test_reactive_compute_first_time_set", "tests/test_reactive.py::test_reactive_method_call_order", "tests/test_reactive.py::test_premature_reactive_call", "tests/test_reactive.py::test_reactive_inheritance", "tests/test_reactive.py::test_compute", "tests/test_reactive.py::test_watch_compute", "tests/test_reactive.py::test_public_and_private_watch", "tests/test_reactive.py::test_private_validate", "tests/test_reactive.py::test_public_and_private_validate", "tests/test_reactive.py::test_public_and_private_validate_order", "tests/test_reactive.py::test_public_and_private_compute", "tests/test_reactive.py::test_private_compute", "tests/test_reactive.py::test_async_reactive_watch_callbacks_go_on_the_watcher", "tests/test_reactive.py::test_sync_reactive_watch_callbacks_go_on_the_watcher", "tests/test_reactive.py::test_set_reactive" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-16 14:55:05+00:00
mit
775
Textualize__textual-4032
diff --git a/CHANGELOG.md b/CHANGELOG.md index 44a95d744..bc2657ad1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `SelectionList` option IDs are usable as soon as the widget is instantiated https://github.com/Textualize/textual/issues/3903 - Fix issue with `Strip.crop` when crop window start aligned with strip end https://github.com/Textualize/textual/pull/3998 - Fixed Strip.crop_extend https://github.com/Textualize/textual/pull/4011 +- ID and class validation was too lenient https://github.com/Textualize/textual/issues/3954 - Fixed a crash if the `TextArea` language was set but tree-sitter lanuage binaries were not installed https://github.com/Textualize/textual/issues/4045 diff --git a/src/textual/dom.py b/src/textual/dom.py index 461e9acea..2664881d9 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -80,7 +80,7 @@ def check_identifiers(description: str, *names: str) -> None: description: Description of where identifier is used for error message. *names: Identifiers to check. """ - match = _re_identifier.match + match = _re_identifier.fullmatch for name in names: if match(name) is None: raise BadIdentifier(
Textualize/textual
2983d6140a3cd15c08359f529c460c9e9f72f715
diff --git a/tests/test_dom.py b/tests/test_dom.py index 6f06fb809..ea14a25bf 100644 --- a/tests/test_dom.py +++ b/tests/test_dom.py @@ -259,3 +259,24 @@ def test_walk_children_with_self_breadth(search): ] assert children == ["f", "e", "d", "c", "b", "a"] + + [email protected]( + "identifier", + [ + " bad", + " terrible ", + "worse! ", + "&ampersand", + "amper&sand", + "ampersand&", + "2_leading_digits", + "água", # water + "cão", # dog + "@'/.23", + ], +) +def test_id_validation(identifier: str): + """Regression tests for https://github.com/Textualize/textual/issues/3954.""" + with pytest.raises(BadIdentifier): + DOMNode(id=identifier)
It is possible to give a widget an ID that can't be queried back It is possible to give a widget an ID that can't then be queried back; for example: ```python from textual.app import App, ComposeResult from textual.widgets import Label class BadIDApp(App[None]): def compose(self) -> ComposeResult: yield Label("Hello, World!", id="foo&") def on_mount(self) -> None: self.notify(f"{self.query_one('#foo&')}") if __name__ == "__main__": BadIDApp().run() ``` Perhaps we should validate widget IDs when they are assigned?
0.0
2983d6140a3cd15c08359f529c460c9e9f72f715
[ "tests/test_dom.py::test_id_validation[worse!", "tests/test_dom.py::test_id_validation[amper&sand]", "tests/test_dom.py::test_id_validation[ampersand&]", "tests/test_dom.py::test_id_validation[c\\xe3o]" ]
[ "tests/test_dom.py::test_display_default", "tests/test_dom.py::test_display_set_bool[True-block]", "tests/test_dom.py::test_display_set_bool[False-none]", "tests/test_dom.py::test_display_set_bool[block-block]", "tests/test_dom.py::test_display_set_bool[none-none]", "tests/test_dom.py::test_display_set_invalid_value", "tests/test_dom.py::test_validate", "tests/test_dom.py::test_classes_setter", "tests/test_dom.py::test_classes_setter_iterable", "tests/test_dom.py::test_classes_set_classes", "tests/test_dom.py::test_inherited_bindings", "tests/test_dom.py::test__get_default_css", "tests/test_dom.py::test_component_classes_inheritance", "tests/test_dom.py::test_walk_children_depth", "tests/test_dom.py::test_walk_children_with_self_depth", "tests/test_dom.py::test_walk_children_breadth", "tests/test_dom.py::test_walk_children_with_self_breadth", "tests/test_dom.py::test_id_validation[", "tests/test_dom.py::test_id_validation[&ampersand]", "tests/test_dom.py::test_id_validation[2_leading_digits]", "tests/test_dom.py::test_id_validation[\\xe1gua]", "tests/test_dom.py::test_id_validation[@'/.23]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-01-16 17:31:17+00:00
mit
776
Textualize__textual-4103
diff --git a/CHANGELOG.md b/CHANGELOG.md index d3796faf7..fe0830770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## Unreleased +### Fixed + +- Fixed broken `OptionList` `Option.id` mappings https://github.com/Textualize/textual/issues/4101 + ### Changed - Breaking change: keyboard navigation in `RadioSet`, `ListView`, `OptionList`, and `SelectionList`, no longer allows highlighting disabled items https://github.com/Textualize/textual/issues/3881 diff --git a/src/textual/widgets/_option_list.py b/src/textual/widgets/_option_list.py index a9ba696bc..888140bbe 100644 --- a/src/textual/widgets/_option_list.py +++ b/src/textual/widgets/_option_list.py @@ -573,15 +573,16 @@ class OptionList(ScrollView, can_focus=True): content = [self._make_content(item) for item in items] self._duplicate_id_check(content) self._contents.extend(content) - # Pull out the content that is genuine options. Add them to the - # list of options and map option IDs to their new indices. + # Pull out the content that is genuine options, create any new + # ID mappings required, then add the new options to the option + # list. new_options = [item for item in content if isinstance(item, Option)] - self._options.extend(new_options) for new_option_index, new_option in enumerate( new_options, start=len(self._options) ): if new_option.id: self._option_ids[new_option.id] = new_option_index + self._options.extend(new_options) self._refresh_content_tracking(force=True) self.refresh()
Textualize/textual
8ae0b27bc8a18237e568430fc9f74c3c10f8e0a5
diff --git a/tests/option_list/test_option_list_id_stability.py b/tests/option_list/test_option_list_id_stability.py new file mode 100644 index 000000000..bd746914b --- /dev/null +++ b/tests/option_list/test_option_list_id_stability.py @@ -0,0 +1,22 @@ +"""Tests inspired by https://github.com/Textualize/textual/issues/4101""" + +from __future__ import annotations + +from textual.app import App, ComposeResult +from textual.widgets import OptionList +from textual.widgets.option_list import Option + + +class OptionListApp(App[None]): + """Test option list application.""" + + def compose(self) -> ComposeResult: + yield OptionList() + + +async def test_get_after_add() -> None: + """It should be possible to get an option by ID after adding.""" + async with OptionListApp().run_test() as pilot: + option_list = pilot.app.query_one(OptionList) + option_list.add_option(Option("0", id="0")) + assert option_list.get_option("0").id == "0"
`Option` indexing appears to break after an `OptionList.clear_options` and `OptionList.add_option(s)` This looks to be a bug introduced in v0.48 of Textual. Consider this code: ```python from textual import on from textual.app import App, ComposeResult from textual.reactive import var from textual.widgets import Button, OptionList from textual.widgets.option_list import Option class OptionListReAdd(App[None]): count: var[int] = var(0) def compose(self) -> ComposeResult: yield Button("Add again") yield OptionList(Option(f"This is the option we'll keep adding {self.count}", id="0")) @on(Button.Pressed) def readd(self) -> None: self.count += 1 _ = self.query_one(OptionList).get_option("0") self.query_one(OptionList).clear_options().add_option( Option(f"This is the option we'll keep adding {self.count}", id="0") ) if __name__ == "__main__": OptionListReAdd().run() ``` With v0.47.1, you can press the button many times and the code does what you'd expect; the option keeps being replaced, and it can always be acquired back with a `get_option` on its ID. With v0.48.0/1 you get the following error the second time you press the button: ```python ╭────────────────────────────────────────────────────── Traceback (most recent call last) ───────────────────────────────────────────────────────╮ │ /Users/davep/develop/python/textual-sandbox/option_list_readd.py:18 in readd │ │ │ │ 15 │ @on(Button.Pressed) │ │ 16 │ def readd(self) -> None: │ │ 17 │ │ self.count += 1 │ │ ❱ 18 │ │ _ = self.query_one(OptionList).get_option("0") │ │ 19 │ │ self.query_one(OptionList).clear_options().add_option( │ │ 20 │ │ │ Option(f"This is the option we'll keep adding {self.count}", id="0") │ │ 21 │ │ ) │ │ │ │ ╭──────────────────────────────── locals ─────────────────────────────────╮ │ │ │ self = OptionListReAdd(title='OptionListReAdd', classes={'-dark-mode'}) │ │ │ ╰─────────────────────────────────────────────────────────────────────────╯ │ │ │ │ /Users/davep/develop/python/textual-sandbox/.venv/lib/python3.10/site-packages/textual/widgets/_option_list.py:861 in get_option │ │ │ │ 858 │ │ Raises: ╭───────── locals ─────────╮ │ │ 859 │ │ │ OptionDoesNotExist: If no option has the given ID. │ option_id = '0' │ │ │ 860 │ │ """ │ self = OptionList() │ │ │ ❱ 861 │ │ return self.get_option_at_index(self.get_option_index(option_id)) ╰──────────────────────────╯ │ │ 862 │ │ │ 863 │ def get_option_index(self, option_id: str) -> int: │ │ 864 │ │ """Get the index of the option with the given ID. │ │ │ │ /Users/davep/develop/python/textual-sandbox/.venv/lib/python3.10/site-packages/textual/widgets/_option_list.py:845 in get_option_at_index │ │ │ │ 842 │ │ try: ╭─────── locals ───────╮ │ │ 843 │ │ │ return self._options[index] │ index = 1 │ │ │ 844 │ │ except IndexError: │ self = OptionList() │ │ │ ❱ 845 │ │ │ raise OptionDoesNotExist( ╰──────────────────────╯ │ │ 846 │ │ │ │ f"There is no option with an index of {index}" │ │ 847 │ │ │ ) from None │ │ 848 │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ OptionDoesNotExist: There is no option with an index of 1 ``` Tagging @willmcgugan for triage. Perhaps related to b1aaea781297699e029e120a55ca49b1361d056e
0.0
8ae0b27bc8a18237e568430fc9f74c3c10f8e0a5
[ "tests/option_list/test_option_list_id_stability.py::test_get_after_add" ]
[]
{ "failed_lite_validators": [ "has_git_commit_hash", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-02-02 09:37:08+00:00
mit
777
Textualize__textual-4125
diff --git a/CHANGELOG.md b/CHANGELOG.md index 32facd86a..916101fc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [0.48.2] - 2024-02-02 - -### Fixed - -- Fixed a hang in the Linux driver when connected to a pipe https://github.com/Textualize/textual/issues/4104 -- Fixed broken `OptionList` `Option.id` mappings https://github.com/Textualize/textual/issues/4101 +## Unreleased ### Added @@ -20,6 +15,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Added DOMNode.action_toggle https://github.com/Textualize/textual/pull/4075 - Added Worker.cancelled_event https://github.com/Textualize/textual/pull/4075 +### Fixed + +- Breaking change: `TextArea` will not use `Escape` to shift focus if the `tab_behaviour` is the default https://github.com/Textualize/textual/issues/4110 + +## [0.48.2] - 2024-02-02 + +### Fixed + +- Fixed a hang in the Linux driver when connected to a pipe https://github.com/Textualize/textual/issues/4104 +- Fixed broken `OptionList` `Option.id` mappings https://github.com/Textualize/textual/issues/4101 + ### Changed - Breaking change: keyboard navigation in `RadioSet`, `ListView`, `OptionList`, and `SelectionList`, no longer allows highlighting disabled items https://github.com/Textualize/textual/issues/3881 diff --git a/docs/widgets/text_area.md b/docs/widgets/text_area.md index bb0f50810..57fdc719f 100644 --- a/docs/widgets/text_area.md +++ b/docs/widgets/text_area.md @@ -283,11 +283,13 @@ This immediately updates the appearance of the `TextArea`: ```{.textual path="docs/examples/widgets/text_area_custom_theme.py" columns="42" lines="8"} ``` -### Tab behaviour +### Tab and Escape behaviour Pressing the ++tab++ key will shift focus to the next widget in your application by default. This matches how other widgets work in Textual. + To have ++tab++ insert a `\t` character, set the `tab_behaviour` attribute to the string value `"indent"`. +While in this mode, you can shift focus by pressing the ++escape++ key. ### Indentation diff --git a/src/textual/widgets/_text_area.py b/src/textual/widgets/_text_area.py index 6c8abd101..a263ab6d3 100644 --- a/src/textual/widgets/_text_area.py +++ b/src/textual/widgets/_text_area.py @@ -153,7 +153,6 @@ TextArea:light .text-area--cursor { """ BINDINGS = [ - Binding("escape", "screen.focus_next", "Shift Focus", show=False), # Cursor movement Binding("up", "cursor_up", "cursor up", show=False), Binding("down", "cursor_down", "cursor down", show=False), @@ -213,7 +212,6 @@ TextArea:light .text-area--cursor { """ | Key(s) | Description | | :- | :- | - | escape | Focus on the next item. | | up | Move the cursor up. | | down | Move the cursor down. | | left | Move the cursor left. | @@ -1213,6 +1211,11 @@ TextArea:light .text-area--cursor { "enter": "\n", } if self.tab_behaviour == "indent": + if key == "escape": + event.stop() + event.prevent_default() + self.screen.focus_next() + return if self.indent_type == "tabs": insert_values["tab"] = "\t" else:
Textualize/textual
5d6c61afa0f4cc225e2c6ecea11163556a7a37ef
diff --git a/tests/text_area/test_escape_binding.py b/tests/text_area/test_escape_binding.py new file mode 100644 index 000000000..bc644d308 --- /dev/null +++ b/tests/text_area/test_escape_binding.py @@ -0,0 +1,55 @@ +from textual.app import App, ComposeResult +from textual.screen import ModalScreen +from textual.widgets import Button, TextArea + + +class TextAreaDialog(ModalScreen): + BINDINGS = [("escape", "dismiss")] + + def compose(self) -> ComposeResult: + yield TextArea( + tab_behaviour="focus", # the default + ) + yield Button("Submit") + + +class TextAreaDialogApp(App): + def on_mount(self) -> None: + self.push_screen(TextAreaDialog()) + + +async def test_escape_key_when_tab_behaviour_is_focus(): + """Regression test for https://github.com/Textualize/textual/issues/4110 + + When the `tab_behaviour` of TextArea is the default to shift focus, + pressing <Escape> should not shift focus but instead skip and allow any + parent bindings to run. + """ + + app = TextAreaDialogApp() + async with app.run_test() as pilot: + # Sanity check + assert isinstance(pilot.app.screen, TextAreaDialog) + assert isinstance(pilot.app.focused, TextArea) + + # Pressing escape should dismiss the dialog screen, not focus the button + await pilot.press("escape") + assert not isinstance(pilot.app.screen, TextAreaDialog) + + +async def test_escape_key_when_tab_behaviour_is_indent(): + """When the `tab_behaviour` of TextArea is indent rather than switch focus, + pressing <Escape> should instead shift focus. + """ + + app = TextAreaDialogApp() + async with app.run_test() as pilot: + # Sanity check + assert isinstance(pilot.app.screen, TextAreaDialog) + assert isinstance(pilot.app.focused, TextArea) + + pilot.app.query_one(TextArea).tab_behaviour = "indent" + # Pressing escape should focus the button, not dismiss the dialog screen + await pilot.press("escape") + assert isinstance(pilot.app.screen, TextAreaDialog) + assert isinstance(pilot.app.focused, Button)
`TextArea` still uses `Escape` to move focus on While "out of the box" `TextArea` now uses <kbd>Tab</kbd> to shift focus, it also still uses <kbd>Escape</kbd>, ideally it would not when in this mode. Pressing <kbd>Escape</kbd> to exit a modal dialog would be common, so having <kbd>Escape</kbd> do something different given one particular widget type would be surprising for the user. For example, this dialog uses <kbd>Escape</kbd> as the quick exit key, but instead if moves focus if you happen to press it while in the `TextArea`: ![Screenshot 2024-02-02 at 21 18 15](https://github.com/Textualize/textual/assets/28237/7b1e295e-5908-4afe-94e2-847b20e3f851)
0.0
5d6c61afa0f4cc225e2c6ecea11163556a7a37ef
[ "tests/text_area/test_escape_binding.py::test_escape_key_when_tab_behaviour_is_focus" ]
[ "tests/text_area/test_escape_binding.py::test_escape_key_when_tab_behaviour_is_indent" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-05 20:44:48+00:00
mit
778
Textualize__textual-4183
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e02eb239..409cd5e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Add attribute `App.animation_level` to control whether animations on that app run or not https://github.com/Textualize/textual/pull/4062 - Added support for a `TEXTUAL_SCREENSHOT_LOCATION` environment variable to specify the location of an automated screenshot https://github.com/Textualize/textual/pull/4181/ - Added support for a `TEXTUAL_SCREENSHOT_FILENAME` environment variable to specify the filename of an automated screenshot https://github.com/Textualize/textual/pull/4181/ +- Added an `asyncio` lock attribute `Widget.lock` to be used to synchronize widget state https://github.com/Textualize/textual/issues/4134 +- `Widget.remove_children` now accepts a CSS selector to specify which children to remove https://github.com/Textualize/textual/pull/4183 +- `Widget.batch` combines widget locking and app update batching https://github.com/Textualize/textual/pull/4183 ## [0.51.0] - 2024-02-15 diff --git a/src/textual/widget.py b/src/textual/widget.py index b70596b78..157e0cb93 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -6,11 +6,13 @@ from __future__ import annotations from asyncio import Lock, create_task, wait from collections import Counter +from contextlib import asynccontextmanager from fractions import Fraction from itertools import islice from types import TracebackType from typing import ( TYPE_CHECKING, + AsyncGenerator, Awaitable, ClassVar, Collection, @@ -53,6 +55,8 @@ from .actions import SkipAction from .await_remove import AwaitRemove from .box_model import BoxModel from .cache import FIFOCache +from .css.match import match +from .css.parse import parse_selectors from .css.query import NoMatches, WrongType from .css.scalar import ScalarOffset from .dom import DOMNode, NoScreen @@ -78,6 +82,7 @@ from .walk import walk_depth_first if TYPE_CHECKING: from .app import App, ComposeResult + from .css.query import QueryType from .message_pump import MessagePump from .scrollbar import ( ScrollBar, @@ -3291,15 +3296,42 @@ class Widget(DOMNode): await_remove = self.app._remove_nodes([self], self.parent) return await_remove - def remove_children(self) -> AwaitRemove: - """Remove all children of this Widget from the DOM. + def remove_children(self, selector: str | type[QueryType] = "*") -> AwaitRemove: + """Remove the immediate children of this Widget from the DOM. + + Args: + selector: A CSS selector to specify which direct children to remove. Returns: - An awaitable object that waits for the children to be removed. + An awaitable object that waits for the direct children to be removed. """ - await_remove = self.app._remove_nodes(list(self.children), self) + if not isinstance(selector, str): + selector = selector.__name__ + parsed_selectors = parse_selectors(selector) + children_to_remove = [ + child for child in self.children if match(parsed_selectors, child) + ] + await_remove = self.app._remove_nodes(children_to_remove, self) return await_remove + @asynccontextmanager + async def batch(self) -> AsyncGenerator[None, None]: + """Async context manager that combines widget locking and update batching. + + Use this async context manager whenever you want to acquire the widget lock and + batch app updates at the same time. + + Example: + ```py + async with container.batch(): + await container.remove_children(Button) + await container.mount(Label("All buttons are gone.")) + ``` + """ + async with self.lock: + with self.app.batch_update(): + yield + def render(self) -> RenderableType: """Get text or Rich renderable for this widget.
Textualize/textual
ba17dfb56f16a3f517a16904c7765d08a0df8561
diff --git a/tests/test_widget_removing.py b/tests/test_widget_removing.py index ddb9dae16..7ffb624d7 100644 --- a/tests/test_widget_removing.py +++ b/tests/test_widget_removing.py @@ -141,6 +141,63 @@ async def test_widget_remove_children_container(): assert len(container.children) == 0 +async def test_widget_remove_children_with_star_selector(): + app = ExampleApp() + async with app.run_test(): + container = app.query_one(Vertical) + + # 6 labels in total, with 5 of them inside the container. + assert len(app.query(Label)) == 6 + assert len(container.children) == 5 + + await container.remove_children("*") + + # The labels inside the container are gone, and the 1 outside remains. + assert len(app.query(Label)) == 1 + assert len(container.children) == 0 + + +async def test_widget_remove_children_with_string_selector(): + app = ExampleApp() + async with app.run_test(): + container = app.query_one(Vertical) + + # 6 labels in total, with 5 of them inside the container. + assert len(app.query(Label)) == 6 + assert len(container.children) == 5 + + await app.screen.remove_children("Label") + + # Only the Screen > Label widget is gone, everything else remains. + assert len(app.query(Button)) == 1 + assert len(app.query(Vertical)) == 1 + assert len(app.query(Label)) == 5 + + +async def test_widget_remove_children_with_type_selector(): + app = ExampleApp() + async with app.run_test(): + assert len(app.query(Button)) == 1 # Sanity check. + await app.screen.remove_children(Button) + assert len(app.query(Button)) == 0 + + +async def test_widget_remove_children_with_selector_does_not_leak(): + app = ExampleApp() + async with app.run_test(): + container = app.query_one(Vertical) + + # 6 labels in total, with 5 of them inside the container. + assert len(app.query(Label)) == 6 + assert len(container.children) == 5 + + await container.remove_children("Label") + + # The labels inside the container are gone, and the 1 outside remains. + assert len(app.query(Label)) == 1 + assert len(container.children) == 0 + + async def test_widget_remove_children_no_children(): app = ExampleApp() async with app.run_test(): @@ -154,3 +211,17 @@ async def test_widget_remove_children_no_children(): assert ( count_before == count_after ) # No widgets have been removed, since Button has no children. + + +async def test_widget_remove_children_no_children_match_selector(): + app = ExampleApp() + async with app.run_test(): + container = app.query_one(Vertical) + assert len(container.query("Button")) == 0 # Sanity check. + + count_before = len(app.query("*")) + container_children_before = list(container.children) + await container.remove_children("Button") + + assert count_before == len(app.query("*")) + assert container_children_before == list(container.children)
Add `remove` attribute to `mount` and `mount_all` It's common to remove some widgets and add some other widgets. To make this easier, I think we should add a `remove` attribute to the mount methods which accepts a selector and removes those widgets prior to mounting. The remove + mount should be atomic, to avoid flicker (might need to be wrapped in `batch_update`). API would look something like this: ```python # Replace all MyWidgets with a single MyWidget await self.mount(MyWidget("Foo"), remove="MyWidget") # Remove all children and replace with a label await self.mount(Label("Goodbye"), remove="*") ```
0.0
ba17dfb56f16a3f517a16904c7765d08a0df8561
[ "tests/test_widget_removing.py::test_widget_remove_children_with_star_selector", "tests/test_widget_removing.py::test_widget_remove_children_with_string_selector", "tests/test_widget_removing.py::test_widget_remove_children_with_type_selector", "tests/test_widget_removing.py::test_widget_remove_children_with_selector_does_not_leak", "tests/test_widget_removing.py::test_widget_remove_children_no_children_match_selector" ]
[ "tests/test_widget_removing.py::test_remove_single_widget", "tests/test_widget_removing.py::test_many_remove_all_widgets", "tests/test_widget_removing.py::test_many_remove_some_widgets", "tests/test_widget_removing.py::test_remove_branch", "tests/test_widget_removing.py::test_remove_overlap", "tests/test_widget_removing.py::test_remove_move_focus", "tests/test_widget_removing.py::test_widget_remove_order", "tests/test_widget_removing.py::test_query_remove_order", "tests/test_widget_removing.py::test_widget_remove_children_container", "tests/test_widget_removing.py::test_widget_remove_children_no_children" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-19 14:50:01+00:00
mit
779
Textualize__textual-4234
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7859d9034..24410aa10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added - Mapping of ANSI colors to hex codes configurable via `App.ansi_theme_dark` and `App.ansi_theme_light` https://github.com/Textualize/textual/pull/4192 +- `Pilot.resize_terminal` to resize the terminal in testing https://github.com/Textualize/textual/issues/4212 ### Fixed @@ -26,9 +27,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Rename `CollapsibleTitle.action_toggle` to `action_toggle_collapsible` to fix clash with `DOMNode.action_toggle` https://github.com/Textualize/textual/pull/4221 - Markdown component classes weren't refreshed when watching for CSS https://github.com/Textualize/textual/issues/3464 -### Added +### Changed -- `Pilot.resize_terminal` to resize the terminal in testing https://github.com/Textualize/textual/issues/4212 +- Clicking a non focusable widget focus ancestors https://github.com/Textualize/textual/pull/4236 ## [0.52.1] - 2024-02-20 diff --git a/mkdocs-nav.yml b/mkdocs-nav.yml index ccb858f35..c97e5396b 100644 --- a/mkdocs-nav.yml +++ b/mkdocs-nav.yml @@ -67,6 +67,7 @@ nav: - "events/screen_suspend.md" - "events/show.md" - Styles: + - "styles/index.md" - "styles/align.md" - "styles/background.md" - "styles/border.md" @@ -83,8 +84,6 @@ nav: - "styles/content_align.md" - "styles/display.md" - "styles/dock.md" - - "styles/index.md" - - "styles/keyline.md" - Grid: - "styles/grid/index.md" - "styles/grid/column_span.md" @@ -94,6 +93,7 @@ nav: - "styles/grid/grid_size.md" - "styles/grid/row_span.md" - "styles/height.md" + - "styles/keyline.md" - "styles/layer.md" - "styles/layers.md" - "styles/layout.md" diff --git a/src/textual/app.py b/src/textual/app.py index 2e9c7f532..124f2d25c 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -1286,7 +1286,7 @@ class App(Generic[ReturnType], DOMNode): except KeyError: char = key if len(key) == 1 else None key_event = events.Key(key, char) - key_event._set_sender(app) + key_event.set_sender(app) driver.send_event(key_event) await wait_for_idle(0) await app._animator.wait_until_complete() diff --git a/src/textual/await_complete.py b/src/textual/await_complete.py index 51d807f6d..3ac56b03b 100644 --- a/src/textual/await_complete.py +++ b/src/textual/await_complete.py @@ -1,7 +1,7 @@ from __future__ import annotations from asyncio import Future, gather -from typing import Any, Coroutine, Iterator, TypeVar +from typing import Any, Coroutine, Generator, TypeVar import rich.repr @@ -19,12 +19,12 @@ class AwaitComplete: coroutines: One or more coroutines to execute. """ self.coroutines: tuple[Coroutine[Any, Any, Any], ...] = coroutines - self._future: Future = gather(*self.coroutines) + self._future: Future[Any] = gather(*self.coroutines) async def __call__(self) -> Any: return await self - def __await__(self) -> Iterator[None]: + def __await__(self) -> Generator[Any, None, Any]: return self._future.__await__() @property diff --git a/src/textual/driver.py b/src/textual/driver.py index 8500e3099..c70edf958 100644 --- a/src/textual/driver.py +++ b/src/textual/driver.py @@ -66,7 +66,7 @@ class Driver(ABC): """ # NOTE: This runs in a thread. # Avoid calling methods on the app. - event._set_sender(self._app) + event.set_sender(self._app) if isinstance(event, events.MouseDown): if event.button: self._down_buttons.append(event.button) diff --git a/src/textual/message.py b/src/textual/message.py index becdb374e..97d6b6c40 100644 --- a/src/textual/message.py +++ b/src/textual/message.py @@ -8,6 +8,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, ClassVar import rich.repr +from typing_extensions import Self from . import _time from ._context import active_message_pump @@ -90,9 +91,23 @@ class Message: """Mark this event as being forwarded.""" self._forwarded = True - def _set_sender(self, sender: MessagePump) -> None: - """Set the sender.""" + def set_sender(self, sender: MessagePump) -> Self: + """Set the sender of the message. + + Args: + sender: The sender. + + Note: + When creating a message the sender is automatically set. + Normally there will be no need for this method to be called. + This method will be used when strict control is required over + the sender of a message. + + Returns: + Self. + """ self._sender = sender + return self def can_replace(self, message: "Message") -> bool: """Check if another message may supersede this one. diff --git a/src/textual/screen.py b/src/textual/screen.py index 99d65ddf2..f9674a472 100644 --- a/src/textual/screen.py +++ b/src/textual/screen.py @@ -307,6 +307,29 @@ class Screen(Generic[ScreenResultType], Widget): """ return self._compositor.get_widgets_at(x, y) + def get_focusable_widget_at(self, x: int, y: int) -> Widget | None: + """Get the focusable widget under a given coordinate. + + If the widget directly under the given coordinate is not focusable, then this method will check + if any of the ancestors are focusable. If no ancestors are focusable, then `None` will be returned. + + Args: + x: X coordinate. + y: Y coordinate. + + Returns: + A `Widget`, or `None` if there is no focusable widget underneath the coordinate. + """ + try: + widget, _region = self.get_widget_at(x, y) + except NoWidget: + return None + + for node in widget.ancestors_with_self: + if isinstance(node, Widget) and node.focusable: + return node + return None + def get_style_at(self, x: int, y: int) -> Style: """Get the style under a given coordinate. @@ -1015,8 +1038,10 @@ class Screen(Generic[ScreenResultType], Widget): except errors.NoWidget: self.set_focus(None) else: - if isinstance(event, events.MouseDown) and widget.focusable: - self.set_focus(widget, scroll_visible=False) + if isinstance(event, events.MouseDown): + focusable_widget = self.get_focusable_widget_at(event.x, event.y) + if focusable_widget: + self.set_focus(focusable_widget, scroll_visible=False) event.style = self.get_style_at(event.screen_x, event.screen_y) if widget is self: event._set_forwarded()
Textualize/textual
08e78b8959eaacb2ad95d694c867084bffd4a4c3
diff --git a/tests/test_focus.py b/tests/test_focus.py index 67b35d0a9..0942753a6 100644 --- a/tests/test_focus.py +++ b/tests/test_focus.py @@ -1,10 +1,10 @@ import pytest from textual.app import App, ComposeResult -from textual.containers import Container +from textual.containers import Container, ScrollableContainer from textual.screen import Screen from textual.widget import Widget -from textual.widgets import Button +from textual.widgets import Button, Label class Focusable(Widget, can_focus=True): @@ -409,3 +409,42 @@ async def test_focus_pseudo_class(): classes = list(button.get_pseudo_classes()) assert "blur" not in classes assert "focus" in classes + + +async def test_get_focusable_widget_at() -> None: + """Check that clicking a non-focusable widget will focus any (focusable) ancestors.""" + + class FocusApp(App): + AUTO_FOCUS = None + + def compose(self) -> ComposeResult: + with ScrollableContainer(id="focusable"): + with Container(): + yield Label("Foo", id="foo") + yield Label("Bar", id="bar") + yield Label("Egg", id="egg") + + app = FocusApp() + async with app.run_test() as pilot: + # Nothing focused + assert app.screen.focused is None + # Click foo + await pilot.click("#foo") + # Confirm container is focused + assert app.screen.focused is not None + assert app.screen.focused.id == "focusable" + # Reset focus + app.screen.set_focus(None) + assert app.screen.focused is None + # Click bar + await pilot.click("#bar") + # Confirm container is focused + assert app.screen.focused is not None + assert app.screen.focused.id == "focusable" + # Reset focus + app.screen.set_focus(None) + assert app.screen.focused is None + # Click egg (outside of focusable widget) + await pilot.click("#egg") + # Confirm nothing focused + assert app.screen.focused is None
Type warning with `AwaitComplete` It seems that there is a type error when it comes to awaiting `AwaitComplete`. As an example, given this code: ```python from textual.app import App from textual.widgets import TabbedContent, TabPane class AwaitableTypeWarningApp(App[None]): async def on_mount(self) -> None: await self.query_one(TabbedContent).add_pane(TabPane("Test")) await self.query_one(TabbedContent).remove_pane("some-tab") ``` pyright reports: ``` /Users/davep/develop/python/textual-sandbox/await_type_warning.py /Users/davep/develop/python/textual-sandbox/await_type_warning.py:7:15 - error: "AwaitComplete" is not awaitable   "AwaitComplete" is incompatible with protocol "Awaitable[_T_co@Awaitable]"     "__await__" is an incompatible type       Type "() -> Iterator[None]" cannot be assigned to type "() -> Generator[Any, None, _T_co@Awaitable]"         Function return type "Iterator[None]" is incompatible with type "Generator[Any, None, _T_co@Awaitable]"           "Iterator[None]" is incompatible with "Generator[Any, None, _T_co@Awaitable]" (reportGeneralTypeIssues) /Users/davep/develop/python/textual-sandbox/await_type_warning.py:8:15 - error: "AwaitComplete" is not awaitable   "AwaitComplete" is incompatible with protocol "Awaitable[_T_co@Awaitable]"     "__await__" is an incompatible type       Type "() -> Iterator[None]" cannot be assigned to type "() -> Generator[Any, None, _T_co@Awaitable]"         Function return type "Iterator[None]" is incompatible with type "Generator[Any, None, _T_co@Awaitable]"           "Iterator[None]" is incompatible with "Generator[Any, None, _T_co@Awaitable]" (reportGeneralTypeIssues) 2 errors, 0 warnings, 0 informations ```
0.0
08e78b8959eaacb2ad95d694c867084bffd4a4c3
[ "tests/test_focus.py::test_get_focusable_widget_at" ]
[ "tests/test_focus.py::test_focus_chain", "tests/test_focus.py::test_allow_focus", "tests/test_focus.py::test_focus_next_and_previous", "tests/test_focus.py::test_focus_next_wrap_around", "tests/test_focus.py::test_focus_previous_wrap_around", "tests/test_focus.py::test_wrap_around_selector", "tests/test_focus.py::test_no_focus_empty_selector", "tests/test_focus.py::test_focus_next_and_previous_with_type_selector", "tests/test_focus.py::test_focus_next_and_previous_with_str_selector", "tests/test_focus.py::test_focus_next_and_previous_with_type_selector_without_self", "tests/test_focus.py::test_focus_next_and_previous_with_str_selector_without_self", "tests/test_focus.py::test_focus_does_not_move_to_invisible_widgets", "tests/test_focus.py::test_focus_moves_to_visible_widgets_inside_invisible_containers", "tests/test_focus.py::test_focus_chain_handles_inherited_visibility", "tests/test_focus.py::test_mouse_down_gives_focus", "tests/test_focus.py::test_mouse_up_does_not_give_focus", "tests/test_focus.py::test_focus_pseudo_class" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-28 14:03:23+00:00
mit
780
Textualize__textual-436
diff --git a/src/textual/app.py b/src/textual/app.py index 6a6e80272..2acc04ffe 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -521,6 +521,7 @@ class App(DOMNode): mount_event = events.Mount(sender=self) await self.dispatch_message(mount_event) + # TODO: don't override `self.console` here self.console = Console(file=sys.__stdout__) self.title = self._title self.refresh() diff --git a/src/textual/css/styles.py b/src/textual/css/styles.py index d1ecbdd91..43c724479 100644 --- a/src/textual/css/styles.py +++ b/src/textual/css/styles.py @@ -70,7 +70,7 @@ if TYPE_CHECKING: class RulesMap(TypedDict, total=False): """A typed dict for CSS rules. - Any key may be absent, indiciating that rule has not been set. + Any key may be absent, indicating that rule has not been set. Does not define composite rules, that is a rule that is made of a combination of other rules. diff --git a/src/textual/css/tokenize.py b/src/textual/css/tokenize.py index 3ccc8166f..7d5dbe3a0 100644 --- a/src/textual/css/tokenize.py +++ b/src/textual/css/tokenize.py @@ -11,7 +11,7 @@ DURATION = r"\d+\.?\d*(?:ms|s)" NUMBER = r"\-?\d+\.?\d*" COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|rgb\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)|rgba\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)" KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+" -TOKEN = "[a-zA-Z_-]+" +TOKEN = "[a-zA-Z][a-zA-Z0-9_-]*" STRING = r"\".*?\"" VARIABLE_REF = r"\$[a-zA-Z0-9_\-]+" diff --git a/src/textual/dom.py b/src/textual/dom.py index 7c0c0ba54..79f2cc796 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -278,6 +278,10 @@ class DOMNode(MessagePump): add_children(tree, self) return tree + @property + def displayed_children(self) -> list[DOMNode]: + return [child for child in self.children if child.display] + def get_pseudo_classes(self) -> Iterable[str]: """Get any pseudo classes applicable to this Node, e.g. hover, focus. diff --git a/src/textual/layouts/dock.py b/src/textual/layouts/dock.py index b507bbc67..f85e6de02 100644 --- a/src/textual/layouts/dock.py +++ b/src/textual/layouts/dock.py @@ -50,10 +50,9 @@ class DockLayout(Layout): def get_docks(self, parent: Widget) -> list[Dock]: groups: dict[str, list[Widget]] = defaultdict(list) - for child in parent.children: + for child in parent.displayed_children: assert isinstance(child, Widget) - if child.display: - groups[child.styles.dock].append(child) + groups[child.styles.dock].append(child) docks: list[Dock] = [] append_dock = docks.append for name, edge, z in parent.styles.docks: diff --git a/src/textual/layouts/horizontal.py b/src/textual/layouts/horizontal.py index 36fef9bd7..ba428c968 100644 --- a/src/textual/layouts/horizontal.py +++ b/src/textual/layouts/horizontal.py @@ -39,7 +39,9 @@ class HorizontalLayout(Layout): x = box_models[0].margin.left if box_models else 0 - for widget, box_model, margin in zip(parent.children, box_models, margins): + displayed_children = parent.displayed_children + + for widget, box_model, margin in zip(displayed_children, box_models, margins): content_width, content_height = box_model.size offset_y = widget.styles.align_height(content_height, parent_size.height) region = Region(x, offset_y, content_width, content_height) @@ -53,4 +55,4 @@ class HorizontalLayout(Layout): total_region = Region(0, 0, max_width, max_height) add_placement(WidgetPlacement(total_region, None, 0)) - return placements, set(parent.children) + return placements, set(displayed_children) diff --git a/src/textual/layouts/vertical.py b/src/textual/layouts/vertical.py index 2752c4445..196f7eb52 100644 --- a/src/textual/layouts/vertical.py +++ b/src/textual/layouts/vertical.py @@ -40,10 +40,13 @@ class VerticalLayout(Layout): y = box_models[0].margin.top if box_models else 0 - for widget, box_model, margin in zip(parent.children, box_models, margins): + displayed_children = parent.displayed_children + + for widget, box_model, margin in zip(displayed_children, box_models, margins): content_width, content_height = box_model.size offset_x = widget.styles.align_width(content_width, parent_size.width) region = Region(offset_x, y, content_width, content_height) + # TODO: it seems that `max_height` is not used? max_height = max(max_height, content_height) add_placement(WidgetPlacement(region, widget, 0)) y += region.height + margin @@ -54,4 +57,4 @@ class VerticalLayout(Layout): total_region = Region(0, 0, max_width, max_height) add_placement(WidgetPlacement(total_region, None, 0)) - return placements, set(parent.children) + return placements, set(displayed_children)
Textualize/textual
efafbdfcc16fdd3c7e9b5906fc7d8cc6e354f70e
diff --git a/tests/css/test_stylesheet.py b/tests/css/test_stylesheet.py new file mode 100644 index 000000000..87f27845d --- /dev/null +++ b/tests/css/test_stylesheet.py @@ -0,0 +1,49 @@ +from contextlib import nullcontext as does_not_raise +import pytest + +from textual.color import Color +from textual.css.stylesheet import Stylesheet, StylesheetParseError +from textual.css.tokenizer import TokenizeError + + [email protected]( + "css_value,expectation,expected_color", + [ + # Valid values: + ["red", does_not_raise(), Color(128, 0, 0)], + ["dark_cyan", does_not_raise(), Color(0, 175, 135)], + ["medium_turquoise", does_not_raise(), Color(95, 215, 215)], + ["turquoise4", does_not_raise(), Color(0, 135, 135)], + ["#ffcc00", does_not_raise(), Color(255, 204, 0)], + ["#ffcc0033", does_not_raise(), Color(255, 204, 0, 0.2)], + ["rgb(200,90,30)", does_not_raise(), Color(200, 90, 30)], + ["rgba(200,90,30,0.3)", does_not_raise(), Color(200, 90, 30, 0.3)], + # Some invalid ones: + ["coffee", pytest.raises(StylesheetParseError), None], # invalid color name + ["turquoise10", pytest.raises(StylesheetParseError), None], + ["turquoise 4", pytest.raises(StylesheetParseError), None], # space in it + ["1", pytest.raises(StylesheetParseError), None], # invalid value + ["()", pytest.raises(TokenizeError), None], # invalid tokens + # TODO: implement hex colors with 3 chars? @link https://devdocs.io/css/color_value + ["#09f", pytest.raises(TokenizeError), None], + # TODO: allow spaces in rgb/rgba expressions? + ["rgb(200, 90, 30)", pytest.raises(TokenizeError), None], + ["rgba(200,90,30, 0.4)", pytest.raises(TokenizeError), None], + ], +) +def test_color_property_parsing(css_value, expectation, expected_color): + stylesheet = Stylesheet() + css = """ + * { + background: ${COLOR}; + } + """.replace( + "${COLOR}", css_value + ) + + with expectation: + stylesheet.parse(css) + + if expected_color: + css_rule = stylesheet.rules[0] + assert css_rule.styles.background == expected_color diff --git a/tests/layouts/test_common_layout_features.py b/tests/layouts/test_common_layout_features.py new file mode 100644 index 000000000..e8cc5ee19 --- /dev/null +++ b/tests/layouts/test_common_layout_features.py @@ -0,0 +1,30 @@ +import pytest + +from textual.screen import Screen +from textual.widget import Widget + + [email protected]( + "layout,display,expected_in_displayed_children", + [ + ("dock", "block", True), + ("horizontal", "block", True), + ("vertical", "block", True), + ("dock", "none", False), + ("horizontal", "none", False), + ("vertical", "none", False), + ], +) +def test_nodes_take_display_property_into_account_when_they_display_their_children( + layout: str, display: str, expected_in_displayed_children: bool +): + widget = Widget(name="widget that might not be visible 🥷 ") + widget.styles.display = display + + screen = Screen() + screen.styles.layout = layout + screen.add_child(widget) + + displayed_children = screen.displayed_children + assert isinstance(displayed_children, list) + assert (widget in screen.displayed_children) is expected_in_displayed_children
`display: none` is being ignored in vertical and horizontal layouts Example app: ```python from textual.app import App from textual.widget import Widget class ButtonsApp(App): def on_load(self) -> None: self.bind("q", "quit") def on_mount(self): self.mount( Widget(classes={"no-display"}) ) ButtonsApp.run(css_file="buttons.scss", log="textual.log") ``` Example CSS: ```scss Widget.no-display { display: none; } ``` The widget is unexpectedly displayed.
0.0
efafbdfcc16fdd3c7e9b5906fc7d8cc6e354f70e
[ "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise4-expectation3-expected_color3]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[dock-block-True]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[horizontal-block-True]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[vertical-block-True]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[dock-none-False]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[horizontal-none-False]", "tests/layouts/test_common_layout_features.py::test_nodes_take_display_property_into_account_when_they_display_their_children[vertical-none-False]" ]
[ "tests/css/test_stylesheet.py::test_color_property_parsing[red-expectation0-expected_color0]", "tests/css/test_stylesheet.py::test_color_property_parsing[dark_cyan-expectation1-expected_color1]", "tests/css/test_stylesheet.py::test_color_property_parsing[medium_turquoise-expectation2-expected_color2]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc00-expectation4-expected_color4]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc0033-expectation5-expected_color5]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,90,30)-expectation6-expected_color6]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,0.3)-expectation7-expected_color7]", "tests/css/test_stylesheet.py::test_color_property_parsing[coffee-expectation8-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise10-expectation9-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise", "tests/css/test_stylesheet.py::test_color_property_parsing[1-expectation11-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[()-expectation12-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[#09f-expectation13-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30," ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-27 14:12:56+00:00
mit
781
Textualize__textual-441
diff --git a/src/textual/css/tokenize.py b/src/textual/css/tokenize.py index 3ccc8166f..7d5dbe3a0 100644 --- a/src/textual/css/tokenize.py +++ b/src/textual/css/tokenize.py @@ -11,7 +11,7 @@ DURATION = r"\d+\.?\d*(?:ms|s)" NUMBER = r"\-?\d+\.?\d*" COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|rgb\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)|rgba\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)" KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+" -TOKEN = "[a-zA-Z_-]+" +TOKEN = "[a-zA-Z][a-zA-Z0-9_-]*" STRING = r"\".*?\"" VARIABLE_REF = r"\$[a-zA-Z0-9_\-]+"
Textualize/textual
efafbdfcc16fdd3c7e9b5906fc7d8cc6e354f70e
diff --git a/tests/css/test_stylesheet.py b/tests/css/test_stylesheet.py new file mode 100644 index 000000000..87f27845d --- /dev/null +++ b/tests/css/test_stylesheet.py @@ -0,0 +1,49 @@ +from contextlib import nullcontext as does_not_raise +import pytest + +from textual.color import Color +from textual.css.stylesheet import Stylesheet, StylesheetParseError +from textual.css.tokenizer import TokenizeError + + [email protected]( + "css_value,expectation,expected_color", + [ + # Valid values: + ["red", does_not_raise(), Color(128, 0, 0)], + ["dark_cyan", does_not_raise(), Color(0, 175, 135)], + ["medium_turquoise", does_not_raise(), Color(95, 215, 215)], + ["turquoise4", does_not_raise(), Color(0, 135, 135)], + ["#ffcc00", does_not_raise(), Color(255, 204, 0)], + ["#ffcc0033", does_not_raise(), Color(255, 204, 0, 0.2)], + ["rgb(200,90,30)", does_not_raise(), Color(200, 90, 30)], + ["rgba(200,90,30,0.3)", does_not_raise(), Color(200, 90, 30, 0.3)], + # Some invalid ones: + ["coffee", pytest.raises(StylesheetParseError), None], # invalid color name + ["turquoise10", pytest.raises(StylesheetParseError), None], + ["turquoise 4", pytest.raises(StylesheetParseError), None], # space in it + ["1", pytest.raises(StylesheetParseError), None], # invalid value + ["()", pytest.raises(TokenizeError), None], # invalid tokens + # TODO: implement hex colors with 3 chars? @link https://devdocs.io/css/color_value + ["#09f", pytest.raises(TokenizeError), None], + # TODO: allow spaces in rgb/rgba expressions? + ["rgb(200, 90, 30)", pytest.raises(TokenizeError), None], + ["rgba(200,90,30, 0.4)", pytest.raises(TokenizeError), None], + ], +) +def test_color_property_parsing(css_value, expectation, expected_color): + stylesheet = Stylesheet() + css = """ + * { + background: ${COLOR}; + } + """.replace( + "${COLOR}", css_value + ) + + with expectation: + stylesheet.parse(css) + + if expected_color: + css_rule = stylesheet.rules[0] + assert css_rule.styles.background == expected_color
[textual][bug] CSS rule parsing fails when the name of the colour we pass contains a digit So while this is working correctly: ```css #my_widget { background: dark_cyan; } ``` ...this fails: ```css #my_widget { background: turquoise4; } ``` ...with the following error: ``` • failed to parse color 'turquoise'; • failed to parse 'turquoise' as a color; ``` (maybe just a regex that doesn't take into account the fact that colour names can include numbers?)
0.0
efafbdfcc16fdd3c7e9b5906fc7d8cc6e354f70e
[ "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise4-expectation3-expected_color3]" ]
[ "tests/css/test_stylesheet.py::test_color_property_parsing[red-expectation0-expected_color0]", "tests/css/test_stylesheet.py::test_color_property_parsing[dark_cyan-expectation1-expected_color1]", "tests/css/test_stylesheet.py::test_color_property_parsing[medium_turquoise-expectation2-expected_color2]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc00-expectation4-expected_color4]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc0033-expectation5-expected_color5]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,90,30)-expectation6-expected_color6]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,0.3)-expectation7-expected_color7]", "tests/css/test_stylesheet.py::test_color_property_parsing[coffee-expectation8-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise10-expectation9-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[turquoise", "tests/css/test_stylesheet.py::test_color_property_parsing[1-expectation11-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[()-expectation12-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[#09f-expectation13-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30," ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-04-28 09:27:13+00:00
mit
782
Textualize__textual-445
diff --git a/src/textual/css/_help_text.py b/src/textual/css/_help_text.py index 6dac2bee2..dc6cf9ff5 100644 --- a/src/textual/css/_help_text.py +++ b/src/textual/css/_help_text.py @@ -128,7 +128,32 @@ def _spacing_examples(property_name: str) -> ContextSpecificBullets: ) -def spacing_wrong_number_of_values( +def property_invalid_value_help_text( + property_name: str, context: StylingContext, *, suggested_property_name: str = None +) -> HelpText: + """Help text to show when the user supplies an invalid value for CSS property + property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the spacing property is being used in. + Keyword Args: + suggested_property_name (str | None): A suggested name for the property (e.g. "width" for "wdth"). Defaults to None. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + bullets = [] + if suggested_property_name: + suggested_property_name = _contextualize_property_name( + suggested_property_name, context + ) + bullets.append(Bullet(f'Did you mean "{suggested_property_name}"?')) + return HelpText(f"Invalid CSS property [i]{property_name}[/]", bullets=bullets) + + +def spacing_wrong_number_of_values_help_text( property_name: str, num_values_supplied: int, context: StylingContext, @@ -159,7 +184,7 @@ def spacing_wrong_number_of_values( ) -def spacing_invalid_value( +def spacing_invalid_value_help_text( property_name: str, context: StylingContext, ) -> HelpText: diff --git a/src/textual/css/_style_properties.py b/src/textual/css/_style_properties.py index 01b64b001..ecafefa86 100644 --- a/src/textual/css/_style_properties.py +++ b/src/textual/css/_style_properties.py @@ -22,7 +22,7 @@ from ._help_text import ( style_flags_property_help_text, ) from ._help_text import ( - spacing_wrong_number_of_values, + spacing_wrong_number_of_values_help_text, scalar_help_text, string_enum_help_text, color_property_help_text, @@ -415,7 +415,7 @@ class SpacingProperty: except ValueError as error: raise StyleValueError( str(error), - help_text=spacing_wrong_number_of_values( + help_text=spacing_wrong_number_of_values_help_text( property_name=self.name, num_values_supplied=len(spacing), context="inline", diff --git a/src/textual/css/_styles_builder.py b/src/textual/css/_styles_builder.py index 54b1a2d46..2c72e13d3 100644 --- a/src/textual/css/_styles_builder.py +++ b/src/textual/css/_styles_builder.py @@ -1,14 +1,15 @@ from __future__ import annotations -from typing import cast, Iterable, NoReturn +from functools import lru_cache +from typing import cast, Iterable, NoReturn, Sequence import rich.repr from ._error_tools import friendly_list from ._help_renderables import HelpText from ._help_text import ( - spacing_invalid_value, - spacing_wrong_number_of_values, + spacing_invalid_value_help_text, + spacing_wrong_number_of_values_help_text, scalar_help_text, color_property_help_text, string_enum_help_text, @@ -21,6 +22,7 @@ from ._help_text import ( offset_property_help_text, offset_single_axis_help_text, style_flags_property_help_text, + property_invalid_value_help_text, ) from .constants import ( VALID_ALIGN_HORIZONTAL, @@ -44,6 +46,7 @@ from ..color import Color, ColorParseError from .._duration import _duration_as_seconds from .._easing import EASING from ..geometry import Spacing, SpacingDimensions, clamp +from ..suggestions import get_suggestion def _join_tokens(tokens: Iterable[Token], joiner: str = "") -> str: @@ -84,26 +87,47 @@ class StylesBuilder: process_method = getattr(self, f"process_{rule_name}", None) if process_method is None: + suggested_property_name = self._get_suggested_property_name_for_rule( + declaration.name + ) self.error( declaration.name, declaration.token, - f"unknown declaration {declaration.name!r}", + property_invalid_value_help_text( + declaration.name, + "css", + suggested_property_name=suggested_property_name, + ), ) - else: - tokens = declaration.tokens + return - important = tokens[-1].name == "important" - if important: - tokens = tokens[:-1] - self.styles.important.add(rule_name) - try: - process_method(declaration.name, tokens) - except DeclarationError: - raise - except Exception as error: - self.error(declaration.name, declaration.token, str(error)) + tokens = declaration.tokens + + important = tokens[-1].name == "important" + if important: + tokens = tokens[:-1] + self.styles.important.add(rule_name) + try: + process_method(declaration.name, tokens) + except DeclarationError: + raise + except Exception as error: + self.error(declaration.name, declaration.token, str(error)) + + @lru_cache(maxsize=None) + def _get_processable_rule_names(self) -> Sequence[str]: + """ + Returns the list of CSS properties we can manage - + i.e. the ones for which we have a `process_[property name]` method - def _process_enum_multiple( + Returns: + Sequence[str]: All the "Python-ised" CSS property names this class can handle. + + Example: ("width", "background", "offset_x", ...) + """ + return [attr[8:] for attr in dir(self) if attr.startswith("process_")] + + def _get_process_enum_multiple( self, name: str, tokens: list[Token], valid_values: set[str], count: int ) -> tuple[str, ...]: """Generic code to process a declaration with two enumerations, like overflow: auto auto""" @@ -332,14 +356,20 @@ class StylesBuilder: try: append(int(value)) except ValueError: - self.error(name, token, spacing_invalid_value(name, context="css")) + self.error( + name, + token, + spacing_invalid_value_help_text(name, context="css"), + ) else: - self.error(name, token, spacing_invalid_value(name, context="css")) + self.error( + name, token, spacing_invalid_value_help_text(name, context="css") + ) if len(space) not in (1, 2, 4): self.error( name, tokens[0], - spacing_wrong_number_of_values( + spacing_wrong_number_of_values_help_text( name, num_values_supplied=len(space), context="css" ), ) @@ -348,7 +378,9 @@ class StylesBuilder: def _process_space_partial(self, name: str, tokens: list[Token]) -> None: """Process granular margin / padding declarations.""" if len(tokens) != 1: - self.error(name, tokens[0], spacing_invalid_value(name, context="css")) + self.error( + name, tokens[0], spacing_invalid_value_help_text(name, context="css") + ) _EDGE_SPACING_MAP = {"top": 0, "right": 1, "bottom": 2, "left": 3} token = tokens[0] @@ -356,7 +388,9 @@ class StylesBuilder: if token_name == "number": space = int(value) else: - self.error(name, token, spacing_invalid_value(name, context="css")) + self.error( + name, token, spacing_invalid_value_help_text(name, context="css") + ) style_name, _, edge = name.replace("-", "_").partition("_") current_spacing = cast( @@ -717,3 +751,18 @@ class StylesBuilder: process_content_align = process_align process_content_align_horizontal = process_align_horizontal process_content_align_vertical = process_align_vertical + + def _get_suggested_property_name_for_rule(self, rule_name: str) -> str | None: + """ + Returns a valid CSS property "Python" name, or None if no close matches could be found. + + Args: + rule_name (str): An invalid "Python-ised" CSS property (i.e. "offst_x" rather than "offst-x") + + Returns: + str | None: The closest valid "Python-ised" CSS property. + Returns `None` if no close matches could be found. + + Example: returns "background" for rule_name "bkgrund", "offset_x" for "ofset_x" + """ + return get_suggestion(rule_name, self._get_processable_rule_names()) diff --git a/src/textual/suggestions.py b/src/textual/suggestions.py new file mode 100644 index 000000000..e3fb20db2 --- /dev/null +++ b/src/textual/suggestions.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from difflib import get_close_matches +from typing import Sequence + + +def get_suggestion(word: str, possible_words: Sequence[str]) -> str | None: + """ + Returns a close match of `word` amongst `possible_words`. + + Args: + word (str): The word we want to find a close match for + possible_words (Sequence[str]): The words amongst which we want to find a close match + + Returns: + str | None: The closest match amongst the `possible_words`. Returns `None` if no close matches could be found. + + Example: returns "red" for word "redu" and possible words ("yellow", "red") + """ + possible_matches = get_close_matches(word, possible_words, n=1) + return None if not possible_matches else possible_matches[0] + + +def get_suggestions(word: str, possible_words: Sequence[str], count: int) -> list[str]: + """ + Returns a list of up to `count` matches of `word` amongst `possible_words`. + + Args: + word (str): The word we want to find a close match for + possible_words (Sequence[str]): The words amongst which we want to find close matches + + Returns: + list[str]: The closest matches amongst the `possible_words`, from the closest to the least close. + Returns an empty list if no close matches could be found. + + Example: returns ["yellow", "ellow"] for word "yllow" and possible words ("yellow", "red", "ellow") + """ + return get_close_matches(word, possible_words, n=count)
Textualize/textual
6fba64facefbdf9a202011fa96f1852f59371258
diff --git a/tests/css/test_help_text.py b/tests/css/test_help_text.py index 5c34c3974..f5818a11d 100644 --- a/tests/css/test_help_text.py +++ b/tests/css/test_help_text.py @@ -1,10 +1,22 @@ import pytest from tests.utilities.render import render -from textual.css._help_text import spacing_wrong_number_of_values, spacing_invalid_value, scalar_help_text, \ - string_enum_help_text, color_property_help_text, border_property_help_text, layout_property_help_text, \ - docks_property_help_text, dock_property_help_text, fractional_property_help_text, offset_property_help_text, \ - align_help_text, offset_single_axis_help_text, style_flags_property_help_text +from textual.css._help_text import ( + spacing_wrong_number_of_values_help_text, + spacing_invalid_value_help_text, + scalar_help_text, + string_enum_help_text, + color_property_help_text, + border_property_help_text, + layout_property_help_text, + docks_property_help_text, + dock_property_help_text, + fractional_property_help_text, + offset_property_help_text, + align_help_text, + offset_single_axis_help_text, + style_flags_property_help_text, +) @pytest.fixture(params=["css", "inline"]) @@ -15,22 +27,24 @@ def styling_context(request): def test_help_text_examples_are_contextualized(): """Ensure that if the user is using CSS, they see CSS-specific examples and if they're using inline styles they see inline-specific examples.""" - rendered_inline = render(spacing_invalid_value("padding", "inline")) + rendered_inline = render(spacing_invalid_value_help_text("padding", "inline")) assert "widget.styles.padding" in rendered_inline - rendered_css = render(spacing_invalid_value("padding", "css")) + rendered_css = render(spacing_invalid_value_help_text("padding", "css")) assert "padding:" in rendered_css def test_spacing_wrong_number_of_values(styling_context): - rendered = render(spacing_wrong_number_of_values("margin", 3, styling_context)) + rendered = render( + spacing_wrong_number_of_values_help_text("margin", 3, styling_context) + ) assert "Invalid number of values" in rendered assert "margin" in rendered assert "3" in rendered def test_spacing_invalid_value(styling_context): - rendered = render(spacing_invalid_value("padding", styling_context)) + rendered = render(spacing_invalid_value_help_text("padding", styling_context)) assert "Invalid value for" in rendered assert "padding" in rendered @@ -47,7 +61,9 @@ def test_scalar_help_text(styling_context): def test_string_enum_help_text(styling_context): - rendered = render(string_enum_help_text("display", ["none", "hidden"], styling_context)) + rendered = render( + string_enum_help_text("display", ["none", "hidden"], styling_context) + ) assert "Invalid value for" in rendered # Ensure property name is mentioned @@ -113,7 +129,9 @@ def test_offset_single_axis_help_text(): def test_style_flags_property_help_text(styling_context): - rendered = render(style_flags_property_help_text("text-style", "notavalue b", styling_context)) + rendered = render( + style_flags_property_help_text("text-style", "notavalue b", styling_context) + ) assert "Invalid value" in rendered assert "notavalue" in rendered diff --git a/tests/css/test_stylesheet.py b/tests/css/test_stylesheet.py index 4544d1e1d..202935a3d 100644 --- a/tests/css/test_stylesheet.py +++ b/tests/css/test_stylesheet.py @@ -1,7 +1,10 @@ from contextlib import nullcontext as does_not_raise +from typing import Any + import pytest from textual.color import Color +from textual.css._help_renderables import HelpText from textual.css.stylesheet import Stylesheet, StylesheetParseError from textual.css.tokenizer import TokenizeError @@ -53,3 +56,50 @@ def test_color_property_parsing(css_value, expectation, expected_color): if expected_color: css_rule = stylesheet.rules[0] assert css_rule.styles.background == expected_color + + [email protected]( + "css_property_name,expected_property_name_suggestion", + [ + ["backgroundu", "background"], + ["bckgroundu", "background"], + ["ofset-x", "offset-x"], + ["ofst_y", "offset-y"], + ["colr", "color"], + ["colour", "color"], + ["wdth", "width"], + ["wth", "width"], + ["wh", None], + ["xkcd", None], + ], +) +def test_did_you_mean_for_css_property_names( + css_property_name: str, expected_property_name_suggestion +): + stylesheet = Stylesheet() + css = """ + * { + border: blue; + ${PROPERTY}: red; + } + """.replace( + "${PROPERTY}", css_property_name + ) + + stylesheet.add_source(css) + with pytest.raises(StylesheetParseError) as err: + stylesheet.parse() + + _, help_text = err.value.errors.rules[0].errors[0] # type: Any, HelpText + displayed_css_property_name = css_property_name.replace("_", "-") + assert ( + help_text.summary == f"Invalid CSS property [i]{displayed_css_property_name}[/]" + ) + + expected_bullets_length = 1 if expected_property_name_suggestion else 0 + assert len(help_text.bullets) == expected_bullets_length + if expected_property_name_suggestion is not None: + expected_suggestion_message = ( + f'Did you mean "{expected_property_name_suggestion}"?' + ) + assert help_text.bullets[0].markup == expected_suggestion_message diff --git a/tests/test_suggestions.py b/tests/test_suggestions.py new file mode 100644 index 000000000..8faedcbaf --- /dev/null +++ b/tests/test_suggestions.py @@ -0,0 +1,35 @@ +import pytest + +from textual.suggestions import get_suggestion, get_suggestions + + [email protected]( + "word, possible_words, expected_result", + ( + ["background", ("background",), "background"], + ["backgroundu", ("background",), "background"], + ["bkgrund", ("background",), "background"], + ["llow", ("background",), None], + ["llow", ("background", "yellow"), "yellow"], + ["yllow", ("background", "yellow", "ellow"), "yellow"], + ), +) +def test_get_suggestion(word, possible_words, expected_result): + assert get_suggestion(word, possible_words) == expected_result + + [email protected]( + "word, possible_words, count, expected_result", + ( + ["background", ("background",), 1, ["background"]], + ["backgroundu", ("background",), 1, ["background"]], + ["bkgrund", ("background",), 1, ["background"]], + ["llow", ("background",), 1, []], + ["llow", ("background", "yellow"), 1, ["yellow"]], + ["yllow", ("background", "yellow", "ellow"), 1, ["yellow"]], + ["yllow", ("background", "yellow", "ellow"), 2, ["yellow", "ellow"]], + ["yllow", ("background", "yellow", "red"), 2, ["yellow"]], + ), +) +def test_get_suggestions(word, possible_words, count, expected_result): + assert get_suggestions(word, possible_words, count) == expected_result
Did you Mean? I'm a big fan of when software detects typos and offers suggestions. We should have a function in the project which uses [Levenshtein Word distance](https://en.wikipedia.org/wiki/Levenshtein_distance) to offer suggestions when a symbol is not found. The first application of this should probably be CSS declarations. i.e. if I use the UK spelling of "colour" it the error would contain a message to the effect of `Did you mean "color" ?` However I would imagine there are multiple uses for this. IIRC there is a routine in the standard library that already does this. Might want to google for that.
0.0
6fba64facefbdf9a202011fa96f1852f59371258
[ "tests/css/test_help_text.py::test_help_text_examples_are_contextualized", "tests/css/test_help_text.py::test_spacing_wrong_number_of_values[css]", "tests/css/test_help_text.py::test_spacing_wrong_number_of_values[inline]", "tests/css/test_help_text.py::test_spacing_invalid_value[css]", "tests/css/test_help_text.py::test_spacing_invalid_value[inline]", "tests/css/test_help_text.py::test_scalar_help_text[css]", "tests/css/test_help_text.py::test_scalar_help_text[inline]", "tests/css/test_help_text.py::test_string_enum_help_text[css]", "tests/css/test_help_text.py::test_string_enum_help_text[inline]", "tests/css/test_help_text.py::test_color_property_help_text[css]", "tests/css/test_help_text.py::test_color_property_help_text[inline]", "tests/css/test_help_text.py::test_border_property_help_text[css]", "tests/css/test_help_text.py::test_border_property_help_text[inline]", "tests/css/test_help_text.py::test_layout_property_help_text[css]", "tests/css/test_help_text.py::test_layout_property_help_text[inline]", "tests/css/test_help_text.py::test_docks_property_help_text[css]", "tests/css/test_help_text.py::test_docks_property_help_text[inline]", "tests/css/test_help_text.py::test_dock_property_help_text[css]", "tests/css/test_help_text.py::test_dock_property_help_text[inline]", "tests/css/test_help_text.py::test_fractional_property_help_text[css]", "tests/css/test_help_text.py::test_fractional_property_help_text[inline]", "tests/css/test_help_text.py::test_offset_property_help_text[css]", "tests/css/test_help_text.py::test_offset_property_help_text[inline]", "tests/css/test_help_text.py::test_align_help_text", "tests/css/test_help_text.py::test_offset_single_axis_help_text", "tests/css/test_help_text.py::test_style_flags_property_help_text[css]", "tests/css/test_help_text.py::test_style_flags_property_help_text[inline]", "tests/css/test_stylesheet.py::test_color_property_parsing[transparent-expectation0-expected_color0]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_red-expectation1-expected_color1]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_bright_magenta-expectation2-expected_color2]", "tests/css/test_stylesheet.py::test_color_property_parsing[red-expectation3-expected_color3]", "tests/css/test_stylesheet.py::test_color_property_parsing[lime-expectation4-expected_color4]", "tests/css/test_stylesheet.py::test_color_property_parsing[coral-expectation5-expected_color5]", "tests/css/test_stylesheet.py::test_color_property_parsing[aqua-expectation6-expected_color6]", "tests/css/test_stylesheet.py::test_color_property_parsing[deepskyblue-expectation7-expected_color7]", "tests/css/test_stylesheet.py::test_color_property_parsing[rebeccapurple-expectation8-expected_color8]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc00-expectation9-expected_color9]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc0033-expectation10-expected_color10]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,90,30)-expectation11-expected_color11]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,0.3)-expectation12-expected_color12]", "tests/css/test_stylesheet.py::test_color_property_parsing[coffee-expectation13-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_dark_cyan-expectation14-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[red", "tests/css/test_stylesheet.py::test_color_property_parsing[1-expectation16-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[()-expectation17-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[#09f-expectation18-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[backgroundu-background]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[bckgroundu-background]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[ofset-x-offset-x]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[ofst_y-offset-y]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[colr-color]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[colour-color]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wdth-width]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wth-width]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wh-None]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[xkcd-None]", "tests/test_suggestions.py::test_get_suggestion[background-possible_words0-background]", "tests/test_suggestions.py::test_get_suggestion[backgroundu-possible_words1-background]", "tests/test_suggestions.py::test_get_suggestion[bkgrund-possible_words2-background]", "tests/test_suggestions.py::test_get_suggestion[llow-possible_words3-None]", "tests/test_suggestions.py::test_get_suggestion[llow-possible_words4-yellow]", "tests/test_suggestions.py::test_get_suggestion[yllow-possible_words5-yellow]", "tests/test_suggestions.py::test_get_suggestions[background-possible_words0-1-expected_result0]", "tests/test_suggestions.py::test_get_suggestions[backgroundu-possible_words1-1-expected_result1]", "tests/test_suggestions.py::test_get_suggestions[bkgrund-possible_words2-1-expected_result2]", "tests/test_suggestions.py::test_get_suggestions[llow-possible_words3-1-expected_result3]", "tests/test_suggestions.py::test_get_suggestions[llow-possible_words4-1-expected_result4]", "tests/test_suggestions.py::test_get_suggestions[yllow-possible_words5-1-expected_result5]", "tests/test_suggestions.py::test_get_suggestions[yllow-possible_words6-2-expected_result6]", "tests/test_suggestions.py::test_get_suggestions[yllow-possible_words7-2-expected_result7]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-29 09:34:12+00:00
mit
783
Textualize__textual-459
diff --git a/poetry.lock b/poetry.lock index 3182e7961..98961e8e7 100644 --- a/poetry.lock +++ b/poetry.lock @@ -205,7 +205,7 @@ python-versions = ">=3.7" [[package]] name = "ghp-import" -version = "2.0.2" +version = "2.1.0" description = "Copy your docs directly to the gh-pages branch." category = "dev" optional = false @@ -219,7 +219,7 @@ dev = ["twine", "markdown", "flake8", "wheel"] [[package]] name = "identify" -version = "2.4.12" +version = "2.5.0" description = "File identification library for Python" category = "dev" optional = false @@ -263,7 +263,7 @@ python-versions = "*" [[package]] name = "jinja2" -version = "3.1.1" +version = "3.1.2" description = "A very fast and expressive template engine." category = "dev" optional = false @@ -496,22 +496,22 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" [[package]] name = "pygments" -version = "2.11.2" +version = "2.12.0" description = "Pygments is a syntax highlighting package written in Python." category = "main" optional = false -python-versions = ">=3.5" +python-versions = ">=3.6" [[package]] name = "pymdown-extensions" -version = "9.3" +version = "9.4" description = "Extension pack for Python Markdown." category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] -Markdown = ">=3.2" +markdown = ">=3.2" [[package]] name = "pyparsing" @@ -641,16 +641,16 @@ pyyaml = "*" [[package]] name = "rich" -version = "12.1.0" +version = "12.3.0" description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" category = "main" optional = false -python-versions = ">=3.6.2,<4.0.0" +python-versions = ">=3.6.3,<4.0.0" [package.dependencies] commonmark = ">=0.9.0,<0.10.0" pygments = ">=2.6.0,<3.0.0" -typing-extensions = {version = ">=3.7.4,<5.0", markers = "python_version < \"3.9\""} +typing-extensions = {version = ">=4.0.0,<5.0", markers = "python_version < \"3.9\""} [package.extras] jupyter = ["ipywidgets (>=7.5.1,<8.0.0)"] @@ -700,11 +700,11 @@ python-versions = ">=3.6" [[package]] name = "typing-extensions" -version = "3.10.0.2" -description = "Backported and Experimental Type Hints for Python 3.5+" +version = "4.2.0" +description = "Backported and Experimental Type Hints for Python 3.7+" category = "main" optional = false -python-versions = "*" +python-versions = ">=3.7" [[package]] name = "virtualenv" @@ -764,7 +764,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "256c1d6571a11bf4b80d0eba16d9e39bf2965c4436281c3ec40033cca54aa098" +content-hash = "2f50b8219bfdf683dabf54b0a33636f27712a6ecccc1f8ce2695e1f7793f9969" [metadata.files] aiohttp = [ @@ -1027,12 +1027,12 @@ frozenlist = [ {file = "frozenlist-1.3.0.tar.gz", hash = "sha256:ce6f2ba0edb7b0c1d8976565298ad2deba6f8064d2bebb6ffce2ca896eb35b0b"}, ] ghp-import = [ - {file = "ghp-import-2.0.2.tar.gz", hash = "sha256:947b3771f11be850c852c64b561c600fdddf794bab363060854c1ee7ad05e071"}, - {file = "ghp_import-2.0.2-py3-none-any.whl", hash = "sha256:5f8962b30b20652cdffa9c5a9812f7de6bcb56ec475acac579807719bf242c46"}, + {file = "ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343"}, + {file = "ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619"}, ] identify = [ - {file = "identify-2.4.12-py2.py3-none-any.whl", hash = "sha256:5f06b14366bd1facb88b00540a1de05b69b310cbc2654db3c7e07fa3a4339323"}, - {file = "identify-2.4.12.tar.gz", hash = "sha256:3f3244a559290e7d3deb9e9adc7b33594c1bc85a9dd82e0f1be519bf12a1ec17"}, + {file = "identify-2.5.0-py2.py3-none-any.whl", hash = "sha256:3acfe15a96e4272b4ec5662ee3e231ceba976ef63fd9980ed2ce9cc415df393f"}, + {file = "identify-2.5.0.tar.gz", hash = "sha256:c83af514ea50bf2be2c4a3f2fb349442b59dc87284558ae9ff54191bff3541d2"}, ] idna = [ {file = "idna-3.3-py3-none-any.whl", hash = "sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff"}, @@ -1047,8 +1047,8 @@ iniconfig = [ {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, ] jinja2 = [ - {file = "Jinja2-3.1.1-py3-none-any.whl", hash = "sha256:539835f51a74a69f41b848a9645dbdc35b4f20a3b601e2d9a7e22947b15ff119"}, - {file = "Jinja2-3.1.1.tar.gz", hash = "sha256:640bed4bb501cbd17194b3cace1dc2126f5b619cf068a726b98192a0fde74ae9"}, + {file = "Jinja2-3.1.2-py3-none-any.whl", hash = "sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61"}, + {file = "Jinja2-3.1.2.tar.gz", hash = "sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852"}, ] markdown = [ {file = "Markdown-3.3.6-py3-none-any.whl", hash = "sha256:9923332318f843411e9932237530df53162e29dc7a4e2b91e35764583c46c9a3"}, @@ -1236,12 +1236,12 @@ py = [ {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, ] pygments = [ - {file = "Pygments-2.11.2-py3-none-any.whl", hash = "sha256:44238f1b60a76d78fc8ca0528ee429702aae011c265fe6a8dd8b63049ae41c65"}, - {file = "Pygments-2.11.2.tar.gz", hash = "sha256:4e426f72023d88d03b2fa258de560726ce890ff3b630f88c21cbb8b2503b8c6a"}, + {file = "Pygments-2.12.0-py3-none-any.whl", hash = "sha256:dc9c10fb40944260f6ed4c688ece0cd2048414940f1cea51b8b226318411c519"}, + {file = "Pygments-2.12.0.tar.gz", hash = "sha256:5eb116118f9612ff1ee89ac96437bb6b49e8f04d8a13b514ba26f620208e26eb"}, ] pymdown-extensions = [ - {file = "pymdown-extensions-9.3.tar.gz", hash = "sha256:a80553b243d3ed2d6c27723bcd64ca9887e560e6f4808baa96f36e93061eaf90"}, - {file = "pymdown_extensions-9.3-py3-none-any.whl", hash = "sha256:b37461a181c1c8103cfe1660081726a0361a8294cbfda88e5b02cefe976f0546"}, + {file = "pymdown_extensions-9.4-py3-none-any.whl", hash = "sha256:5b7432456bf555ce2b0ab3c2439401084cda8110f24f6b3ecef952b8313dfa1b"}, + {file = "pymdown_extensions-9.4.tar.gz", hash = "sha256:1baa22a60550f731630474cad28feb0405c8101f1a7ddc3ec0ed86ee510bcc43"}, ] pyparsing = [ {file = "pyparsing-3.0.8-py3-none-any.whl", hash = "sha256:ef7b523f6356f763771559412c0d7134753f037822dad1b16945b7b846f7ad06"}, @@ -1312,8 +1312,8 @@ pyyaml-env-tag = [ {file = "pyyaml_env_tag-0.1.tar.gz", hash = "sha256:70092675bda14fdec33b31ba77e7543de9ddc88f2e5b99160396572d11525bdb"}, ] rich = [ - {file = "rich-12.1.0-py3-none-any.whl", hash = "sha256:b60ff99f4ff7e3d1d37444dee2b22fdd941c622dbc37841823ec1ce7f058b263"}, - {file = "rich-12.1.0.tar.gz", hash = "sha256:198ae15807a7c1bf84ceabf662e902731bf8f874f9e775e2289cab02bb6a4e30"}, + {file = "rich-12.3.0-py3-none-any.whl", hash = "sha256:0eb63013630c6ee1237e0e395d51cb23513de6b5531235e33889e8842bdf3a6f"}, + {file = "rich-12.3.0.tar.gz", hash = "sha256:7e8700cda776337036a712ff0495b04052fb5f957c7dfb8df997f88350044b64"}, ] six = [ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, @@ -1396,9 +1396,8 @@ typed-ast = [ {file = "typed_ast-1.5.3.tar.gz", hash = "sha256:27f25232e2dd0edfe1f019d6bfaaf11e86e657d9bdb7b0956db95f560cceb2b3"}, ] typing-extensions = [ - {file = "typing_extensions-3.10.0.2-py2-none-any.whl", hash = "sha256:d8226d10bc02a29bcc81df19a26e56a9647f8b0a6d4a83924139f4a8b01f17b7"}, - {file = "typing_extensions-3.10.0.2-py3-none-any.whl", hash = "sha256:f1d25edafde516b146ecd0613dabcc61409817af4766fbbcfb8d1ad4ec441a34"}, - {file = "typing_extensions-3.10.0.2.tar.gz", hash = "sha256:49f75d16ff11f1cd258e1b988ccff82a3ca5570217d7ad8c5f48205dd99a677e"}, + {file = "typing_extensions-4.2.0-py3-none-any.whl", hash = "sha256:6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708"}, + {file = "typing_extensions-4.2.0.tar.gz", hash = "sha256:f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376"}, ] virtualenv = [ {file = "virtualenv-20.14.1-py2.py3-none-any.whl", hash = "sha256:e617f16e25b42eb4f6e74096b9c9e37713cf10bf30168fb4a739f3fa8f898a3a"}, diff --git a/pyproject.toml b/pyproject.toml index 3b110a12d..388724741 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,12 +22,12 @@ textual = "textual.cli.cli:run" [tool.poetry.dependencies] python = "^3.7" -rich = "^12.0.0" +rich = "^12.3.0" #rich = {git = "[email protected]:willmcgugan/rich", rev = "link-id"} -typing-extensions = { version = "^3.10.0", python = "<3.8" } click = "8.1.2" importlib-metadata = "^4.11.3" +typing-extensions = { version = "^4.0.0", python = "<3.8" } [tool.poetry.dev-dependencies] pytest = "^6.2.3" diff --git a/sandbox/uber.css b/sandbox/uber.css index 195c06593..517aec8d2 100644 --- a/sandbox/uber.css +++ b/sandbox/uber.css @@ -7,5 +7,6 @@ .list-item { height: 8; - background: darkblue; + color: #12a0; + background: #ffffff00; } diff --git a/sandbox/uber.py b/sandbox/uber.py index 91835343b..0eb90cdbd 100644 --- a/sandbox/uber.py +++ b/sandbox/uber.py @@ -80,7 +80,7 @@ class BasicApp(App): self.focused.display = not self.focused.display def action_toggle_border(self): - self.focused.styles.border = ("solid", "red") + self.focused.styles.border_top = ("solid", "invalid-color") app = BasicApp(css_file="uber.css", log="textual.log", log_verbosity=1) diff --git a/src/textual/color.py b/src/textual/color.py index f6e5be1c3..73adbabf3 100644 --- a/src/textual/color.py +++ b/src/textual/color.py @@ -1,7 +1,7 @@ """ Manages Color in Textual. -All instances where the developer is presented with a color should use this class. The only +All instances where the developer is presented with a color should use this class. The only exception should be when passing things to a Rich renderable, which will need to use the `rich_color` attribute to perform a conversion. @@ -54,6 +54,8 @@ class Lab(NamedTuple): RE_COLOR = re.compile( r"""^ +\#([0-9a-fA-F]{3})$| +\#([0-9a-fA-F]{4})$| \#([0-9a-fA-F]{6})$| \#([0-9a-fA-F]{8})$| rgb\((\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*)\)$| @@ -62,7 +64,7 @@ rgba\((\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*)\)$ re.VERBOSE, ) -# Fast way to split a string of 8 characters in to 3 pairs of 2 characters +# Fast way to split a string of 6 characters in to 3 pairs of 2 characters split_pairs3: Callable[[str], tuple[str, str, str]] = itemgetter( slice(0, 2), slice(2, 4), slice(4, 6) ) @@ -264,9 +266,27 @@ class Color(NamedTuple): color_match = RE_COLOR.match(color_text) if color_match is None: raise ColorParseError(f"failed to parse {color_text!r} as a color") - rgb_hex, rgba_hex, rgb, rgba = color_match.groups() - - if rgb_hex is not None: + ( + rgb_hex_triple, + rgb_hex_quad, + rgb_hex, + rgba_hex, + rgb, + rgba, + ) = color_match.groups() + + if rgb_hex_triple is not None: + r, g, b = rgb_hex_triple + color = cls(int(f"{r}{r}", 16), int(f"{g}{g}", 16), int(f"{b}{b}", 16)) + elif rgb_hex_quad is not None: + r, g, b, a = rgb_hex_quad + color = cls( + int(f"{r}{r}", 16), + int(f"{g}{g}", 16), + int(f"{b}{b}", 16), + int(f"{a}{a}", 16) / 255.0, + ) + elif rgb_hex is not None: r, g, b = [int(pair, 16) for pair in split_pairs3(rgb_hex)] color = cls(r, g, b, 1.0) elif rgba_hex is not None: diff --git a/src/textual/css/_style_properties.py b/src/textual/css/_style_properties.py index ecafefa86..19f402bb4 100644 --- a/src/textual/css/_style_properties.py +++ b/src/textual/css/_style_properties.py @@ -103,6 +103,7 @@ class ScalarProperty: StyleValueError: If the value is of an invalid type, uses an invalid unit, or cannot be parsed for any other reason. """ + _rich_traceback_omit = True if value is None: obj.clear_rule(self.name) obj.refresh(layout=True) @@ -186,6 +187,7 @@ class BoxProperty: Raises: StyleSyntaxError: If the string supplied for the color has invalid syntax. """ + _rich_traceback_omit = True if border is None: if obj.clear_rule(self.name): obj.refresh() @@ -310,6 +312,7 @@ class BorderProperty: Raises: StyleValueError: When the supplied ``tuple`` is not of valid length (1, 2, or 4). """ + _rich_traceback_omit = True top, right, bottom, left = self._properties if border is None: clear_rule = obj.clear_rule @@ -405,7 +408,7 @@ class SpacingProperty: ValueError: When the value is malformed, e.g. a ``tuple`` with a length that is not 1, 2, or 4. """ - + _rich_traceback_omit = True if spacing is None: if obj.clear_rule(self.name): obj.refresh(layout=True) @@ -455,6 +458,7 @@ class DocksProperty: obj (Styles): The ``Styles`` object. docks (Iterable[DockGroup]): Iterable of DockGroups """ + _rich_traceback_omit = True if docks is None: if obj.clear_rule("docks"): obj.refresh(layout=True) @@ -489,6 +493,7 @@ class DockProperty: obj (Styles): The ``Styles`` object dock_name (str | None): The name of the dock to attach this widget to """ + _rich_traceback_omit = True if obj.set_rule("dock", dock_name): obj.refresh(layout=True) @@ -525,6 +530,7 @@ class LayoutProperty: MissingLayout, ) # Prevents circular import + _rich_traceback_omit = True if layout is None: if obj.clear_rule("layout"): obj.refresh(layout=True) @@ -583,6 +589,7 @@ class OffsetProperty: ScalarParseError: If any of the string values supplied in the 2-tuple cannot be parsed into a Scalar. For example, if you specify a non-existent unit. """ + _rich_traceback_omit = True if offset is None: if obj.clear_rule(self.name): obj.refresh(layout=True) @@ -649,7 +656,7 @@ class StringEnumProperty: Raises: StyleValueError: If the value is not in the set of valid values. """ - + _rich_traceback_omit = True if value is None: if obj.clear_rule(self.name): obj.refresh(layout=self._layout) @@ -695,7 +702,7 @@ class NameProperty: Raises: StyleTypeError: If the value is not a ``str``. """ - + _rich_traceback_omit = True if name is None: if obj.clear_rule(self.name): obj.refresh(layout=True) @@ -716,7 +723,7 @@ class NameListProperty: return cast("tuple[str, ...]", obj.get_rule(self.name, ())) def __set__(self, obj: StylesBase, names: str | tuple[str] | None = None): - + _rich_traceback_omit = True if names is None: if obj.clear_rule(self.name): obj.refresh(layout=True) @@ -765,7 +772,7 @@ class ColorProperty: Raises: ColorParseError: When the color string is invalid. """ - + _rich_traceback_omit = True if color is None: if obj.clear_rule(self.name): obj.refresh() @@ -817,6 +824,7 @@ class StyleFlagsProperty: Raises: StyleValueError: If the value is an invalid style flag """ + _rich_traceback_omit = True if style_flags is None: if obj.clear_rule(self.name): obj.refresh() @@ -859,6 +867,7 @@ class TransitionsProperty: return obj.get_rule("transitions", {}) def __set__(self, obj: Styles, transitions: dict[str, Transition] | None) -> None: + _rich_traceback_omit = True if transitions is None: obj.clear_rule("transitions") else: @@ -896,6 +905,7 @@ class FractionalProperty: value (float|str|None): The value to set as a float between 0 and 1, or as a percentage string such as '10%'. """ + _rich_traceback_omit = True name = self.name if value is None: if obj.clear_rule(name): diff --git a/src/textual/css/tokenize.py b/src/textual/css/tokenize.py index 7d5dbe3a0..7076d390a 100644 --- a/src/textual/css/tokenize.py +++ b/src/textual/css/tokenize.py @@ -9,7 +9,7 @@ COMMENT_START = r"\/\*" SCALAR = r"\-?\d+\.?\d*(?:fr|%|w|h|vw|vh)" DURATION = r"\d+\.?\d*(?:ms|s)" NUMBER = r"\-?\d+\.?\d*" -COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|rgb\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)|rgba\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)" +COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|\#[0-9a-fA-F]{4}|\#[0-9a-fA-F]{3}|rgb\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)|rgba\(\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*,\-?\d+\.?\d*\)" KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+" TOKEN = "[a-zA-Z][a-zA-Z0-9_-]*" STRING = r"\".*?\""
Textualize/textual
2841527ca67d373ae2e32970f19b0b2b6ddb87f0
diff --git a/tests/css/test_stylesheet.py b/tests/css/test_stylesheet.py index 202935a3d..e9042675b 100644 --- a/tests/css/test_stylesheet.py +++ b/tests/css/test_stylesheet.py @@ -32,8 +32,6 @@ from textual.css.tokenizer import TokenizeError ["red 4", pytest.raises(StylesheetParseError), None], # space in it ["1", pytest.raises(StylesheetParseError), None], # invalid value ["()", pytest.raises(TokenizeError), None], # invalid tokens - # TODO: implement hex colors with 3 chars? @link https://devdocs.io/css/color_value - ["#09f", pytest.raises(TokenizeError), None], # TODO: allow spaces in rgb/rgba expressions? ["rgb(200, 90, 30)", pytest.raises(TokenizeError), None], ["rgba(200,90,30, 0.4)", pytest.raises(TokenizeError), None], diff --git a/tests/test_color.py b/tests/test_color.py index 26f65f724..e1db3922b 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -93,6 +93,8 @@ def test_color_blend(): ("#000000", Color(0, 0, 0, 1.0)), ("#ffffff", Color(255, 255, 255, 1.0)), ("#FFFFFF", Color(255, 255, 255, 1.0)), + ("#fab", Color(255, 170, 187, 1.0)), # #ffaabb + ("#fab0", Color(255, 170, 187, .0)), # #ffaabb00 ("#020304ff", Color(2, 3, 4, 1.0)), ("#02030400", Color(2, 3, 4, 0.0)), ("#0203040f", Color(2, 3, 4, 0.058823529411764705)),
Add 3 and 8 digit hex colors to Color and CSS parser For 3 digits colors, each digit is repeat. Thus #17a is the same as #1177aa For 8 digit colors, the last two hex digits translate to the alpha component in a color, which should be 0 - 1, for hex 0 - FF.
0.0
2841527ca67d373ae2e32970f19b0b2b6ddb87f0
[ "tests/test_color.py::test_color_parse[#fab-expected3]", "tests/test_color.py::test_color_parse[#fab0-expected4]" ]
[ "tests/css/test_stylesheet.py::test_color_property_parsing[transparent-expectation0-expected_color0]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_red-expectation1-expected_color1]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_bright_magenta-expectation2-expected_color2]", "tests/css/test_stylesheet.py::test_color_property_parsing[red-expectation3-expected_color3]", "tests/css/test_stylesheet.py::test_color_property_parsing[lime-expectation4-expected_color4]", "tests/css/test_stylesheet.py::test_color_property_parsing[coral-expectation5-expected_color5]", "tests/css/test_stylesheet.py::test_color_property_parsing[aqua-expectation6-expected_color6]", "tests/css/test_stylesheet.py::test_color_property_parsing[deepskyblue-expectation7-expected_color7]", "tests/css/test_stylesheet.py::test_color_property_parsing[rebeccapurple-expectation8-expected_color8]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc00-expectation9-expected_color9]", "tests/css/test_stylesheet.py::test_color_property_parsing[#ffcc0033-expectation10-expected_color10]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,90,30)-expectation11-expected_color11]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,0.3)-expectation12-expected_color12]", "tests/css/test_stylesheet.py::test_color_property_parsing[coffee-expectation13-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[ansi_dark_cyan-expectation14-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[red", "tests/css/test_stylesheet.py::test_color_property_parsing[1-expectation16-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[()-expectation17-None]", "tests/css/test_stylesheet.py::test_color_property_parsing[rgb(200,", "tests/css/test_stylesheet.py::test_color_property_parsing[rgba(200,90,30,", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[backgroundu-background]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[bckgroundu-background]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[ofset-x-offset-x]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[ofst_y-offset-y]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[colr-color]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[colour-color]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wdth-width]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wth-width]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[wh-None]", "tests/css/test_stylesheet.py::test_did_you_mean_for_css_property_names[xkcd-None]", "tests/test_color.py::test_rich_color", "tests/test_color.py::test_rich_color_rich_output", "tests/test_color.py::test_normalized", "tests/test_color.py::test_clamped", "tests/test_color.py::test_css", "tests/test_color.py::test_colorpair_style", "tests/test_color.py::test_hls", "tests/test_color.py::test_color_brightness", "tests/test_color.py::test_color_hex", "tests/test_color.py::test_color_css", "tests/test_color.py::test_color_with_alpha", "tests/test_color.py::test_color_blend", "tests/test_color.py::test_color_parse[#000000-expected0]", "tests/test_color.py::test_color_parse[#ffffff-expected1]", "tests/test_color.py::test_color_parse[#FFFFFF-expected2]", "tests/test_color.py::test_color_parse[#020304ff-expected5]", "tests/test_color.py::test_color_parse[#02030400-expected6]", "tests/test_color.py::test_color_parse[#0203040f-expected7]", "tests/test_color.py::test_color_parse[rgb(0,0,0)-expected8]", "tests/test_color.py::test_color_parse[rgb(255,255,255)-expected9]", "tests/test_color.py::test_color_parse[rgba(255,255,255,1)-expected10]", "tests/test_color.py::test_color_parse[rgb(2,3,4)-expected11]", "tests/test_color.py::test_color_parse[rgba(2,3,4,1.0)-expected12]", "tests/test_color.py::test_color_parse[rgba(2,3,4,0.058823529411764705)-expected13]", "tests/test_color.py::test_color_parse_color", "tests/test_color.py::test_color_add", "tests/test_color.py::test_color_darken", "tests/test_color.py::test_color_lighten", "tests/test_color.py::test_rgb_to_lab[10-23-73-10.245-15.913--32.672]", "tests/test_color.py::test_rgb_to_lab[200-34-123-45.438-67.75--8.008]", "tests/test_color.py::test_rgb_to_lab[0-0-0-0-0-0]", "tests/test_color.py::test_rgb_to_lab[255-255-255-100-0-0]", "tests/test_color.py::test_lab_to_rgb[10-23-73-10.245-15.913--32.672]", "tests/test_color.py::test_lab_to_rgb[200-34-123-45.438-67.75--8.008]", "tests/test_color.py::test_lab_to_rgb[0-0-0-0-0-0]", "tests/test_color.py::test_lab_to_rgb[255-255-255-100-0-0]", "tests/test_color.py::test_rgb_lab_rgb_roundtrip", "tests/test_color.py::test_color_pair_style" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-05-03 16:48:13+00:00
mit
784
TheFriendlyCoder__friendlypins-101
diff --git a/src/friendlypins/board.py b/src/friendlypins/board.py index 3426068..4ef40d4 100644 --- a/src/friendlypins/board.py +++ b/src/friendlypins/board.py @@ -1,34 +1,22 @@ """Primitives for interacting with Pinterest boards""" -import logging -import json from friendlypins.pin import Pin +from friendlypins.utils.base_object import BaseObject -class Board(object): +class Board(BaseObject): """Abstraction around a Pinterest board""" + @staticmethod + def default_url(unique_id): + """Generates a URL for the REST API endpoint for a board with a given + identification number - def __init__(self, url, rest_io, json_data=None): - """ Args: - url (str): URL for this board, relative to the API root - rest_io (RestIO): reference to the Pinterest REST API - json_data (dict): - Optional JSON response data describing this board - if not provided, the class will lazy load response data - when needed - """ - self._log = logging.getLogger(__name__) - self._data_cache = json_data - self._relative_url = url - self._io = rest_io + unique_id (int): unique ID for the board - def refresh(self): - """Updates cached response data describing the state of this board - - NOTE: This method simply clears the internal cache, and updated - information will automatically be pulled on demand as additional - queries are made through the API""" - self._data_cache = None + Returns: + str: URL for the API endpoint + """ + return "boards/{0}".format(unique_id) @staticmethod def default_fields(): @@ -45,51 +33,6 @@ class Board(object): "privacy" ] - @property - def _data(self): - """dict: gets response data, either from the internal cache or from the - REST API""" - if self._data_cache is not None: - return self._data_cache - self._log.debug("Lazy loading board data for: %s", self._relative_url) - properties = { - "fields": ','.join(self.default_fields()) - } - temp = self._io.get(self._relative_url, properties) - assert "data" in temp - self._data_cache = temp["data"] - - return self._data_cache - - @classmethod - def from_json(cls, json_data, rest_io): - """Factory method that instantiates an instance of this class - from JSON response data loaded by the caller - - Args: - json_data (dict): - pre-loaded response data describing the board - rest_io (RestIO): - pre-initialized session object for communicating with the - REST API - - Returns: - Board: instance of this class encapsulating the response data - """ - board_url = "boards/{0}".format(json_data["id"]) - return Board(board_url, rest_io, json_data) - - @property - def json(self): - """dict: returns raw json representation of this object""" - return self._data - - def __str__(self): - return json.dumps(self._data, sort_keys=True, indent=4) - - def __repr__(self): - return "<{0} ({1})>".format(self.__class__.__name__, self.name) - @property def unique_id(self): """int: The unique identifier associated with this board""" @@ -121,21 +64,7 @@ class Board(object): self._log.debug('Loading pins for board %s...', self._relative_url) properties = { - "fields": ','.join([ - "id", - "link", - "url", - "board", - "created_at", - "note", - "color", - "counts", - "media", - "attribution", - "image", - "metadata", - "original_link" - ]) + "fields": ','.join(Pin.default_fields()) } path = "{0}/pins".format(self._relative_url) @@ -143,7 +72,7 @@ class Board(object): assert 'data' in cur_page for cur_item in cur_page['data']: - yield Pin(cur_item, self._io) + yield Pin.from_json(cur_item, self._io) def delete(self): """Removes this board and all pins attached to it""" diff --git a/src/friendlypins/pin.py b/src/friendlypins/pin.py index e90e0a7..6e896d6 100644 --- a/src/friendlypins/pin.py +++ b/src/friendlypins/pin.py @@ -1,27 +1,42 @@ """Primitives for operating on Pinterest pins""" -import logging -import json from friendlypins.thumbnail import Thumbnail +from friendlypins.utils.base_object import BaseObject -class Pin(object): +class Pin(BaseObject): """Abstraction around a Pinterest pin""" - def __init__(self, data, rest_io): - """ - Args: - data (dict): Raw Pinterest API data describing a pin - rest_io (RestIO): reference to the Pinterest REST API - """ - self._log = logging.getLogger(__name__) - self._io = rest_io - self._data = data + @staticmethod + def default_url(unique_id): + """Generates a URL for the REST API endpoint for a pin with a given + identification number - def __str__(self): - return json.dumps(dict(self._data), sort_keys=True, indent=4) + Args: + unique_id (int): unique ID for the pin - def __repr__(self): - return "<{0} ({1})>".format(self.__class__.__name__, self.note) + Returns: + str: URL for the API endpoint + """ + return "pins/{0}".format(unique_id) + + @staticmethod + def default_fields(): + """list (str): list of fields we pre-populate when loading pin data""" + return [ + "id", + "link", + "url", + "board", + "created_at", + "note", + "color", + "counts", + "media", + "attribution", + "image", + "metadata", + "original_link" + ] @property def url(self): @@ -63,8 +78,8 @@ class Pin(object): def delete(self): """Removes this pin from it's respective board""" - self._log.debug('Deleting pin %s', repr(self)) - self._io.delete('pins/{0}'.format(self.unique_id)) + self._log.debug('Deleting pin %s', self._relative_url) + self._io.delete(self._relative_url) if __name__ == "__main__": # pragma: no cover diff --git a/src/friendlypins/utils/base_object.py b/src/friendlypins/utils/base_object.py new file mode 100644 index 0000000..4368adb --- /dev/null +++ b/src/friendlypins/utils/base_object.py @@ -0,0 +1,96 @@ +"""Base class exposing common functionality to all Pinterest primitives""" +import logging +import json + + +class BaseObject: + """Common base class providing shared functionality for all Pinterest + primitives""" + + def __init__(self, url, rest_io, json_data=None): + """ + Args: + url (str): URL for this object, relative to the API root + rest_io (RestIO): reference to the Pinterest REST API + json_data (dict): + Optional JSON response data describing this object + if not provided, the class will lazy load response data + when needed + """ + self._log = logging.getLogger(type(self).__module__) + self._data_cache = json_data + self._relative_url = url + self._io = rest_io + + @staticmethod + def default_fields(): + """Default implementation""" + raise NotImplementedError( + "All derived classes must define a default_fields method" + ) + + @staticmethod + def default_url(unique_id): + """Default implementation""" + raise NotImplementedError( + "All derived classes must define a default_url method" + ) + + def refresh(self): + """Updates cached response data describing the state of this pin + + NOTE: This method simply clears the internal cache, and updated + information will automatically be pulled on demand as additional + queries are made through the API""" + self._data_cache = None + + @property + def _data(self): + """dict: gets response data, either from the internal cache or from the + REST API""" + if self._data_cache is not None: + return self._data_cache + self._log.debug("Lazy loading data for: %s", self._relative_url) + properties = { + "fields": ','.join(self.default_fields()) + } + temp = self._io.get(self._relative_url, properties) + assert "data" in temp + self._data_cache = temp["data"] + + return self._data_cache + + @classmethod + def from_json(cls, json_data, rest_io): + """Factory method that instantiates an instance of this class + from JSON response data loaded by the caller + + Args: + json_data (dict): + pre-loaded response data describing the object + rest_io (RestIO): + pre-initialized session object for communicating with the + REST API + + Returns: + instance of this derived class, pre-initialized with the provided + response data + """ + + return cls(cls.default_url(json_data["id"]), rest_io, json_data) + + @property + def json(self): + """dict: returns raw json representation of this object""" + return self._data + + def __str__(self): + return json.dumps(self._data, sort_keys=True, indent=4) + + def __repr__(self): + return "<{0} ({1}, {2}, {3})>".format( + self.__class__.__name__, + self._relative_url, + self._io, + self._data_cache + )
TheFriendlyCoder/friendlypins
5fbf9388b72ccbdb565e8d937a0a456715c9698f
diff --git a/tests/test_pin.py b/tests/test_pin.py index 0d79543..3f6c030 100644 --- a/tests/test_pin.py +++ b/tests/test_pin.py @@ -19,7 +19,7 @@ def test_pin_properties(): } mock_io = mock.MagicMock() - obj = Pin(sample_data, mock_io) + obj = Pin("pins/1234", mock_io, sample_data) assert obj.unique_id == expected_id assert obj.note == expected_note @@ -41,7 +41,7 @@ def test_pin_missing_media_type(): } mock_io = mock.MagicMock() - obj = Pin(sample_data, mock_io) + obj = Pin("pins/1234", mock_io, sample_data) assert obj.unique_id == expected_id assert obj.note == expected_note @@ -74,7 +74,7 @@ def test_get_thumbnail(): } mock_io = mock.MagicMock() - obj = Pin(data, mock_io) + obj = Pin("pins/1234", mock_io, data) result = obj.thumbnail assert result.url == expected_url
Add helper to get all pins from a board I need to add a helper method that pulls down all of the pins attached to a board with the minimal number of api calls, and include support for waiting when rate limits are exceeded to pull down more paged data. Ideally the helper would accept the ID of a board and return the raw JSON for all paged data for all pins on the board. Further, it would be good to have support for a callback method that could give updates to the caller when operations are pending like waiting for next rate limit expiration.
0.0
5fbf9388b72ccbdb565e8d937a0a456715c9698f
[ "tests/test_pin.py::test_pin_properties", "tests/test_pin.py::test_pin_missing_media_type", "tests/test_pin.py::test_get_thumbnail" ]
[ "tests/test_pin.py::test_delete" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-20 22:15:31+00:00
apache-2.0
785
TheFriendlyCoder__friendlypins-77
diff --git a/src/friendlypins/api.py b/src/friendlypins/api.py index 4b014c9..03a92f2 100644 --- a/src/friendlypins/api.py +++ b/src/friendlypins/api.py @@ -48,11 +48,7 @@ class API(object): # pylint: disable=too-few-public-methods :rtype: :class:`datetime.datetime` """ - try: - if self._io.headers is None: - self._io.get("me") - finally: - return self._io.headers.time_to_refresh # pylint: disable=lost-exception + return self._io.headers.time_to_refresh @property def transaction_limit(self): @@ -60,11 +56,7 @@ class API(object): # pylint: disable=too-few-public-methods :rtype: :class:`int` """ - try: - if self._io.headers is None: - self._io.get("me") - finally: - return self._io.headers.rate_limit # pylint: disable=lost-exception + return self._io.headers.rate_limit @property def transaction_remaining(self): @@ -72,11 +64,8 @@ class API(object): # pylint: disable=too-few-public-methods :rtype: :class:`int` """ - try: - if self._io.headers is None: - self._io.get("me") - finally: - return self._io.headers.rate_remaining # pylint: disable=lost-exception + return self._io.headers.rate_remaining + if __name__ == "__main__": pass diff --git a/src/friendlypins/utils/rest_io.py b/src/friendlypins/utils/rest_io.py index 4fe03f1..50c9136 100644 --- a/src/friendlypins/utils/rest_io.py +++ b/src/friendlypins/utils/rest_io.py @@ -35,6 +35,12 @@ class RestIO(object): :rtype: :class:`friendlypins.headers.Headers` """ + if not self._latest_header: + temp_url = "{0}/me".format(self._root_url) + properties = {"access_token": self._token} + response = requests.get(temp_url, params=properties) + self._latest_header = Headers(response.headers) + response.raise_for_status() return self._latest_header def get(self, path, properties=None): diff --git a/tox.ini b/tox.ini index e5c3570..1fc289c 100644 --- a/tox.ini +++ b/tox.ini @@ -13,7 +13,7 @@ commands = /bin/bash -c 'pip install dist/*.whl' pylint setup.py bash -c "source toxenv.sh; pylint ./src/$PROJECT_NAME" - bash -c "source toxenv.sh; pytest ./tests -v --cov-report html --cov $PROJECT_NAME --no-cov-on-fail" + bash -c "source toxenv.sh; pytest {posargs} ./tests -v --cov-report html --cov $PROJECT_NAME --no-cov-on-fail" [testenv:py2] deps = -rtests/python2.reqs
TheFriendlyCoder/friendlypins
11981f65cd70b9db9c0e39fb608e73800e58dd33
diff --git a/tests/test_api.py b/tests/test_api.py index 552f578..026b261 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,4 +1,3 @@ -import pytest import mock from friendlypins.api import API from dateutil import tz @@ -51,13 +50,13 @@ def test_transaction_limit(mock_requests): 'Pinterest-Generated-By': '', } mock_requests.get.return_value = mock_response - mock_response.raise_for_status.side_effect = Exception obj = API("abcd1234") - obj.transaction_limit == expected_rate_limit + assert obj.transaction_limit == expected_rate_limit mock_requests.get.assert_called_once() mock_response.raise_for_status.assert_called_once() + @mock.patch("friendlypins.utils.rest_io.requests") def test_transaction_remaining(mock_requests): mock_response = mock.MagicMock() @@ -78,13 +77,13 @@ def test_transaction_remaining(mock_requests): 'Pinterest-Generated-By': '', } mock_requests.get.return_value = mock_response - mock_response.raise_for_status.side_effect = Exception obj = API("abcd1234") tmp = obj.transaction_remaining mock_requests.get.assert_called_once() mock_response.raise_for_status.assert_called_once() - tmp == expected_rate_remaining + assert tmp == expected_rate_remaining + @mock.patch("friendlypins.utils.rest_io.requests") def test_rate_refresh(mock_requests): @@ -109,7 +108,6 @@ def test_rate_refresh(mock_requests): 'X-Ratelimit-Refresh': str(refresh_time) } mock_requests.get.return_value = mock_response - mock_response.raise_for_status.side_effect = Exception obj = API("abcd1234") tmp = obj.rate_limit_refresh @@ -118,7 +116,3 @@ def test_rate_refresh(mock_requests): mock_response.raise_for_status.assert_called_once() tmp = tmp.astimezone(tz.tzutc()) assert tmp.strftime("%a, %d %b %Y %H:%M:%S") == expected_time_str - - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) diff --git a/tests/test_board.py b/tests/test_board.py index 698aed6..94753aa 100644 --- a/tests/test_board.py +++ b/tests/test_board.py @@ -1,7 +1,7 @@ -import pytest import mock from friendlypins.board import Board + def test_board_properties(): expected_id = 1234 expected_name = "MyBoard" @@ -64,6 +64,7 @@ def test_get_pins(): assert expected_id == result[0].unique_id assert expected_mediatype == result[0].media_type + def test_delete(): data = { "id": "12345678", @@ -75,6 +76,3 @@ def test_delete(): obj.delete() mock_io.delete.assert_called_once() - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) diff --git a/tests/test_console_actions.py b/tests/test_console_actions.py index eb41b05..3097767 100644 --- a/tests/test_console_actions.py +++ b/tests/test_console_actions.py @@ -1,4 +1,3 @@ -import pytest import mock import os from friendlypins.utils.console_actions import download_thumbnails, \ @@ -6,6 +5,7 @@ from friendlypins.utils.console_actions import download_thumbnails, \ import friendlypins.utils.console_actions as ca ca.DISABLE_PROGRESS_BARS = True + @mock.patch("friendlypins.utils.console_actions.os") @mock.patch("friendlypins.utils.console_actions.open") @mock.patch("friendlypins.utils.console_actions.requests") @@ -170,6 +170,7 @@ def test_download_thumbnails_error(rest_io, action_requests, mock_open, mock_os) mock_os.path.exists.assert_called() assert not mock_open.called + @mock.patch("friendlypins.utils.console_actions.os") @mock.patch("friendlypins.utils.console_actions.open") @mock.patch("friendlypins.utils.console_actions.requests") @@ -249,6 +250,7 @@ def test_download_thumbnails_missing_board(rest_io, action_requests, mock_open, assert not mock_os.path.exists.called assert not mock_open.called + @mock.patch("friendlypins.utils.console_actions.os") @mock.patch("friendlypins.utils.console_actions.open") @mock.patch("friendlypins.utils.console_actions.requests") @@ -332,6 +334,7 @@ def test_download_thumbnails_exists(rest_io, action_requests, mock_open, mock_os mock_os.path.exists.assert_called_with(os.path.join(output_folder, expected_filename)) assert not mock_open.called + @mock.patch("friendlypins.api.RestIO") def test_delete_board(rest_io): @@ -423,6 +426,7 @@ def test_delete_missing_board(rest_io): assert result != 0 mock_response.delete.assert_not_called() + @mock.patch("friendlypins.api.RestIO") def test_create_board(rest_io): # Fake user data for the user authenticating to Pinterest @@ -453,6 +457,3 @@ def test_create_board(rest_io): assert res == 0 mock_response.get.assert_called_once() - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) \ No newline at end of file diff --git a/tests/test_headers.py b/tests/test_headers.py index 797e786..f8ea695 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -1,5 +1,3 @@ -import pytest -import mock from friendlypins.headers import Headers from dateutil import tz @@ -32,26 +30,31 @@ def test_get_date_locale(): assert obj.date.tzinfo == tz.tzlocal() + def test_get_rate_limit(): obj = Headers(sample_header) assert obj.rate_limit == sample_rate_limit + def test_get_rate_max(): obj = Headers(sample_header) assert obj.rate_remaining == sample_rate_max + def test_get_rate_percent(): obj = Headers(sample_header) assert obj.percent_rate_remaining == 75 + def test_get_num_bytes(): obj = Headers(sample_header) assert obj.bytes == sample_content_length + def test_time_to_refresh(): obj = Headers(sample_header) @@ -60,5 +63,3 @@ def test_time_to_refresh(): tmp = tmp.astimezone(tz.tzutc()) assert tmp.strftime("%a, %d %b %Y %H:%M:%S") == expected_time_str -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) \ No newline at end of file diff --git a/tests/test_pin.py b/tests/test_pin.py index 7fd8924..0d79543 100644 --- a/tests/test_pin.py +++ b/tests/test_pin.py @@ -1,7 +1,7 @@ -import pytest import mock from friendlypins.pin import Pin + def test_pin_properties(): expected_id = 1234 expected_note = "Here's my note" @@ -78,7 +78,3 @@ def test_get_thumbnail(): result = obj.thumbnail assert result.url == expected_url - - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) \ No newline at end of file diff --git a/tests/test_rest_io.py b/tests/test_rest_io.py index 83b04a5..1539768 100644 --- a/tests/test_rest_io.py +++ b/tests/test_rest_io.py @@ -1,7 +1,7 @@ -import pytest import mock from friendlypins.utils.rest_io import RestIO + @mock.patch("friendlypins.utils.rest_io.requests") def test_get_method(mock_requests): expected_token = "1234abcd" @@ -23,6 +23,7 @@ def test_get_method(mock_requests): assert "access_token" in mock_requests.get.call_args[1]['params'] assert mock_requests.get.call_args[1]['params']['access_token'] == expected_token + @mock.patch("friendlypins.utils.rest_io.requests") def test_get_pages_one_page(mock_requests): expected_token = "1234abcd" @@ -47,10 +48,10 @@ def test_get_pages_one_page(mock_requests): assert "access_token" in mock_requests.get.call_args[1]['params'] assert mock_requests.get.call_args[1]['params']['access_token'] == expected_token + @mock.patch("friendlypins.utils.rest_io.requests") def test_get_headers(mock_requests): obj = RestIO("1234abcd") - assert obj.headers is None expected_bytes = 1024 mock_response = mock.MagicMock() @@ -59,12 +60,28 @@ def test_get_headers(mock_requests): } mock_requests.get.return_value = mock_response obj.get("me/boards") + tmp = obj.headers mock_requests.get.assert_called_once() + assert tmp is not None + assert tmp.bytes == expected_bytes + + [email protected]("friendlypins.utils.rest_io.requests") +def test_get_default_headers(mock_requests): + obj = RestIO("1234abcd") + + expected_bytes = 1024 + mock_response = mock.MagicMock() + mock_response.headers = { + "Content-Length": str(expected_bytes) + } + mock_requests.get.return_value = mock_response tmp = obj.headers assert tmp is not None assert tmp.bytes == expected_bytes + mock_requests.get.assert_called_once() @mock.patch("friendlypins.utils.rest_io.requests") @@ -91,6 +108,4 @@ def test_post(mock_requests): assert expected_path in mock_requests.post.call_args[0][0] assert "data" in mock_requests.post.call_args[1] assert mock_requests.post.call_args[1]["data"] == expected_data - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) + assert res == expected_results diff --git a/tests/test_thumbnail.py b/tests/test_thumbnail.py index b9dd141..c43aee6 100644 --- a/tests/test_thumbnail.py +++ b/tests/test_thumbnail.py @@ -1,7 +1,6 @@ -import pytest -import mock from friendlypins.thumbnail import Thumbnail + def test_thumbnail_properties(): expected_url = "https://i.pinimg.com/originals/1/2/3/abcd.jpg" expected_width = 800 @@ -19,6 +18,3 @@ def test_thumbnail_properties(): assert obj.url == expected_url assert obj.width == expected_width assert obj.height == expected_height - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"]) \ No newline at end of file diff --git a/tests/test_user.py b/tests/test_user.py index 75d051e..9659aac 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -1,7 +1,7 @@ -import pytest import mock from friendlypins.user import User + def test_user_properties(): expected_url = 'https://www.pinterest.com/MyUserName/' expected_firstname = "John" @@ -63,6 +63,7 @@ def test_get_boards(): assert expected_name == result[0].name assert expected_id == result[0].unique_id + def test_create_board(): expected_name = "My Board" expected_desc = "My new board is about this stuff..." @@ -86,6 +87,3 @@ def test_create_board(): assert board is not None assert board.name == expected_name assert board.description == expected_desc - -if __name__ == "__main__": - pytest.main([__file__, "-v", "-s"])
Update API to auto-load header data The REST API abstraction layer attempts to auto-load the header data produced by the pinterest API, caching it for future reference, however in certain situations the caching mechanism doesn't 't work. Specifically, only certain method calls on the restio class are configured to populate the internal header cache. To help compensate for more advanced use cases we should update the **headers** property to detect when the internal cache has not yet been populated, and auto-populate the cache.
0.0
11981f65cd70b9db9c0e39fb608e73800e58dd33
[ "tests/test_rest_io.py::test_get_default_headers" ]
[ "tests/test_api.py::test_get_user", "tests/test_api.py::test_transaction_limit", "tests/test_api.py::test_transaction_remaining", "tests/test_api.py::test_rate_refresh", "tests/test_board.py::test_board_properties", "tests/test_board.py::test_get_pins", "tests/test_board.py::test_delete", "tests/test_console_actions.py::test_download_thumbnails", "tests/test_console_actions.py::test_download_thumbnails_error", "tests/test_console_actions.py::test_download_thumbnails_missing_board", "tests/test_console_actions.py::test_download_thumbnails_exists", "tests/test_console_actions.py::test_delete_board", "tests/test_console_actions.py::test_delete_missing_board", "tests/test_console_actions.py::test_create_board", "tests/test_headers.py::test_get_date_locale", "tests/test_headers.py::test_get_rate_limit", "tests/test_headers.py::test_get_rate_max", "tests/test_headers.py::test_get_rate_percent", "tests/test_headers.py::test_get_num_bytes", "tests/test_headers.py::test_time_to_refresh", "tests/test_pin.py::test_pin_properties", "tests/test_pin.py::test_pin_missing_media_type", "tests/test_pin.py::test_delete", "tests/test_pin.py::test_get_thumbnail", "tests/test_rest_io.py::test_get_method", "tests/test_rest_io.py::test_get_pages_one_page", "tests/test_rest_io.py::test_get_headers", "tests/test_rest_io.py::test_post", "tests/test_thumbnail.py::test_thumbnail_properties", "tests/test_user.py::test_user_properties", "tests/test_user.py::test_get_boards", "tests/test_user.py::test_create_board" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-18 12:33:00+00:00
apache-2.0
786
TheFriendlyCoder__friendlypins-93
diff --git a/.gitignore b/.gitignore index adb9ca9..917bbc2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ build/ # Temporary unit test files htmlcov/ .tox/ -.coverage +.coverage* docs/_* docs/api/* htmldocs/* diff --git a/src/friendlypins/api.py b/src/friendlypins/api.py index 3d382cc..81bc8b0 100644 --- a/src/friendlypins/api.py +++ b/src/friendlypins/api.py @@ -1,5 +1,4 @@ """Primary entry point for the Friendly Pinterest library""" -from __future__ import print_function import logging from friendlypins.user import User from friendlypins.utils.rest_io import RestIO @@ -21,24 +20,7 @@ class API(object): # pylint: disable=too-few-public-methods @property def user(self): """User: Gets all primitives associated with the authenticated user""" - self._log.debug("Getting authenticated user details...") - - fields = ",".join([ - "id", - "username", - "first_name", - "last_name", - "bio", - "created_at", - "counts", - "image", - "account_type", - "url" - ]) - result = self._io.get("me", {"fields": fields}) - assert 'data' in result - - return User(result['data'], self._io) + return User("me", self._io) @property def rate_limit_refresh(self): diff --git a/src/friendlypins/user.py b/src/friendlypins/user.py index 5aea1c9..0d8670d 100644 --- a/src/friendlypins/user.py +++ b/src/friendlypins/user.py @@ -7,15 +7,53 @@ from friendlypins.board import Board class User(object): """Abstraction around a Pinterest user and their associated data""" - def __init__(self, data, rest_io): + def __init__(self, url, rest_io): """ Args: - data (dict): JSON data parsed from the API + url (str): URL for this user, relative to the API root rest_io (RestIO): reference to the Pinterest REST API """ self._log = logging.getLogger(__name__) - self._data = data self._io = rest_io + self._relative_url = url + self._data_cache = None + + def refresh(self): + """Updates cached response data describing the state of this user + + NOTE: This method simply clears the internal cache, and updated + information will automatically be pulled on demand as additional + queries are made through the API""" + self._data_cache = None + + @property + def _data(self): + """dict: JSON response containing details of the users' profile + + This internal helper caches the user profile data to minimize the + number of calls to the REST API, to make more efficient use of rate + limitations. + """ + if self._data_cache is not None: + return self._data_cache["data"] + self._log.debug("Getting authenticated user details...") + + fields = ",".join([ + "id", + "username", + "first_name", + "last_name", + "bio", + "created_at", + "counts", + "image", + "account_type", + "url" + ]) + self._data_cache = self._io.get(self._relative_url, {"fields": fields}) + assert 'data' in self._data_cache + return self._data_cache["data"] + def __str__(self): return json.dumps(dict(self._data), sort_keys=True, indent=4) @@ -67,7 +105,7 @@ class User(object): @property def boards(self): """Board: Generator for iterating over the boards owned by this user""" - self._log.debug('Loading boards for user %s...', self.name) + self._log.debug('Loading boards for user %s...', self._relative_url) properties = { "fields": ','.join([ @@ -84,7 +122,8 @@ class User(object): ]) } - for cur_page in self._io.get_pages("me/boards", properties): + board_url = "{0}/boards".format(self._relative_url) + for cur_page in self._io.get_pages(board_url, properties): assert 'data' in cur_page for cur_item in cur_page['data']:
TheFriendlyCoder/friendlypins
3f1f566c647299f9da73db11a98cc142b565072e
diff --git a/tests/test_console_actions.py b/tests/test_console_actions.py index 3097767..7c0a6af 100644 --- a/tests/test_console_actions.py +++ b/tests/test_console_actions.py @@ -456,4 +456,9 @@ def test_create_board(rest_io): res = create_board("1234abcd", expected_name) assert res == 0 - mock_response.get.assert_called_once() + # Now that we lazy load user data we should never need to call get + # to create a board + assert mock_response.get.call_count == 0 + + # The post operation should have occurred once to create the board + mock_response.post.assert_called_once() diff --git a/tests/test_user.py b/tests/test_user.py index 9659aac..ffacb62 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -21,13 +21,43 @@ def test_user_properties(): } mock_io = mock.MagicMock() - obj = User(data, mock_io) + mock_io.get.return_value = {"data": data} + obj = User("me", mock_io) assert expected_url == obj.url assert expected_firstname == obj.first_name assert expected_lastname == obj.last_name assert expected_id == obj.unique_id assert expected_board_count == obj.num_boards assert expected_pin_count == obj.num_pins + mock_io.get.assert_called_once() + + +def test_cache_refresh(): + expected_url = 'https://www.pinterest.com/MyUserName/' + data = { + 'url': expected_url, + } + + mock_io = mock.MagicMock() + mock_io.get.return_value = {"data": data} + obj = User("me", mock_io) + # If we make multiple requests for API data, we should only get + # a single hit to the remote API endpoint + assert expected_url == obj.url + assert expected_url == obj.url + mock_io.get.assert_called_once() + + # Calling refresh should clear our internal response cache + # which should not require any additional API calls + obj.refresh() + mock_io.get.assert_called_once() + + # Subsequent requests for additional data should reload the cache, + # and then preserve / reuse the cache data for all subsequent calls, + # limiting the number of remote requests + assert expected_url == obj.url + assert expected_url == obj.url + assert mock_io.get.call_count == 2 def test_get_boards():
lazy load user data from api Currently, all API calls in our library are funnelled through the "current user" object (ie: api.user()) and this property pre-caches the user profile data for the current user prior to generating the user object returned to the caller. For cases where the user profile data is unnecessary, this forces the caller to perform an initial get request that may be completely superfluous. In an effort to make the API as efficient as possible in it's use of API calls (ie: to optimize the calls to stay within any rate limits the calling code may have) we should make this pre-caching of the user profile optional, lazy loading the data only when needed.
0.0
3f1f566c647299f9da73db11a98cc142b565072e
[ "tests/test_console_actions.py::test_create_board", "tests/test_user.py::test_user_properties", "tests/test_user.py::test_cache_refresh" ]
[ "tests/test_console_actions.py::test_download_thumbnails", "tests/test_console_actions.py::test_download_thumbnails_error", "tests/test_console_actions.py::test_download_thumbnails_missing_board", "tests/test_console_actions.py::test_download_thumbnails_exists", "tests/test_console_actions.py::test_delete_board", "tests/test_console_actions.py::test_delete_missing_board", "tests/test_user.py::test_get_boards", "tests/test_user.py::test_create_board" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-19 18:21:23+00:00
apache-2.0
787
TheFriendlyCoder__pyjen-113
diff --git a/src/pyjen/job.py b/src/pyjen/job.py index ee9fba0..179e689 100644 --- a/src/pyjen/job.py +++ b/src/pyjen/job.py @@ -2,7 +2,7 @@ import logging from pyjen.build import Build from pyjen.utils.jobxml import JobXML -from pyjen.utils.plugin_api import find_plugin +from pyjen.utils.plugin_api import find_plugin, get_all_plugins class Job(object): @@ -82,6 +82,18 @@ class Job(object): return plugin_class(rest_api.clone(job_url)) + @classmethod + def get_supported_plugins(cls): + """Returns a list of PyJen plugins that derive from this class + + :rtype: :class:`list` of :class:`class` + """ + retval = list() + for cur_plugin in get_all_plugins(): + if issubclass(cur_plugin, cls): + retval.append(cur_plugin) + return retval + @property def name(self): """Returns the name of the job managed by this object diff --git a/src/pyjen/utils/plugin_api.py b/src/pyjen/utils/plugin_api.py index 0c925e2..0c26416 100644 --- a/src/pyjen/utils/plugin_api.py +++ b/src/pyjen/utils/plugin_api.py @@ -24,19 +24,9 @@ def find_plugin(plugin_name): formatted_plugin_name = plugin_name.replace("__", "_") log = logging.getLogger(__name__) - all_plugins = list() - for entry_point in iter_entry_points(group=PLUGIN_ENTRYPOINT_NAME): - all_plugins.append(entry_point.load()) supported_plugins = list() - for cur_plugin in all_plugins: - if not hasattr(cur_plugin, PLUGIN_METHOD_NAME): - log.debug( - "Plugin %s does not expose the required %s static method.", - cur_plugin.__module__, - PLUGIN_METHOD_NAME) - continue - + for cur_plugin in get_all_plugins(): if getattr(cur_plugin, PLUGIN_METHOD_NAME)() == formatted_plugin_name: supported_plugins.append(cur_plugin) @@ -50,5 +40,32 @@ def find_plugin(plugin_name): return supported_plugins[0] +def get_all_plugins(): + """Returns a list of all PyJen plugins installed on the system + + :returns: list of 0 or more installed plugins + :rtype: :class:`list` of :class:`class` + """ + log = logging.getLogger(__name__) + # First load all libraries that are registered with the PyJen plugin API + all_plugins = list() + for entry_point in iter_entry_points(group=PLUGIN_ENTRYPOINT_NAME): + all_plugins.append(entry_point.load()) + + # Next, filter out those that don't support the current version of our API + retval = list() + for cur_plugin in all_plugins: + if not hasattr(cur_plugin, PLUGIN_METHOD_NAME): + log.debug( + "Plugin %s does not expose the required %s static method.", + cur_plugin.__module__, + PLUGIN_METHOD_NAME) + continue + + retval.append(cur_plugin) + + return retval + + if __name__ == "__main__": # pragma: no cover pass diff --git a/src/pyjen/view.py b/src/pyjen/view.py index 76ef326..2b94b3a 100644 --- a/src/pyjen/view.py +++ b/src/pyjen/view.py @@ -1,7 +1,7 @@ """Primitives for interacting with Jenkins views""" import logging from pyjen.job import Job -from pyjen.utils.plugin_api import find_plugin +from pyjen.utils.plugin_api import find_plugin, get_all_plugins class View(object): @@ -68,6 +68,18 @@ class View(object): return plugin_class(rest_api.clone(view_url)) + @classmethod + def get_supported_plugins(cls): + """Returns a list of PyJen plugins that derive from this class + + :rtype: :class:`list` of :class:`class` + """ + retval = list() + for cur_plugin in get_all_plugins(): + if issubclass(cur_plugin, cls): + retval.append(cur_plugin) + return retval + @property def name(self): """Gets the display name for this view
TheFriendlyCoder/pyjen
85e8c0860d304de461b53805f471e3bc3fabc4c4
diff --git a/tests/test_plugin_api.py b/tests/test_plugin_api.py index a4f1c1d..3c65678 100644 --- a/tests/test_plugin_api.py +++ b/tests/test_plugin_api.py @@ -1,6 +1,9 @@ import pytest from mock import patch, MagicMock -from pyjen.utils.plugin_api import find_plugin +from .utils import count_plugins +from pyjen.utils.plugin_api import find_plugin, get_all_plugins +from pyjen.view import View +from pyjen.job import Job def test_unsupported_plugin(caplog): @@ -54,23 +57,45 @@ def test_multiple_supported_plugin(caplog): assert "multiple plugins detected" in caplog.text [email protected]("TODO: add helper to get list of all installed plugins to new plugin api") def test_list_plugins(): - res = ConfigXML.get_installed_plugins() + res = get_all_plugins() assert res is not None assert isinstance(res, list) assert len(res) == count_plugins() [email protected]("TODO: add helper to get list of all installed plugins to new plugin api") -def test_load_all_plugins(): - plugin_names = ConfigXML.get_installed_plugins() - assert plugin_names - - for cur_plugin_name in plugin_names: - cur_plugin = ConfigXML.find_plugin(cur_plugin_name) - assert cur_plugin is not None - assert inspect.isclass(cur_plugin) +def test_load_all_job_plugins(): + plugins = Job.get_supported_plugins() + assert plugins is not None + assert isinstance(plugins, list) + assert len(plugins) > 0 + + mock_api = MagicMock() + expected_name = "FakeName" + mock_api.get_api_data.return_value = { + "name": expected_name + } + for cur_plugin in plugins: + job = cur_plugin(mock_api) + assert job.name == expected_name + assert isinstance(job, Job) + + +def test_load_all_view_plugins(): + plugins = View.get_supported_plugins() + assert plugins is not None + assert isinstance(plugins, list) + assert len(plugins) > 0 + + mock_api = MagicMock() + expected_name = "FakeName" + mock_api.get_api_data.return_value = { + "name": expected_name + } + for cur_plugin in plugins: + view = cur_plugin(mock_api) + assert view.name == expected_name + assert isinstance(view, View) if __name__ == "__main__":
Add helper methods to get installed plugins In an effort to make it easier for implementers to query for a list of installed PyJen plugins, we should add a couple of helper functions to the plugin API to return the list of installed plugins. I'm thinking one helper that returns all plugins, one that returns the subset of plugins that derive from the View base class, and another that returns the subset that derives from the Job base class, would be most helpful. We could probably use these helpers within the API itself as well as shorthands for locating plugins for specific purposes.
0.0
85e8c0860d304de461b53805f471e3bc3fabc4c4
[ "tests/test_plugin_api.py::test_unsupported_plugin", "tests/test_plugin_api.py::test_one_supported_plugin", "tests/test_plugin_api.py::test_multiple_supported_plugin", "tests/test_plugin_api.py::test_list_plugins", "tests/test_plugin_api.py::test_load_all_job_plugins", "tests/test_plugin_api.py::test_load_all_view_plugins" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-14 00:18:58+00:00
mit
788
TheFriendlyCoder__pyjen-136
diff --git a/src/pyjen/build.py b/src/pyjen/build.py index d0c902e..aba3a36 100644 --- a/src/pyjen/build.py +++ b/src/pyjen/build.py @@ -82,7 +82,6 @@ class Build(object): :rtype: :class:`bool` """ data = self._api.get_api_data() - return data['building'] @property @@ -105,10 +104,11 @@ class Build(object): * "SUCCESS" * "UNSTABLE" * "FAILURE" + * "ABORTED" + :rtype: :class:`str` """ data = self._api.get_api_data() - return data['result'] @property @@ -162,6 +162,10 @@ class Build(object): return retval + def abort(self): + """Aborts this build before it completes""" + self._api.post(self._api.url + "stop") + if __name__ == "__main__": # pragma: no cover pass diff --git a/src/pyjen/plugins/buildblocker.py b/src/pyjen/plugins/buildblocker.py index 87d09e0..f89643f 100644 --- a/src/pyjen/plugins/buildblocker.py +++ b/src/pyjen/plugins/buildblocker.py @@ -8,6 +8,58 @@ class BuildBlockerProperty(XMLPlugin): https://wiki.jenkins-ci.org/display/JENKINS/Build+Blocker+Plugin """ + QUEUE_SCAN_TYPES = ("DISABLED", "ALL", "BUILDABLE") + LEVEL_TYPES = ("GLOBAL", "NODE") + + @property + def queue_scan(self): + """Checks to see whether build blocking scans the build queue or not + + :returns: One of BuildBlockerProperty.QUEUE_SCAN_TYPES + :rtype: :class:`str` + """ + retval = self._root.find("scanQueueFor").text + assert retval in BuildBlockerProperty.QUEUE_SCAN_TYPES + return retval + + @queue_scan.setter + def queue_scan(self, value): + """Sets the type of build queue scanning for the blocking job + + :param str value: + type of queue scanning to perform + Must be one of BuildBlockerProperty.QUEUE_SCAN_TYPES + """ + if value not in BuildBlockerProperty.QUEUE_SCAN_TYPES: + raise ValueError( + "Build blocker queue scan may only be one of the following " + "types: " + ",".join(BuildBlockerProperty.QUEUE_SCAN_TYPES)) + self._root.find("scanQueueFor").text = value + + @property + def level(self): + """Gets the scope of the blocked job settings + + :returns: One of BuildBlockerProperty.LEVEL_TYPES + :rtype: :class:`str` + """ + retval = self._root.find("blockLevel").text + assert retval in BuildBlockerProperty.LEVEL_TYPES + return retval + + @level.setter + def level(self, value): + """Sets the scope of the blocked builds + + :param str value: + scope for this build blocker + Must be one of BuildBlockerProperty.LEVEL_TYPES + """ + if value not in BuildBlockerProperty.LEVEL_TYPES: + raise ValueError( + "Build blocker scope level may only be one of the following " + "types: " + ",".join(BuildBlockerProperty.LEVEL_TYPES)) + self._root.find("blockLevel").text = value @property def blockers(self): @@ -16,27 +68,24 @@ class BuildBlockerProperty(XMLPlugin): :return: list of search criteria for blocking jobs :rtype: :class:`list` """ - retval = [] - if not self.is_enabled: - return retval - temp = self._root.find("blockingJobs").text - if temp is None: - return retval - - retval = temp.split() - return retval + return temp.split() @blockers.setter - def blockers(self, new_blockers): - """Sets the list of search criteria for blocking jobs - - :param list new_blockers: list of search criteria for blocking jobs + def blockers(self, patterns): + """Defines the names or regular expressions for jobs that block + execution of this job + + :param patterns: + One or more names or regular expressions for jobs that block the + execution of this one. + :type patterns: either :class:`list` or :class:`str` """ node = self._root.find("blockingJobs") - if node is None: - node = ElementTree.SubElement(self._root, 'blockingJobs') - node.text = "\n".join(new_blockers) + if isinstance(patterns, str): + node.text = patterns + else: + node.text = "\n".join(patterns) @property def is_enabled(self): @@ -51,15 +100,11 @@ class BuildBlockerProperty(XMLPlugin): def enable(self): """Enables this set of build blockers""" node = self._root.find("useBuildBlocker") - if node is None: - node = ElementTree.SubElement(self._root, 'useBuildBlocker') node.text = "true" def disable(self): """Disables this set of build blockers""" node = self._root.find("useBuildBlocker") - if node is None: - node = ElementTree.SubElement(self._root, 'useBuildBlocker') node.text = "false" @staticmethod @@ -71,7 +116,30 @@ class BuildBlockerProperty(XMLPlugin): :rtype: :class:`str` """ - return "buildblocker" + return "hudson.plugins.buildblocker.BuildBlockerProperty" + + @classmethod + def create(cls, patterns): + """Factory method used to instantiate an instance of this plugin + + :param patterns: + One or more names or regular expressions for jobs that block the + execution of this one. + :type patterns: either :class:`list` or :class:`str` + """ + default_xml = """<hudson.plugins.buildblocker.BuildBlockerProperty plugin="[email protected]"> +<useBuildBlocker>true</useBuildBlocker> +<blockLevel>GLOBAL</blockLevel> +<scanQueueFor>DISABLED</scanQueueFor> +</hudson.plugins.buildblocker.BuildBlockerProperty>""" + + root_node = ElementTree.fromstring(default_xml) + jobs_node = ElementTree.SubElement(root_node, "blockingJobs") + if isinstance(patterns, str): + jobs_node.text = patterns + else: + jobs_node.text = " ".join(patterns) + return cls(root_node) PluginClass = BuildBlockerProperty diff --git a/src/pyjen/queue_item.py b/src/pyjen/queue_item.py index 7783f26..7c2165b 100644 --- a/src/pyjen/queue_item.py +++ b/src/pyjen/queue_item.py @@ -88,7 +88,7 @@ class QueueItem(object): :rtype: :class:`bool` """ - return self._data["cancelled"] + return self._data.get("cancelled", False) @property def job(self):
TheFriendlyCoder/pyjen
c4c268c0e359691f8fc034982a40cbaa6fae46f6
diff --git a/tests/conftest.py b/tests/conftest.py index 75dce52..178ae95 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -37,6 +37,7 @@ JENKINS_PLUGINS = [ "sectioned-view", "conditional-buildstep", "parameterized-trigger", + "build-blocker-plugin", ] diff --git a/tests/test_build.py b/tests/test_build.py index 1d02763..68e7129 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -88,5 +88,32 @@ def test_console_text(jenkins_env): assert expected_output in jb.last_build.console_output [email protected](10) +def test_abort(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + expected_job_name = "test_abort" + jb = jk.create_job(expected_job_name, "hudson.model.FreeStyleProject") + + with clean_job(jb): + jb.quiet_period = 0 + shell_builder = ShellBuilder.create("echo 'waiting for sleep' && sleep 40") + jb.add_builder(shell_builder) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(expected_job_name).builders) + + # Trigger a build and wait for it to complete + jb.start_build() + async_assert(lambda: jb.last_build) + + async_assert(lambda: "waiting for sleep" in jb.last_build.console_output) + + jb.last_build.abort() + + assert jb.last_build.is_building is False + assert jb.last_build.result == "ABORTED" + + if __name__ == "__main__": pytest.main([__file__, "-v", "-s"]) diff --git a/tests/test_build_queue.py b/tests/test_build_queue.py index eb0d335..79bea8f 100644 --- a/tests/test_build_queue.py +++ b/tests/test_build_queue.py @@ -83,5 +83,19 @@ def test_start_build_returned_queue_item(jenkins_env): assert queue.items[0] == item +def test_queue_get_build(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + jb = jk.create_job("test_queue_get_build", "hudson.model.FreeStyleProject") + with clean_job(jb): + jb.quiet_period = 0 + item = jb.start_build() + + async_assert(lambda: not item.waiting) + + bld = item.build + assert bld is not None + assert bld == jb.last_build + + if __name__ == "__main__": pytest.main([__file__, "-v", "-s"]) diff --git a/tests/test_job_properties/test_build_blocker.py b/tests/test_job_properties/test_build_blocker.py new file mode 100644 index 0000000..e884044 --- /dev/null +++ b/tests/test_job_properties/test_build_blocker.py @@ -0,0 +1,209 @@ +import pytest +from pyjen.jenkins import Jenkins +from pyjen.plugins.buildblocker import BuildBlockerProperty +from pyjen.plugins.shellbuilder import ShellBuilder +from ..utils import async_assert, clean_job + + +def test_add_build_blocker(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_add_build_blocker" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_job_name = "MyCoolJob" + build_blocker = BuildBlockerProperty.create(expected_job_name) + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + assert isinstance(properties, list) + assert len(properties) == 1 + assert isinstance(properties[0], BuildBlockerProperty) + + +def test_multiple_blocking_jobs(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_multiple_blocking_jobs" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(["ShouldNotSeeMe"]) + build_blocker.blockers = expected_jobs + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + blockers = prop.blockers + assert isinstance(blockers, list) + assert len(blockers) == 2 + assert expected_jobs[0] in blockers + assert expected_jobs[1] in blockers + + +def test_default_queue_scan(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_default_queue_scan" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(expected_jobs) + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + assert prop.queue_scan == "DISABLED" + + +def test_custom_queue_scan(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_custom_queue_scan" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + expected_type = "ALL" + build_blocker = BuildBlockerProperty.create(expected_jobs) + build_blocker.queue_scan = expected_type + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + assert prop.queue_scan == expected_type + + +def test_invalid_queue_scan_type(): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(expected_jobs) + with pytest.raises(ValueError): + build_blocker.queue_scan = "FuBar" + + +def test_default_block_level(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_default_block_level" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(expected_jobs) + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + assert prop.level == "GLOBAL" + + +def test_custom_block_level(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_custom_block_level" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + expected_type = "NODE" + build_blocker = BuildBlockerProperty.create(expected_jobs) + build_blocker.level = expected_type + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + assert prop.level == expected_type + + +def test_invalid_block_level(): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(expected_jobs) + with pytest.raises(ValueError): + build_blocker.level = "FuBar" + + +def test_default_queue_scan(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_default_queue_scan" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + expected_jobs = ["MyCoolJob1", "MyCoolJob2"] + build_blocker = BuildBlockerProperty.create(expected_jobs) + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + prop = properties[0] + assert prop.queue_scan == "DISABLED" + + +def test_disable_build_blocker(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name = "test_disable_build_blocker" + jb = jk.create_job(job_name, "hudson.model.FreeStyleProject") + with clean_job(jb): + build_blocker = BuildBlockerProperty.create("MyJob") + build_blocker.disable() + jb.quiet_period = 0 + jb.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name).properties) + properties = jk.find_job(job_name).properties + + assert properties[0].is_enabled is False + + +def test_build_blocker_functionality(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + job_name1 = "test_build_blocker_functionality1" + jb1 = jk.create_job(job_name1, "hudson.model.FreeStyleProject") + with clean_job(jb1): + job_name2 = "test_build_blocker_functionality2" + jb2 = jk.create_job(job_name2, "hudson.model.FreeStyleProject") + with clean_job(jb2): + expected_jobs = job_name2 + build_blocker = BuildBlockerProperty.create(expected_jobs) + jb1.quiet_period = 0 + jb1.add_property(build_blocker) + + # Get a fresh copy of our job to ensure we have an up to date + # copy of the config.xml for the job + async_assert(lambda: jk.find_job(job_name1).properties) + + build_step = ShellBuilder.create("sleep 10") + jb2.quiet_period = 0 + jb2.add_builder(build_step) + async_assert(lambda: jb2.builders) + queue2 = jb2.start_build() + + async_assert(lambda: not queue2.waiting) + + queue1 = jb1.start_build() + assert job_name2 in queue1.reason + + queue2.build.abort() + assert queue1.waiting is False + + +if __name__ == "__main__": + pytest.main([__file__, "-v", "-s"])
Write tests for build blocker plugin The build blocker plugin has very little code coverage atm. This needs to be improved.
0.0
c4c268c0e359691f8fc034982a40cbaa6fae46f6
[ "tests/test_job_properties/test_build_blocker.py::test_invalid_queue_scan_type", "tests/test_job_properties/test_build_blocker.py::test_invalid_block_level" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-21 18:19:18+00:00
mit
789
TheFriendlyCoder__pyjen-38
diff --git a/.gitignore b/.gitignore index a5cda0c..a4dd3e7 100644 --- a/.gitignore +++ b/.gitignore @@ -100,4 +100,5 @@ logs/ py?/ .idea -.vscode \ No newline at end of file +.vscode +container_id.txt \ No newline at end of file diff --git a/src/pyjen/jenkins.py b/src/pyjen/jenkins.py index 1be4364..435f20b 100644 --- a/src/pyjen/jenkins.py +++ b/src/pyjen/jenkins.py @@ -86,22 +86,19 @@ class Jenkins(JenkinsAPI): :rtype: :class:`bool` """ try: - version = self.version + if self.jenkins_headers: + return True + return False except RequestException as err: self._log.error("Jenkins connection failed: %s.", err) return False - if version is None or version == "" or version == "Unknown": - self._log.error("Invalid Jenkins version detected: '%s'", version) - return False - return True - @property def version(self): """Gets the version of Jenkins pointed to by this object :return: Version number of the currently running Jenkins instance - :rtype: :class:`str` + :rtype: :class:`tuple` """ return self.jenkins_version @@ -334,7 +331,7 @@ class Jenkins(JenkinsAPI): return None @property - def plugin_manager(self): # pragma: no cover + def plugin_manager(self): """object which manages the plugins installed on this Jenkins :returns: diff --git a/tox.ini b/tox.ini index e920431..b2ec0c0 100644 --- a/tox.ini +++ b/tox.ini @@ -9,8 +9,9 @@ whitelist_externals = bash commands = rm -rf dist + rm -rf build python setup.py bdist_wheel - /bin/bash -c 'pip install dist/*.whl' + /bin/bash -c 'pip install -U dist/*.whl' pylint setup.py - bash -c "source toxenv.sh; pylint ./src/$PROJECT_NAME" bash -c "source toxenv.sh; pytest {posargs} ./tests -v --cov-report html --cov $PROJECT_NAME --no-cov-on-fail" @@ -33,4 +34,26 @@ whitelist_externals = bash commands = bash -c "source toxenv.sh; sphinx-apidoc -f -e -o ./docs/ src/$PROJECT_NAME" - python setup.py build_sphinx \ No newline at end of file + python setup.py build_sphinx + +[testenv:py3-tests] +deps = -rtests/python3.reqs +whitelist_externals = + rm + bash +commands = + rm -rf dist + rm -rf build + python setup.py bdist_wheel + /bin/bash -c 'pip install -U dist/*.whl' + bash -c "source toxenv.sh; pytest {posargs} ./tests -v --cov-report html --cov $PROJECT_NAME --no-cov-on-fail" + + +[testenv:py3-lint] +deps = -rtests/python3.reqs +whitelist_externals = + bash +commands = + pylint setup.py + bash -c "source toxenv.sh; pylint ./src/$PROJECT_NAME" +
TheFriendlyCoder/pyjen
5adc3153fe62af0691f7751cdf97b7f52e00cf77
diff --git a/tests/conftest.py b/tests/conftest.py index cfa0ac4..4b5187c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -143,6 +143,9 @@ def jenkins_env(request, configure_logger): with open(container_id_file) as file_handle: container_id = file_handle.read().strip() log.info("Reusing existing container %s", container_id) + + # TODO: Detect when the ID in the file is invalid and re-create + # the docker environment on the fly else: res = client.create_container( image_name, host_config=hc, volumes=["/var/jenkins_home"]) @@ -200,6 +203,23 @@ def jenkins_env(request, configure_logger): log.info("Done Docker cleanup") [email protected](scope="function", autouse=True) +def clear_global_state(): + """Clears all global state from the PyJen library + + This fixture is a total hack to compensate for the use of global state + in the PyJen library. My hope is to break dependency on this global state + and eliminate the need for this fixture completely + """ + yield + from pyjen.utils.jenkins_api import JenkinsAPI + JenkinsAPI.creds = () + JenkinsAPI.ssl_verify_enabled = False + JenkinsAPI.crumb_cache = None + JenkinsAPI.jenkins_root_url = None + JenkinsAPI.jenkins_headers_cache = None + + def pytest_collection_modifyitems(config, items): """Applies command line customizations to filter tests to be run""" if not config.getoption("--skip-docker"): diff --git a/tests/test_jenkins.py b/tests/test_jenkins.py index ba8cc6c..ba887fd 100644 --- a/tests/test_jenkins.py +++ b/tests/test_jenkins.py @@ -1,13 +1,166 @@ from pyjen.jenkins import Jenkins -from mock import MagicMock +from mock import MagicMock, PropertyMock, patch import pytest -from mock import PropertyMock from pytest import raises -from pyjen.job import Job -from pyjen.view import View -from pyjen.utils.jenkins_api import JenkinsAPI +from pyjen.exceptions import PluginNotSupportedError +def test_simple_connection(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + assert jk.connected + + +def test_not_connected(): + jk = Jenkins("https://0.0.0.0") + assert not jk.connected + + +def test_failed_connection_check(): + with patch("pyjen.utils.jenkins_api.requests") as req: + mock_response = MagicMock() + mock_response.headers = None + req.get.return_value = mock_response + + jk = Jenkins("https://0.0.0.0") + assert not jk.connected + + req.get.assert_called_once() + + +def test_get_version(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + assert jk.version + assert isinstance(jk.version, tuple) + + +def test_is_shutting_down(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + assert not jk.is_shutting_down + + +def test_cancel_shutdown_not_quietdown_mode(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + assert not jk.is_shutting_down + jk.cancel_shutdown() + assert not jk.is_shutting_down + + +def test_cancel_shutdown(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + try: + jk.prepare_shutdown() + assert jk.is_shutting_down + jk.cancel_shutdown() + assert not jk.is_shutting_down + finally: + jk.cancel_shutdown() + + +def test_prepare_shutdown(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + try: + jk.prepare_shutdown() + assert jk.is_shutting_down + finally: + jk.cancel_shutdown() + + +def test_find_non_existent_job(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + jb = jk.find_job("DoesNotExistJob") + assert jb is None + + +def test_get_default_view(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + v = jk.default_view + assert v is not None + assert v.url.startswith(jenkins_env["url"]) + assert v.url == jenkins_env["url"] + "/view/all/" + + +def test_get_views(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + v = jk.views + + assert v is not None + assert isinstance(v, list) + assert len(v) == 1 + assert v[0].name == "all" + + +def test_find_view(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + v = jk.find_view("all") + + assert v is not None + assert v.url == jenkins_env["url"] + "/view/all/" + + +def test_find_missing_view(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + v = jk.find_view("DoesNotExist") + + assert v is None + + +def test_get_nodes(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + nodes = jk.nodes + + assert nodes is not None + assert isinstance(nodes, list) + assert len(nodes) == 1 + assert nodes[0].name == "master" + + +def test_find_node(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + node = jk.find_node("master") + + assert node is not None + assert node.name == "master" + + +def test_find_node_not_exists(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + node = jk.find_node("NodeDoesNotExist") + + assert node is None + + +def test_find_user(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + user = jk.find_user(jenkins_env["admin_user"]) + assert user is not None + assert user.full_name == jenkins_env["admin_user"] + + +def test_find_user_not_exists(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + user = jk.find_user("UserDoesNotExist") + assert user is None + + +def test_get_plugin_manager(jenkins_env): + jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) + pm = jk.plugin_manager + + assert pm is not None + + +# TODO: Fix this test so coverage works correctly +# TODO: apply fix for pip install wheel file in my template project and elsewhere +# TODO: Find a way to get pycharm to preserve docker container +def test_get_plugin_template_not_supported(): + jk = Jenkins("http://0.0.0.0") + with raises(PluginNotSupportedError): + res = jk.get_plugin_template("DoesNotExistTemplate") + assert res is None + + +# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# legacy tests fake_jenkins_url = "http://localhost:8080/" fake_default_view_name = "MyPrimaryView" fake_default_view_url = fake_jenkins_url + "view/" + fake_default_view_name + "/" @@ -27,27 +180,6 @@ fake_jenkins_data = { ] } -fake_jenkins_headers = { - "x-jenkins": "2.0.0" -} - - -def test_simple_connection(jenkins_env): - jk = Jenkins(jenkins_env["url"], (jenkins_env["admin_user"], jenkins_env["admin_token"])) - assert jk.connected - - [email protected] -def patch_jenkins_api(monkeypatch): - mock_api_data = MagicMock() - mock_api_data.return_value = fake_jenkins_data - monkeypatch.setattr(Jenkins, "get_api_data", mock_api_data) - - mock_headers = PropertyMock() - mock_headers.return_value = fake_jenkins_headers - monkeypatch.setattr(Jenkins, "jenkins_headers", mock_headers) - - def get_mock_api_data(field, data): tmp_data = fake_jenkins_data.copy() tmp_data[field] = data @@ -57,6 +189,9 @@ def get_mock_api_data(field, data): def test_init(): + # THIS TEST SHOULD BE DEPRECATED AS SOON AS WE ELIMINATE GLOBAL STATE + # FROM THE PYJEN API + from pyjen.utils.jenkins_api import JenkinsAPI jenkins_url = "http://localhost:8080" jenkins_user = "MyUser" jenkins_pw = "MyPass" @@ -71,12 +206,6 @@ def test_init(): assert JenkinsAPI.ssl_verify_enabled is True -def test_get_version(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - - assert j.version == (2, 0, 0) - - def test_get_unknown_version(monkeypatch): from requests.exceptions import InvalidHeader mock_header = PropertyMock() @@ -88,40 +217,6 @@ def test_get_unknown_version(monkeypatch): j.version -def test_prepare_shutdown(monkeypatch): - mock_post = MagicMock() - monkeypatch.setattr(Jenkins, "post", mock_post) - - jenkins_url = "http://localhost:8080" - j = Jenkins(jenkins_url) - j.prepare_shutdown() - - mock_post.assert_called_once_with(jenkins_url + "/quietDown") - - -def test_cancel_shutdown(monkeypatch): - mock_post = MagicMock() - monkeypatch.setattr(Jenkins, "post", mock_post) - - jenkins_url = "http://localhost:8080" - j = Jenkins(jenkins_url) - j.cancel_shutdown() - - mock_post.assert_called_once_with(jenkins_url + "/cancelQuietDown") - - -def test_is_shutting_down(patch_jenkins_api): - - j = Jenkins("http://localhost:8080") - assert j.is_shutting_down is True - - -def test_find_non_existent_job(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - jb = j.find_job("DoesNotExistJob") - assert jb is None - - def test_find_job(monkeypatch): expected_job_name = "MyJob" expected_job_url = "http://localhost:8080/job/MyJob/" @@ -134,50 +229,9 @@ def test_find_job(monkeypatch): j = Jenkins("http://localhost:8080") jb = j.find_job("MyJob") - assert isinstance(jb, Job) assert jb.url == expected_job_url -def test_get_default_view(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - v = j.default_view - - assert v.url == fake_jenkins_url + "view/" + fake_default_view_name + "/" - - -def test_get_multiple_views(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - views = j.views - - assert len(views) == 2 - for cur_view in views: - assert cur_view.url in [fake_second_view_url, fake_default_view_url] - assert views[0].url != views[1].url - - -def test_find_view(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - v = j.find_view(fake_second_view_name) - - assert isinstance(v, View) - assert v.url == fake_second_view_url - - -def test_find_missing_view(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - v = j.find_view("DoesNotExist") - - assert v is None - - -def test_find_view_primary_view(patch_jenkins_api): - j = Jenkins("http://localhost:8080") - v = j.find_view(fake_default_view_name) - - assert isinstance(v, View) - assert v.url == fake_default_view_url - - def test_create_view(monkeypatch): new_view_name = "MyNewView" expected_view_url = fake_jenkins_url + "view/" + new_view_name + "/" @@ -188,7 +242,6 @@ def test_create_view(monkeypatch): j = Jenkins(fake_jenkins_url) v = j.create_view(new_view_name, expected_view_type) - assert isinstance(v, View) assert v.url == expected_view_url assert mock_post.call_count == 1 assert mock_post.call_args[0][0] == fake_jenkins_url + "createView" @@ -196,27 +249,5 @@ def test_create_view(monkeypatch): assert mock_post.call_args[0][1]['data']['mode'] == expected_view_type -def test_get_multiple_nodes(monkeypatch): - mock_api_data = MagicMock() - fake_node1_url = fake_jenkins_url + "computer/(master)/" - fake_node2_url = fake_jenkins_url + "computer/remoteNode1/" - - fake_api_data = { - "computer": [ - {"displayName": "master"}, - {"displayName": "remoteNode1"} - ] - } - mock_api_data.return_value = fake_api_data - monkeypatch.setattr(Jenkins, "get_api_data", mock_api_data) - - j = Jenkins("http://localhost:8080") - nodes = j.nodes - - assert len(nodes) == 2 - for cur_node in nodes: - assert cur_node.url in [fake_node1_url, fake_node2_url] - assert nodes[0].url != nodes[1].url - if __name__ == "__main__": pytest.main([__file__, "-v", "-s"])
Add more test coverage for jenkins.py We need to improve the unit test coverage on jenkins.py module. In the process, we need to add more tests that leverage the new Docker service, and make sure all tests for this module are compliant with py.test conventions.
0.0
5adc3153fe62af0691f7751cdf97b7f52e00cf77
[ "tests/test_jenkins.py::test_failed_connection_check" ]
[ "tests/test_jenkins.py::test_not_connected", "tests/test_jenkins.py::test_get_plugin_template_not_supported", "tests/test_jenkins.py::test_init", "tests/test_jenkins.py::test_get_unknown_version", "tests/test_jenkins.py::test_find_job", "tests/test_jenkins.py::test_create_view" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-02-16 17:28:19+00:00
mit
790
TheUncleKai__bbutils-20
diff --git a/bbutil/__init__.py b/bbutil/__init__.py index d289f07..f758209 100644 --- a/bbutil/__init__.py +++ b/bbutil/__init__.py @@ -59,7 +59,7 @@ __major__ = 4 __minor__ = 0 #: version patch -__patch__ = 5 +__patch__ = 6 #: package version __version__ = "{0:d}.{1:d}.{2:d}.{3:d}".format(__milestone__, __major__, __minor__, __patch__) diff --git a/bbutil/logging/__init__.py b/bbutil/logging/__init__.py index c5e9dbe..f231310 100755 --- a/bbutil/logging/__init__.py +++ b/bbutil/logging/__init__.py @@ -37,7 +37,7 @@ __all__ = [ _index = { 0: ["INFORM", "WARN", "ERROR", "EXCEPTION", "TIMER", "PROGRESS"], 1: ["INFORM", "DEBUG1", "WARN", "ERROR", "EXCEPTION", "TIMER", "PROGRESS"], - 2: ["INFORM", "DEBUG1", "DEBUG1", "WARN", "ERROR", "EXCEPTION", "TIMER", "PROGRESS"], + 2: ["INFORM", "DEBUG1", "DEBUG2", "WARN", "ERROR", "EXCEPTION", "TIMER", "PROGRESS"], 3: ["INFORM", "DEBUG1", "DEBUG2", "DEBUG3", "WARN", "ERROR", "EXCEPTION", "TIMER", "PROGRESS"] } diff --git a/bbutil/logging/writer/console.py b/bbutil/logging/writer/console.py index b769bf7..bdc2386 100755 --- a/bbutil/logging/writer/console.py +++ b/bbutil/logging/writer/console.py @@ -84,6 +84,7 @@ class ConsoleWriter(Writer): self.styles: Dict[str, _Style] = _schemes self.encoding: str = "" + self.app_space: int = 0 self.text_space: int = 15 self.seperator: str = "|" self.length: int = 0 @@ -103,6 +104,10 @@ class ConsoleWriter(Writer): if item is not None: self.text_space = item + item = kwargs.get("app_space", None) + if item is not None: + self.app_space = item + item = kwargs.get("seperator", None) if item is not None: self.seperator = item @@ -192,7 +197,10 @@ class ConsoleWriter(Writer): return def _create_color(self, item: Message, text: str) -> str: - appname = "{0:s} ".format(item.app).ljust(self.text_space) + _app_space = self.app_space + if self.app_space == 0: + _app_space = len(item.app) + 5 + appname = "{0:s} ".format(item.app).ljust(_app_space) scheme = self.styles[item.level].scheme if item.tag == "":
TheUncleKai/bbutils
79e59c76c09b1f76cc67a3d2b1bcad484ce0029b
diff --git a/tests.json b/tests.json index efb2357..5e650f7 100644 --- a/tests.json +++ b/tests.json @@ -82,6 +82,10 @@ "test_write_04", "test_write_05", "test_write_06", + "test_write_07", + "test_write_08", + "test_write_09", + "test_write_10", "test_clear_01", "test_clear_02" ] diff --git a/tests/logging/console.py b/tests/logging/console.py index e7ce01a..505e772 100755 --- a/tests/logging/console.py +++ b/tests/logging/console.py @@ -21,10 +21,15 @@ import sys import unittest import unittest.mock as mock -from bbutil.logging.writer.console import ConsoleWriter +import colorama + +from bbutil.logging.writer.console import ConsoleWriter, _Style from bbutil.logging.types import Message, Progress, Writer +RESET_ALL = colorama.Style.RESET_ALL + + class Callback(object): def __init__(self, writer: Writer): @@ -241,6 +246,157 @@ class TestConsoleWriter(unittest.TestCase): self.assertFalse(write_called) return + def test_write_07(self): + message = Message(app="TEST", level="INFORM", tag="TEST", content="This is a test!") + + _style = _Style("INFORM", "BRIGHT", "GREEN", "") + + item = ConsoleWriter() + item.open() + item.stdout = SysWrite() + + item.write(message) + + write_called = item.stdout.write.called + call = item.stdout.write.call_args_list[0] + (args, kwargs) = call + data = args[0] + + print(data) + + _tag = "TEST".ljust(15) + _app_space = len("TEST") + 5 + _app = "{0:s} ".format("TEST").ljust(_app_space) + + content = "{0:s}{1:s}{2:s} {3:s}{4:s} {5:s}{6:s}\n".format(RESET_ALL, + _app, + _style.scheme, + _tag, + "|", + RESET_ALL, + "This is a test!") + + self.assertTrue(write_called) + self.assertIn(message.app, data) + self.assertIn(message.tag, data) + self.assertIn(message.content, data) + self.assertEqual(content, data) + return + + def test_write_08(self): + message = Message(app="TEST", level="INFORM", tag="TEST", content="This is a test!") + + _style = _Style("INFORM", "BRIGHT", "GREEN", "") + + item = ConsoleWriter() + item.setup(app_space=15) + item.open() + item.stdout = SysWrite() + + item.write(message) + + write_called = item.stdout.write.called + call = item.stdout.write.call_args_list[0] + (args, kwargs) = call + data = args[0] + + print(data) + + _tag = "TEST".ljust(15) + _app_space = len("TEST") + 5 + _app = "{0:s} ".format("TEST").ljust(15) + + content = "{0:s}{1:s}{2:s} {3:s}{4:s} {5:s}{6:s}\n".format(RESET_ALL, + _app, + _style.scheme, + _tag, + "|", + RESET_ALL, + "This is a test!") + + self.assertTrue(write_called) + self.assertIn(message.app, data) + self.assertIn(message.tag, data) + self.assertIn(message.content, data) + self.assertEqual(content, data) + return + + def test_write_09(self): + message = Message(app="TEST", level="INFORM", tag="TEST", content="This is a test!") + + _style = _Style("INFORM", "BRIGHT", "GREEN", "") + + item = ConsoleWriter() + item.setup(app_space=10) + item.open() + item.stdout = SysWrite() + + item.write(message) + + write_called = item.stdout.write.called + call = item.stdout.write.call_args_list[0] + (args, kwargs) = call + data = args[0] + + print(data) + + _tag = "TEST".ljust(15) + _app_space = len("TEST") + 5 + _app = "{0:s} ".format("TEST").ljust(15) + + content = "{0:s}{1:s}{2:s} {3:s}{4:s} {5:s}{6:s}\n".format(RESET_ALL, + _app, + _style.scheme, + _tag, + "|", + RESET_ALL, + "This is a test!") + + self.assertTrue(write_called) + self.assertIn(message.app, data) + self.assertIn(message.tag, data) + self.assertIn(message.content, data) + self.assertNotEqual(content, data) + return + + def test_write_10(self): + message = Message(app="TEST", level="INFORM", tag="TEST", content="This is a test!") + + _style = _Style("INFORM", "BRIGHT", "GREEN", "") + + item = ConsoleWriter() + item.setup(text_space=10) + item.open() + item.stdout = SysWrite() + + item.write(message) + + write_called = item.stdout.write.called + call = item.stdout.write.call_args_list[0] + (args, kwargs) = call + data = args[0] + + print(data) + + _tag = "TEST".ljust(10) + _app_space = len("TEST") + 5 + _app = "{0:s} ".format("TEST").ljust(_app_space) + + content = "{0:s}{1:s}{2:s} {3:s}{4:s} {5:s}{6:s}\n".format(RESET_ALL, + _app, + _style.scheme, + _tag, + "|", + RESET_ALL, + "This is a test!") + + self.assertTrue(write_called) + self.assertIn(message.app, data) + self.assertIn(message.tag, data) + self.assertIn(message.content, data) + self.assertEqual(content, data) + return + def test_clear_01(self): message = Message(app="TEST", content="This is a test!", raw=True)
Fix appname bug in logging Fix appname bug in logging, it uses the same width as the tags. Thats stupid.
0.0
79e59c76c09b1f76cc67a3d2b1bcad484ce0029b
[ "tests/logging/console.py::TestConsoleWriter::test_write_07", "tests/logging/console.py::TestConsoleWriter::test_write_09", "tests/logging/console.py::TestConsoleWriter::test_write_10" ]
[ "tests/logging/console.py::TestConsoleWriter::test_add_style", "tests/logging/console.py::TestConsoleWriter::test_clear_01", "tests/logging/console.py::TestConsoleWriter::test_clear_02", "tests/logging/console.py::TestConsoleWriter::test_open", "tests/logging/console.py::TestConsoleWriter::test_write_01", "tests/logging/console.py::TestConsoleWriter::test_write_02", "tests/logging/console.py::TestConsoleWriter::test_write_03", "tests/logging/console.py::TestConsoleWriter::test_write_04", "tests/logging/console.py::TestConsoleWriter::test_write_05", "tests/logging/console.py::TestConsoleWriter::test_write_06", "tests/logging/console.py::TestConsoleWriter::test_write_08" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-10 15:08:12+00:00
apache-2.0
791
TheUncleKai__bbutils-31
diff --git a/bbutil/__init__.py b/bbutil/__init__.py index 9255076..0c14292 100644 --- a/bbutil/__init__.py +++ b/bbutil/__init__.py @@ -21,15 +21,15 @@ from bbutil.logging import Logging __all__ = [ "database", - "logging", "lang", + "logging", + "worker", "data", "file", "utils", "log", - "set_log" ] diff --git a/bbutil/worker/__init__.py b/bbutil/worker/__init__.py new file mode 100644 index 0000000..33e645f --- /dev/null +++ b/bbutil/worker/__init__.py @@ -0,0 +1,141 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +import abc +import threading +import time + +from abc import ABCMeta +from dataclasses import dataclass +from typing import Optional + +import bbutil +from bbutil.worker.callback import Callback + +__all__ = [ + "Worker", + + "callback" +] + + +@dataclass +class Worker(metaclass=ABCMeta): + + id: str = "" + abort: bool = False + interval: float = 0.01 + + _callback: Optional[Callback] = None + _error: bool = False + _running: bool = True + + @property + def error(self) -> bool: + return self._error + + @abc.abstractmethod + def prepare(self) -> bool: + pass + + @abc.abstractmethod + def run(self) -> bool: + pass + + @abc.abstractmethod + def close(self) -> bool: + pass + + def set_callback(self, **kwargs): + if self._callback is None: + self._callback = Callback() + + self._callback.set_callback(**kwargs) + return + + def _do_step(self, step: str, function, callback_func): + if self.abort is True: + self._running = False + self.abort = False + self._callback.do_abort() + bbutil.log.warn(self.id, "Abort {0:s}".format(step)) + return + + callback_func() + + _check = function() + if _check is False: + self._error = True + bbutil.log.error("{0:s}: {1:s} failed!".format(self.id, step)) + + if self._error is True: + self._running = False + return + + def _execute(self): + if self._callback is None: + self._callback = Callback() + + self._running = True + self._callback.do_start() + + self._do_step("prepare", self.prepare, self._callback.do_prepare) + if self._running is False: + self._callback.do_stop() + return + + self._do_step("run", self.run, self._callback.do_run) + if self._running is False: + self._callback.do_stop() + return + + self._do_step("close", self.close, self._callback.do_close) + if self._running is False: + self._callback.do_stop() + return + + self._callback.do_stop() + self._running = False + return + + def start(self): + _t = threading.Thread(target=self._execute) + _t.start() + return + + @property + def is_running(self): + return self._running + + def wait(self): + _run = True + + while _run is True: + time.sleep(self.interval) + + if self._running is False: + _run = False + return + + def execute(self) -> bool: + self._execute() + + if self._error is True: + return False + + return True diff --git a/bbutil/worker/callback.py b/bbutil/worker/callback.py new file mode 100644 index 0000000..15c936c --- /dev/null +++ b/bbutil/worker/callback.py @@ -0,0 +1,95 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +__all__ = [ + "Callback" +] + + +class Callback(object): + + def __init__(self): + self.start = None + self.stop = None + self.prepare = None + self.run = None + self.close = None + self.abort = None + return + + def set_callback(self, **kwargs): + _value = kwargs.get("start", None) + if _value is not None: + self.start = _value + + _value = kwargs.get("stop", None) + if _value is not None: + self.stop = _value + + _value = kwargs.get("prepare", None) + if _value is not None: + self.prepare = _value + + _value = kwargs.get("run", None) + if _value is not None: + self.run = _value + + _value = kwargs.get("close", None) + if _value is not None: + self.close = _value + + _value = kwargs.get("abort", None) + if _value is not None: + self.abort = _value + return + + def do_start(self): + if self.start is None: + return + self.start() + return + + def do_stop(self): + if self.stop is None: + return + self.stop() + return + + def do_prepare(self): + if self.prepare is None: + return + self.prepare() + return + + def do_run(self): + if self.run is None: + return + self.run() + return + + def do_close(self): + if self.close is None: + return + self.close() + return + + def do_abort(self): + if self.abort is None: + return + self.abort() + return
TheUncleKai/bbutils
2e710243639acb979b3c3f986d136aad3428a187
diff --git a/tests.json b/tests.json index d2214b2..233519e 100644 --- a/tests.json +++ b/tests.json @@ -330,7 +330,7 @@ ] }, { - "id": "File.File", + "id": "File", "path": "tests.file", "classname": "TestFile", "tests": [ @@ -355,6 +355,21 @@ "test_folder_06", "test_folder_07" ] + }, + { + "id": "Worker", + "path": "tests.worker", + "classname": "TestWorker", + "tests": [ + "test_worker_01", + "test_worker_02", + "test_worker_03", + "test_worker_04", + "test_worker_05", + "test_worker_06", + "test_worker_07", + "test_worker_08" + ] } ] } diff --git a/tests/helper/__init__.py b/tests/helper/__init__.py index f23f667..71630bf 100644 --- a/tests/helper/__init__.py +++ b/tests/helper/__init__.py @@ -29,6 +29,7 @@ __all__ = [ "file", "sqlite", "table", + "worker", "get_sqlite", "set_log" diff --git a/tests/helper/worker.py b/tests/helper/worker.py new file mode 100644 index 0000000..08cbc1e --- /dev/null +++ b/tests/helper/worker.py @@ -0,0 +1,127 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +from typing import List +from dataclasses import dataclass, field + +import bbutil + +from bbutil.worker import Worker + +__all__ = [ + "CallManager", + "Worker01", + "Worker02" +] + + +@dataclass +class CallManager(object): + + start: int = 0 + stop: int = 0 + prepare: int = 0 + run: int = 0 + close: int = 0 + abort: int = 0 + + def count(self, name: str): + _value = getattr(self, name) + _value += 1 + setattr(self, name, _value) + return + + def setup(self, worker: Worker): + worker.set_callback(start=lambda: self.count("start")) + worker.set_callback(stop=lambda: self.count("stop")) + worker.set_callback(prepare=lambda: self.count("prepare")) + worker.set_callback(run=lambda: self.count("run")) + worker.set_callback(close=lambda: self.count("close")) + worker.set_callback(abort=lambda: self.count("abort")) + return + + def info(self): + bbutil.log.inform("start", "{0:d}".format(self.start)) + bbutil.log.inform("stop", "{0:d}".format(self.stop)) + bbutil.log.inform("prepare", "{0:d}".format(self.prepare)) + bbutil.log.inform("run", "{0:d}".format(self.run)) + bbutil.log.inform("close", "{0:d}".format(self.close)) + bbutil.log.inform("abort", "{0:d}".format(self.abort)) + return + + +@dataclass +class Worker01(Worker): + + exit_prepare: bool = True + exit_run: bool = True + exit_close: bool = True + + def prepare(self) -> bool: + return self.exit_prepare + + def run(self) -> bool: + return self.exit_run + + def close(self) -> bool: + return self.exit_close + + +@dataclass +class Worker02(Worker): + + max: int = 50000 + iterate_list: List[int] = field(default_factory=list) + + def prepare(self) -> bool: + _max = self.max + _range = range(0, _max) + _progress = bbutil.log.progress(_max) + + for n in _range: + self.iterate_list.append(n) + _progress.inc() + + bbutil.log.clear() + return True + + def run(self) -> bool: + _max = len(self.iterate_list) + _progress = bbutil.log.progress(_max) + + n = 0 + for x in self.iterate_list: + self.iterate_list[n] = x + 1 + _progress.inc() + n += 1 + + bbutil.log.clear() + return True + + def close(self) -> bool: + _max = len(self.iterate_list) + _progress = bbutil.log.progress(_max) + + n = 0 + for x in self.iterate_list: + self.iterate_list[n] = x - 1 + _progress.inc() + n += 1 + + bbutil.log.clear() + return True diff --git a/tests/worker.py b/tests/worker.py new file mode 100644 index 0000000..fb6fac0 --- /dev/null +++ b/tests/worker.py @@ -0,0 +1,172 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +import unittest + +import unittest.mock as mock + +from tests.helper import set_log +from tests.helper.worker import CallManager, Worker01, Worker02 + +__all__ = [ + "TestWorker" +] + +oserror = OSError("Something strange did happen!") +mock_oserror = mock.Mock(side_effect=oserror) +mock_remove = mock.Mock() + + +class TestWorker(unittest.TestCase): + """Testing class for locking module.""" + + def setUp(self): + set_log() + return + + def test_worker_01(self): + _worker = Worker01(id="Worker01") + + _check = _worker.execute() + self.assertTrue(_check) + self.assertFalse(_worker.error) + return + + def test_worker_02(self): + _calls = CallManager() + _worker = Worker01(id="Worker01") + _calls.setup(_worker) + + _worker.start() + _worker.wait() + + self.assertFalse(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 1) + self.assertEqual(_calls.close, 1) + self.assertEqual(_calls.abort, 0) + return + + def test_worker_03(self): + _calls = CallManager() + _worker = Worker01(id="Worker01", exit_prepare=False) + _calls.setup(_worker) + + _check = _worker.execute() + self.assertFalse(_check) + self.assertTrue(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 0) + self.assertEqual(_calls.close, 0) + self.assertEqual(_calls.abort, 0) + return + + def test_worker_04(self): + _calls = CallManager() + _worker = Worker01(id="Worker01", exit_run=False) + _calls.setup(_worker) + + _check = _worker.execute() + self.assertFalse(_check) + self.assertTrue(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 1) + self.assertEqual(_calls.close, 0) + self.assertEqual(_calls.abort, 0) + return + + def test_worker_05(self): + _calls = CallManager() + _worker = Worker01(id="Worker01", exit_close=False) + _calls.setup(_worker) + + _check = _worker.execute() + self.assertFalse(_check) + self.assertTrue(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 1) + self.assertEqual(_calls.close, 1) + self.assertEqual(_calls.abort, 0) + return + + def test_worker_06(self): + _calls = CallManager() + _worker = Worker01(id="Worker01") + _calls.setup(_worker) + + _worker.start() + _worker.wait() + + self.assertFalse(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 1) + self.assertEqual(_calls.close, 1) + self.assertEqual(_calls.abort, 0) + return + + def test_worker_07(self): + _calls = CallManager() + _worker = Worker02(id="Worker02", max=250000) + _calls.setup(_worker) + + _worker.start() + _check1 = _worker.is_running + _worker.abort = True + + _worker.wait() + self.assertFalse(_worker.error) + + _calls.info() + self.assertEqual(_calls.start, 1) + self.assertEqual(_calls.stop, 1) + self.assertEqual(_calls.prepare, 1) + self.assertEqual(_calls.run, 0) + self.assertEqual(_calls.close, 0) + self.assertEqual(_calls.abort, 1) + return + + def test_worker_08(self): + _worker = Worker02(id="Worker02", max=250000) + + _worker.start() + _check1 = _worker.is_running + _worker.abort = True + + _worker.wait() + self.assertFalse(_worker.error) + return
Add a worker class Add a worker class with prepare, run and close, also for threading.
0.0
2e710243639acb979b3c3f986d136aad3428a187
[ "tests/worker.py::TestWorker::test_worker_01", "tests/worker.py::TestWorker::test_worker_02", "tests/worker.py::TestWorker::test_worker_03", "tests/worker.py::TestWorker::test_worker_04", "tests/worker.py::TestWorker::test_worker_05", "tests/worker.py::TestWorker::test_worker_06", "tests/worker.py::TestWorker::test_worker_07", "tests/worker.py::TestWorker::test_worker_08" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-08-22 13:46:43+00:00
apache-2.0
792
TheUncleKai__bbutils-32
diff --git a/bbutil/__init__.py b/bbutil/__init__.py index 0c14292..351809b 100644 --- a/bbutil/__init__.py +++ b/bbutil/__init__.py @@ -26,6 +26,7 @@ __all__ = [ "worker", "data", + "execute", "file", "utils", diff --git a/bbutil/execute.py b/bbutil/execute.py new file mode 100644 index 0000000..d274556 --- /dev/null +++ b/bbutil/execute.py @@ -0,0 +1,147 @@ +#!/usr/bin/python3 +# coding=utf-8 + +# Copyright (C) 2020, Siemens Healthcare Diagnostics Products GmbH +# Licensed under the Siemens Inner Source License 1.2, see LICENSE.md. + +import subprocess + +from typing import Optional, List + +import bbutil + +__all__ = [ + "Execute" +] + + +class Execute(object): + + def __init__(self, **kwargs): + self.name: str = "" + self.desc: str = "" + self.commands: List[str] = [] + self.messages: List[str] = [] + self.returncode: int = 0 + self.errors: Optional[List[str]] = None + + self.stdout: Optional[subprocess.PIPE] = subprocess.PIPE + self.stderr: Optional[subprocess.PIPE] = subprocess.PIPE + self.stdin: Optional[subprocess.PIPE] = None + self.call_stdout = None + self.call_stderr = None + + self.setup(**kwargs) + return + + def show_command(self): + line = "" + + for _item in self.commands: + if line == "": + line = _item + else: + line = "{0:s} {1:s}".format(line, _item) + + bbutil.log.debug1(self.name, line) + return + + @staticmethod + def _convert_line(data) -> str: + try: + new = data.decode(encoding='utf-8') + except UnicodeDecodeError: + return "" + new = new.replace("\r\n", "") + new = new.replace("\n", "") + return new + + def setup(self, **kwargs): + item = kwargs.get("commands", None) + if item is not None: + self.commands = item + + item = kwargs.get("name", None) + if item is not None: + self.name = item + + item = kwargs.get("desc", None) + if item is not None: + self.desc = item + + item = kwargs.get("stdout", None) + if item is not None: + self.stdout = item + + item = kwargs.get("stderr", None) + if item is not None: + self.stderr = item + + item = kwargs.get("stdin", None) + if item is not None: + self.stdin = item + + item = kwargs.get("call_stdout", None) + if item is not None: + self.call_stdout = item + + item = kwargs.get("call_stderr", None) + if item is not None: + self.call_stderr = item + return + + def execute(self) -> bool: + self.show_command() + + self.messages = [] + + if self.stdin is not None: + p = subprocess.Popen(self.commands, stdout=self.stdout, stderr=self.stderr, stdin=self.stdin) + else: + p = subprocess.Popen(self.commands, stdout=self.stdout, stderr=self.stderr) + + # parse output and wait for end + while True: + if p.stdout is not None: + for line in p.stdout: + if line is None: + continue + data = self._convert_line(line) + self.messages.append(data) + + if self.call_stdout is not None: + self.call_stdout(data) + + if p.stderr is not None: + for line in p.stderr: + if line is None: + continue + data = self._convert_line(line) + + if self.errors is None: + self.errors = [] + + self.errors.append(data) + + if self.call_stderr is not None: + self.call_stderr(data) + + _poll = p.poll() + if _poll is not None: + break + + self.returncode = p.returncode + + if p.returncode != 0: + bbutil.log.clear() + bbutil.log.error("{0:s} failed!".format(self.desc)) + bbutil.log.error("Process did end with error {0:d}".format(p.returncode)) + if self.errors is not None: + for _line in self.errors: + bbutil.log.error(_line) + else: + for _line in self.messages: + bbutil.log.error(_line) + return False + + return True
TheUncleKai/bbutils
e81b60d63ed32dd6c3dcd411b4dfb0edde36bac0
diff --git a/tests.json b/tests.json index 233519e..1937c23 100644 --- a/tests.json +++ b/tests.json @@ -370,6 +370,18 @@ "test_worker_07", "test_worker_08" ] + }, + { + "id": "Execute", + "path": "tests.execute", + "classname": "TestExecute", + "tests": [ + "test_setup_01", + "test_setup_02", + "test_setup_03", + "test_setup_04", + "test_setup_05" + ] } ] } diff --git a/tests/__init__.py b/tests/__init__.py index 614f1cb..b73dd09 100755 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -23,6 +23,8 @@ __all__ = [ "logging", "data", + "execute", "file", - "utils" + "utils", + "worker" ] diff --git a/tests/execute.py b/tests/execute.py new file mode 100644 index 0000000..d8c0bbd --- /dev/null +++ b/tests/execute.py @@ -0,0 +1,138 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +import unittest + +import unittest.mock as mock + +from bbutil.execute import Execute + +from tests.helper import set_log +from tests.helper.execute import CatchBacks, MockPopen1, MockPopen2, MockPopen3 + +__all__ = [ + "TestExecute" +] + + +oserror = OSError("Something strange did happen!") +mock_oserror = mock.Mock(side_effect=oserror) +mock_remove = mock.Mock() + + +class TestExecute(unittest.TestCase): + """Testing class for locking module.""" + + def setUp(self): + set_log() + return + + def test_setup_01(self): + _execute = Execute() + + _commands = [ + "/usr/bin/ls" + ] + + _execute.setup(name="Test", desc="Print ls", commands=_commands) + + _check = _execute.execute() + self.assertTrue(_check) + self.assertEqual(_execute.returncode, 0) + self.assertIsNone(_execute.errors) + self.assertGreater(len(_execute.messages), 1) + return + + def test_setup_02(self): + _commands = [ + "/usr/bin/ls" + ] + + _execute = Execute(name="Test", desc="Print ls", commands=_commands) + + _check = _execute.execute() + self.assertTrue(_check) + self.assertEqual(_execute.returncode, 0) + self.assertIsNone(_execute.errors) + self.assertGreater(len(_execute.messages), 1) + return + + @mock.patch('subprocess.Popen', new=MockPopen1) + def test_setup_03(self): + + _execute = Execute() + _commands = [ + "/usr/bin/ls", + "-lA" + ] + + _execute.setup(name="Test", desc="Print ls", commands=_commands, stdout="TEST", stderr="TEST", stdin="TEST") + _execute.show_command() + + _check = _execute.execute() + self.assertTrue(_check) + self.assertEqual(_execute.returncode, 0) + self.assertIsNone(_execute.errors) + self.assertGreater(len(_execute.messages), 1) + return + + @mock.patch('subprocess.Popen', new=MockPopen2) + def test_setup_04(self): + + _callbacks = CatchBacks() + + _execute = Execute() + _commands = [ + "/usr/bin/ls" + ] + + _execute.setup(name="Test", desc="Print ls", commands=_commands, + call_stdout=_callbacks.add_stdout, call_stderr=_callbacks.add_stderr) + + _check = _execute.execute() + + self.assertFalse(_check) + self.assertEqual(_execute.returncode, 1) + self.assertIsNotNone(_execute.errors) + self.assertGreater(len(_execute.messages), 1) + self.assertEqual(len(_callbacks.stdout), 22) + self.assertEqual(len(_callbacks.stderr), 11) + return + + @mock.patch('subprocess.Popen', new=MockPopen3) + def test_setup_05(self): + + _callbacks = CatchBacks() + + _execute = Execute() + _commands = [ + "/usr/bin/ls" + ] + + _execute.setup(name="Test", desc="Print ls", commands=_commands, + call_stdout=_callbacks.add_stdout, call_stderr=_callbacks.add_stderr) + + _check = _execute.execute() + + self.assertFalse(_check) + self.assertEqual(_execute.returncode, 1) + self.assertIsNone(_execute.errors) + self.assertGreater(len(_execute.messages), 1) + self.assertEqual(len(_callbacks.stdout), 22) + self.assertEqual(len(_callbacks.stderr), 0) + return diff --git a/tests/helper/__init__.py b/tests/helper/__init__.py index 71630bf..c711b7c 100644 --- a/tests/helper/__init__.py +++ b/tests/helper/__init__.py @@ -26,6 +26,7 @@ from bbutil.utils import full_path __all__ = [ "database", + "execute", "file", "sqlite", "table", diff --git a/tests/helper/execute.py b/tests/helper/execute.py new file mode 100644 index 0000000..97aa0a4 --- /dev/null +++ b/tests/helper/execute.py @@ -0,0 +1,138 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# +# 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. +# +# Copyright (C) 2017, Kai Raphahn <[email protected]> +# + +from typing import Optional +from unittest.mock import Mock + +__all__ = [ + "CatchBacks", + "MockPopen1", + "MockPopen2", + "MockPopen3" +] + + +class CatchBacks(object): + + def __init__(self): + self.stdout = [] + self.stderr = [] + return + + def add_stdout(self, data): + if data is None: + return + self.stdout.append(data) + return + + def add_stderr(self, data): + if data is None: + return + self.stderr.append(data) + return + + +def get_stdout() -> list: + + _line1 = "TEST" + + _excec = UnicodeDecodeError('funnycodec', _line1.encode(), 1, 2, 'This is just a fake reason!') + + _line2 = Mock() + _line2.decode = Mock(side_effect=_excec) + + _stdout = [ + _line1.encode(), + _line2, + None + ] + return _stdout + + +def get_stderr() -> list: + _line1 = "ERROR!" + + _stderr = [ + _line1.encode(), + None + ] + + return _stderr + + +class MockPopen1(object): + + def __init__(self, commands, stdout, stderr, stdin=None): + + self.test_stdout = stdout + self.test_stderr = stderr + self.test_stdin = stdin + self._poll = 0 + self.stdout = get_stdout() + self.stderr = [] + self.returncode = 0 + return + + def poll(self) -> Optional[int]: + if self._poll == 10: + self._poll = 0 + return 1 + self._poll += 1 + return None + + +class MockPopen2(object): + + def __init__(self, commands, stdout, stderr, stdin=None): + + self.test_stdout = stdout + self.test_stderr = stderr + self.test_stdin = stdin + self._poll = 0 + self.stdout = get_stdout() + self.stderr = get_stderr() + self.returncode = 1 + return + + def poll(self) -> Optional[int]: + if self._poll == 10: + self._poll = 0 + return 1 + self._poll += 1 + return None + + +class MockPopen3(object): + + def __init__(self, commands, stdout, stderr, stdin=None): + + self.test_stdout = stdout + self.test_stderr = stderr + self.test_stdin = stdin + self._poll = 0 + self.stdout = get_stdout() + self.stderr = [] + self.returncode = 1 + return + + def poll(self) -> Optional[int]: + if self._poll == 10: + self._poll = 0 + return 1 + self._poll += 1 + return None
Add a simple execute wrapper Add a simple execute wrapper with stdout/stdin catcher.
0.0
e81b60d63ed32dd6c3dcd411b4dfb0edde36bac0
[ "tests/execute.py::TestExecute::test_setup_01", "tests/execute.py::TestExecute::test_setup_02", "tests/execute.py::TestExecute::test_setup_03", "tests/execute.py::TestExecute::test_setup_04", "tests/execute.py::TestExecute::test_setup_05" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-08-23 11:06:36+00:00
apache-2.0
793
Tinche__aiofiles-116
diff --git a/README.rst b/README.rst index 067ddbc..cb6383e 100644 --- a/README.rst +++ b/README.rst @@ -173,6 +173,7 @@ History * Added ``aiofiles.os.{makedirs, removedirs}``. * Added ``aiofiles.os.path.{exists, isfile, isdir, getsize, getatime, getctime, samefile, sameopenfile}``. `#63 <https://github.com/Tinche/aiofiles/pull/63>`_ +* Added `suffix`, `prefix`, `dir` args to ``aiofiles.tempfile.TemporaryDirectory`` 0.7.0 (2021-05-17) `````````````````` diff --git a/src/aiofiles/base.py b/src/aiofiles/base.py index 6e3e80d..f64d00d 100644 --- a/src/aiofiles/base.py +++ b/src/aiofiles/base.py @@ -12,9 +12,9 @@ class AsyncBase: def __aiter__(self): """We are our own iterator.""" return self - + def __repr__(self): - return super().__repr__() + ' wrapping ' + repr(self._file) + return super().__repr__() + " wrapping " + repr(self._file) async def __anext__(self): """Simulate normal file iteration.""" diff --git a/src/aiofiles/tempfile/__init__.py b/src/aiofiles/tempfile/__init__.py index e3363f0..21753aa 100644 --- a/src/aiofiles/tempfile/__init__.py +++ b/src/aiofiles/tempfile/__init__.py @@ -113,10 +113,12 @@ def SpooledTemporaryFile( ) -def TemporaryDirectory(loop=None, executor=None): +def TemporaryDirectory(suffix=None, prefix=None, dir=None, loop=None, executor=None): """Async open a temporary directory""" return AiofilesContextManagerTempDir( - _temporary_directory(loop=loop, executor=executor) + _temporary_directory( + suffix=suffix, prefix=prefix, dir=dir, loop=loop, executor=executor + ) ) @@ -213,12 +215,15 @@ async def _spooled_temporary_file( return AsyncSpooledTemporaryFile(f, loop=loop, executor=executor) -async def _temporary_directory(loop=None, executor=None): +async def _temporary_directory( + suffix=None, prefix=None, dir=None, loop=None, executor=None +): """Async method to open a temporary directory with async interface""" if loop is None: loop = asyncio.get_event_loop() - f = await loop.run_in_executor(executor, syncTemporaryDirectory) + cb = partial(syncTemporaryDirectory, suffix, prefix, dir) + f = await loop.run_in_executor(executor, cb) return AsyncTemporaryDirectory(f, loop=loop, executor=executor)
Tinche/aiofiles
8895eb48b6004c8677da5841e2504a73eb8fad5e
diff --git a/tests/test_os.py b/tests/test_os.py index d87b86c..d32ef97 100644 --- a/tests/test_os.py +++ b/tests/test_os.py @@ -19,9 +19,9 @@ async def test_stat(): @pytest.mark.asyncio async def test_remove(): """Test the remove call.""" - filename = join(dirname(__file__), 'resources', 'test_file2.txt') - with open(filename, 'w') as f: - f.write('Test file for remove call') + filename = join(dirname(__file__), "resources", "test_file2.txt") + with open(filename, "w") as f: + f.write("Test file for remove call") assert exists(filename) await aiofiles.os.remove(filename) @@ -31,7 +31,7 @@ async def test_remove(): @pytest.mark.asyncio async def test_mkdir_and_rmdir(): """Test the mkdir and rmdir call.""" - directory = join(dirname(__file__), 'resources', 'test_dir') + directory = join(dirname(__file__), "resources", "test_dir") await aiofiles.os.mkdir(directory) assert isdir(directory) await aiofiles.os.rmdir(directory) @@ -41,8 +41,8 @@ async def test_mkdir_and_rmdir(): @pytest.mark.asyncio async def test_rename(): """Test the rename call.""" - old_filename = join(dirname(__file__), 'resources', 'test_file1.txt') - new_filename = join(dirname(__file__), 'resources', 'test_file2.txt') + old_filename = join(dirname(__file__), "resources", "test_file1.txt") + new_filename = join(dirname(__file__), "resources", "test_file2.txt") await aiofiles.os.rename(old_filename, new_filename) assert exists(old_filename) is False and exists(new_filename) await aiofiles.os.rename(new_filename, old_filename) @@ -128,9 +128,7 @@ async def test_sendfile_socket(unused_tcp_port): server = await asyncio.start_server(serve_file, port=unused_tcp_port) - reader, writer = await asyncio.open_connection( - "127.0.0.1", unused_tcp_port - ) + reader, writer = await asyncio.open_connection("127.0.0.1", unused_tcp_port) actual_contents = await reader.read() writer.close() @@ -143,7 +141,7 @@ async def test_sendfile_socket(unused_tcp_port): @pytest.mark.asyncio async def test_exists(): """Test path.exists call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.exists(filename) assert result @@ -151,7 +149,7 @@ async def test_exists(): @pytest.mark.asyncio async def test_isfile(): """Test path.isfile call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.isfile(filename) assert result @@ -159,7 +157,7 @@ async def test_isfile(): @pytest.mark.asyncio async def test_isdir(): """Test path.isdir call.""" - filename = join(dirname(__file__), 'resources') + filename = join(dirname(__file__), "resources") result = await aiofiles.os.path.isdir(filename) assert result @@ -167,7 +165,7 @@ async def test_isdir(): @pytest.mark.asyncio async def test_getsize(): """Test path.getsize call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.getsize(filename) assert result == 10 @@ -175,7 +173,7 @@ async def test_getsize(): @pytest.mark.asyncio async def test_samefile(): """Test path.samefile call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.samefile(filename, filename) assert result @@ -183,7 +181,7 @@ async def test_samefile(): @pytest.mark.asyncio async def test_sameopenfile(): """Test path.samefile call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.samefile(filename, filename) assert result @@ -191,7 +189,7 @@ async def test_sameopenfile(): @pytest.mark.asyncio async def test_getmtime(): """Test path.getmtime call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.getmtime(filename) assert result @@ -199,7 +197,7 @@ async def test_getmtime(): @pytest.mark.asyncio async def test_getatime(): """Test path.getatime call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.getatime(filename) assert result @@ -207,6 +205,6 @@ async def test_getatime(): @pytest.mark.asyncio async def test_getctime(): """Test path. call.""" - filename = join(dirname(__file__), 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "resources", "test_file1.txt") result = await aiofiles.os.path.getctime(filename) assert result diff --git a/tests/test_tempfile.py b/tests/test_tempfile.py index c6e9542..971f9b9 100644 --- a/tests/test_tempfile.py +++ b/tests/test_tempfile.py @@ -9,24 +9,24 @@ import io @pytest.mark.parametrize("mode", ["r+", "w+", "rb+", "wb+"]) async def test_temporary_file(mode): """Test temporary file.""" - data = b'Hello World!\n' if 'b' in mode else 'Hello World!\n' + data = b"Hello World!\n" if "b" in mode else "Hello World!\n" async with tempfile.TemporaryFile(mode=mode) as f: for i in range(3): - await f.write(data) + await f.write(data) await f.flush() await f.seek(0) async for line in f: assert line == data - + @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["r+", "w+", "rb+", "wb+"]) async def test_named_temporary_file(mode): """Test named temporary file.""" - data = b'Hello World!' if 'b' in mode else 'Hello World!' + data = b"Hello World!" if "b" in mode else "Hello World!" filename = None async with tempfile.NamedTemporaryFile(mode=mode) as f: @@ -42,22 +42,22 @@ async def test_named_temporary_file(mode): assert not os.path.exists(filename) - + @pytest.mark.asyncio @pytest.mark.parametrize("mode", ["r+", "w+", "rb+", "wb+"]) async def test_spooled_temporary_file(mode): """Test spooled temporary file.""" - data = b'Hello World!' if 'b' in mode else 'Hello World!' + data = b"Hello World!" if "b" in mode else "Hello World!" - async with tempfile.SpooledTemporaryFile(max_size=len(data)+1, mode=mode) as f: + async with tempfile.SpooledTemporaryFile(max_size=len(data) + 1, mode=mode) as f: await f.write(data) await f.flush() - if 'b' in mode: + if "b" in mode: assert type(f._file._file) is io.BytesIO await f.write(data) await f.flush() - if 'b' in mode: + if "b" in mode: assert type(f._file._file) is not io.BytesIO await f.seek(0) @@ -65,13 +65,17 @@ async def test_spooled_temporary_file(mode): @pytest.mark.asyncio -async def test_temporary_directory(): [email protected]("prefix, suffix", [("a", "b"), ("c", "d"), ("e", "f")]) +async def test_temporary_directory(prefix, suffix, tmp_path): """Test temporary directory.""" dir_path = None - async with tempfile.TemporaryDirectory() as d: + async with tempfile.TemporaryDirectory( + suffix=suffix, prefix=prefix, dir=tmp_path + ) as d: dir_path = d assert os.path.exists(dir_path) assert os.path.isdir(dir_path) - + assert d[-1] == suffix + assert d.split(os.sep)[-1][0] == prefix assert not os.path.exists(dir_path) diff --git a/tests/threadpool/test_concurrency.py b/tests/threadpool/test_concurrency.py index 2922d66..1411089 100644 --- a/tests/threadpool/test_concurrency.py +++ b/tests/threadpool/test_concurrency.py @@ -57,9 +57,7 @@ async def test_slow_file(monkeypatch, unused_tcp_port): spam_task = asyncio.ensure_future(spam_client()) - reader, writer = await asyncio.open_connection( - "127.0.0.1", port=unused_tcp_port - ) + reader, writer = await asyncio.open_connection("127.0.0.1", port=unused_tcp_port) actual_contents = await reader.read() writer.close() diff --git a/tests/threadpool/test_text.py b/tests/threadpool/test_text.py index 2a3dbcf..8d04039 100644 --- a/tests/threadpool/test_text.py +++ b/tests/threadpool/test_text.py @@ -6,10 +6,10 @@ import pytest @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_simple_iteration(mode): """Test iterating over lines from a file.""" - filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') + filename = join(dirname(__file__), "..", "resources", "multiline_file.txt") async with aioopen(filename, mode=mode) as file: # Append mode needs us to seek. @@ -22,7 +22,7 @@ async def test_simple_iteration(mode): line = await file.readline() if not line: break - assert line.strip() == 'line ' + str(counter) + assert line.strip() == "line " + str(counter) counter += 1 await file.seek(0) @@ -30,19 +30,19 @@ async def test_simple_iteration(mode): # The new iteration pattern: async for line in file: - assert line.strip() == 'line ' + str(counter) + assert line.strip() == "line " + str(counter) counter += 1 assert file.closed @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_simple_readlines(mode): """Test the readlines functionality.""" - filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') + filename = join(dirname(__file__), "..", "resources", "multiline_file.txt") - with open(filename, mode='r') as f: + with open(filename, mode="r") as f: expected = f.readlines() async with aioopen(filename, mode=mode) as file: @@ -57,50 +57,50 @@ async def test_simple_readlines(mode): @pytest.mark.asyncio [email protected]('mode', ['r+', 'w', 'a']) [email protected]("mode", ["r+", "w", "a"]) async def test_simple_flush(mode, tmpdir): """Test flushing to a file.""" - filename = 'file.bin' + filename = "file.bin" full_file = tmpdir.join(filename) - if 'r' in mode: + if "r" in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode) as file: - await file.write('0') # Shouldn't flush. + await file.write("0") # Shouldn't flush. - assert '' == full_file.read_text(encoding='utf8') + assert "" == full_file.read_text(encoding="utf8") await file.flush() - assert '0' == full_file.read_text(encoding='utf8') + assert "0" == full_file.read_text(encoding="utf8") assert file.closed @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_simple_read(mode): """Just read some bytes from a test file.""" - filename = join(dirname(__file__), '..', 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "..", "resources", "test_file1.txt") async with aioopen(filename, mode=mode) as file: await file.seek(0) # Needed for the append mode. actual = await file.read() - assert '' == (await file.read()) - assert actual == open(filename, mode='r').read() + assert "" == (await file.read()) + assert actual == open(filename, mode="r").read() assert file.closed @pytest.mark.asyncio [email protected]('mode', ['w', 'a']) [email protected]("mode", ["w", "a"]) async def test_simple_read_fail(mode, tmpdir): """Try reading some bytes and fail.""" - filename = 'bigfile.bin' - content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE + filename = "bigfile.bin" + content = "0123456789" * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) @@ -114,10 +114,10 @@ async def test_simple_read_fail(mode, tmpdir): @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_staggered_read(mode): """Read bytes repeatedly.""" - filename = join(dirname(__file__), '..', 'resources', 'test_file1.txt') + filename = join(dirname(__file__), "..", "resources", "test_file1.txt") async with aioopen(filename, mode=mode) as file: await file.seek(0) # Needed for the append mode. @@ -129,10 +129,10 @@ async def test_staggered_read(mode): else: break - assert '' == (await file.read()) + assert "" == (await file.read()) expected = [] - with open(filename, mode='r') as f: + with open(filename, mode="r") as f: while True: char = f.read(1) if char: @@ -146,28 +146,28 @@ async def test_staggered_read(mode): @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_simple_seek(mode, tmpdir): """Test seeking and then reading.""" - filename = 'bigfile.bin' - content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE + filename = "bigfile.bin" + content = "0123456789" * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) async with aioopen(str(full_file), mode=mode) as file: await file.seek(4) - assert '4' == (await file.read(1)) + assert "4" == (await file.read(1)) assert file.closed @pytest.mark.asyncio [email protected]('mode', ['w', 'r', 'r+', 'w+', 'a', 'a+']) [email protected]("mode", ["w", "r", "r+", "w+", "a", "a+"]) async def test_simple_close(mode, tmpdir): """Open a file, read a byte, and close it.""" - filename = 'bigfile.bin' - content = '0' * 4 * io.DEFAULT_BUFFER_SIZE + filename = "bigfile.bin" + content = "0" * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) @@ -181,11 +181,11 @@ async def test_simple_close(mode, tmpdir): @pytest.mark.asyncio [email protected]('mode', ['r+', 'w', 'a+']) [email protected]("mode", ["r+", "w", "a+"]) async def test_simple_truncate(mode, tmpdir): """Test truncating files.""" - filename = 'bigfile.bin' - content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE + filename = "bigfile.bin" + content = "0123456789" * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) @@ -194,7 +194,7 @@ async def test_simple_truncate(mode, tmpdir): # The append modes want us to seek first. await file.seek(0) - if 'w' in mode: + if "w" in mode: # We've just erased the entire file. await file.write(content) await file.flush() @@ -202,19 +202,19 @@ async def test_simple_truncate(mode, tmpdir): await file.truncate() - assert '' == full_file.read() + assert "" == full_file.read() @pytest.mark.asyncio [email protected]('mode', ['w', 'r+', 'w+', 'a', 'a+']) [email protected]("mode", ["w", "r+", "w+", "a", "a+"]) async def test_simple_write(mode, tmpdir): """Test writing into a file.""" - filename = 'bigfile.bin' - content = '0' * 4 * io.DEFAULT_BUFFER_SIZE + filename = "bigfile.bin" + content = "0" * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) - if 'r' in mode: + if "r" in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode) as file: @@ -228,13 +228,13 @@ async def test_simple_write(mode, tmpdir): @pytest.mark.asyncio async def test_simple_detach(tmpdir): """Test detaching for buffered streams.""" - filename = 'file.bin' + filename = "file.bin" full_file = tmpdir.join(filename) - full_file.write('0123456789') + full_file.write("0123456789") with pytest.raises(ValueError): # Close will error out. - async with aioopen(str(full_file), mode='r') as file: + async with aioopen(str(full_file), mode="r") as file: raw_file = file.detach() assert raw_file @@ -242,14 +242,14 @@ async def test_simple_detach(tmpdir): with pytest.raises(ValueError): await file.read() - assert b'0123456789' == raw_file.read(10) + assert b"0123456789" == raw_file.read(10) @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_simple_iteration_ctx_mgr(mode): """Test iterating over lines from a file.""" - filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') + filename = join(dirname(__file__), "..", "resources", "multiline_file.txt") async with aioopen(filename, mode=mode) as file: assert not file.closed @@ -258,17 +258,17 @@ async def test_simple_iteration_ctx_mgr(mode): counter = 1 async for line in file: - assert line.strip() == 'line ' + str(counter) + assert line.strip() == "line " + str(counter) counter += 1 assert file.closed @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_name_property(mode): """Test iterating over lines from a file.""" - filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') + filename = join(dirname(__file__), "..", "resources", "multiline_file.txt") async with aioopen(filename, mode=mode) as file: assert file.name == filename @@ -277,10 +277,10 @@ async def test_name_property(mode): @pytest.mark.asyncio [email protected]('mode', ['r', 'r+', 'a+']) [email protected]("mode", ["r", "r+", "a+"]) async def test_mode_property(mode): """Test iterating over lines from a file.""" - filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') + filename = join(dirname(__file__), "..", "resources", "multiline_file.txt") async with aioopen(filename, mode=mode) as file: assert file.mode == mode
TemporaryDirectory is missing keyword arguments from upstream The [synchronous equivalent from the standard library](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory) accepts a few keyword arguments to control the name and location of the created directory. However, `aiofiles.tempfile.TemporaryDirectory` does not accept the same keyword arguments. ``` ... async with aiofiles.tempfile.TemporaryDirectory(dir=working_dir) as temp_dir_str: TypeError: TemporaryDirectory() got an unexpected keyword argument 'dir' ``` Tested using aiofiles version 0.7.0.
0.0
8895eb48b6004c8677da5841e2504a73eb8fad5e
[ "tests/test_tempfile.py::test_temporary_directory[a-b]", "tests/test_tempfile.py::test_temporary_directory[c-d]", "tests/test_tempfile.py::test_temporary_directory[e-f]" ]
[ "tests/test_os.py::test_stat", "tests/test_os.py::test_remove", "tests/test_os.py::test_mkdir_and_rmdir", "tests/test_os.py::test_rename", "tests/test_os.py::test_replace", "tests/test_os.py::test_sendfile_file", "tests/test_os.py::test_sendfile_socket", "tests/test_os.py::test_exists", "tests/test_os.py::test_isfile", "tests/test_os.py::test_isdir", "tests/test_os.py::test_getsize", "tests/test_os.py::test_samefile", "tests/test_os.py::test_sameopenfile", "tests/test_os.py::test_getmtime", "tests/test_os.py::test_getatime", "tests/test_os.py::test_getctime", "tests/test_tempfile.py::test_temporary_file[r+]", "tests/test_tempfile.py::test_temporary_file[w+]", "tests/test_tempfile.py::test_temporary_file[rb+]", "tests/test_tempfile.py::test_temporary_file[wb+]", "tests/test_tempfile.py::test_named_temporary_file[r+]", "tests/test_tempfile.py::test_named_temporary_file[w+]", "tests/test_tempfile.py::test_named_temporary_file[rb+]", "tests/test_tempfile.py::test_named_temporary_file[wb+]", "tests/test_tempfile.py::test_spooled_temporary_file[r+]", "tests/test_tempfile.py::test_spooled_temporary_file[w+]", "tests/test_tempfile.py::test_spooled_temporary_file[rb+]", "tests/test_tempfile.py::test_spooled_temporary_file[wb+]", "tests/threadpool/test_concurrency.py::test_slow_file", "tests/threadpool/test_text.py::test_simple_iteration[r]", "tests/threadpool/test_text.py::test_simple_iteration[r+]", "tests/threadpool/test_text.py::test_simple_iteration[a+]", "tests/threadpool/test_text.py::test_simple_readlines[r]", "tests/threadpool/test_text.py::test_simple_readlines[r+]", "tests/threadpool/test_text.py::test_simple_readlines[a+]", "tests/threadpool/test_text.py::test_simple_flush[r+]", "tests/threadpool/test_text.py::test_simple_flush[w]", "tests/threadpool/test_text.py::test_simple_flush[a]", "tests/threadpool/test_text.py::test_simple_read[r]", "tests/threadpool/test_text.py::test_simple_read[r+]", "tests/threadpool/test_text.py::test_simple_read[a+]", "tests/threadpool/test_text.py::test_simple_read_fail[w]", "tests/threadpool/test_text.py::test_simple_read_fail[a]", "tests/threadpool/test_text.py::test_staggered_read[r]", "tests/threadpool/test_text.py::test_staggered_read[r+]", "tests/threadpool/test_text.py::test_staggered_read[a+]", "tests/threadpool/test_text.py::test_simple_seek[r]", "tests/threadpool/test_text.py::test_simple_seek[r+]", "tests/threadpool/test_text.py::test_simple_seek[a+]", "tests/threadpool/test_text.py::test_simple_close[w]", "tests/threadpool/test_text.py::test_simple_close[r]", "tests/threadpool/test_text.py::test_simple_close[r+]", "tests/threadpool/test_text.py::test_simple_close[w+]", "tests/threadpool/test_text.py::test_simple_close[a]", "tests/threadpool/test_text.py::test_simple_close[a+]", "tests/threadpool/test_text.py::test_simple_truncate[r+]", "tests/threadpool/test_text.py::test_simple_truncate[w]", "tests/threadpool/test_text.py::test_simple_truncate[a+]", "tests/threadpool/test_text.py::test_simple_write[w]", "tests/threadpool/test_text.py::test_simple_write[r+]", "tests/threadpool/test_text.py::test_simple_write[w+]", "tests/threadpool/test_text.py::test_simple_write[a]", "tests/threadpool/test_text.py::test_simple_write[a+]", "tests/threadpool/test_text.py::test_simple_detach", "tests/threadpool/test_text.py::test_simple_iteration_ctx_mgr[r]", "tests/threadpool/test_text.py::test_simple_iteration_ctx_mgr[r+]", "tests/threadpool/test_text.py::test_simple_iteration_ctx_mgr[a+]", "tests/threadpool/test_text.py::test_name_property[r]", "tests/threadpool/test_text.py::test_name_property[r+]", "tests/threadpool/test_text.py::test_name_property[a+]", "tests/threadpool/test_text.py::test_mode_property[r]", "tests/threadpool/test_text.py::test_mode_property[r+]", "tests/threadpool/test_text.py::test_mode_property[a+]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-11-18 10:17:34+00:00
apache-2.0
794
Tinche__aiofiles-154
diff --git a/README.rst b/README.rst index 5ddf859..b7905a0 100644 --- a/README.rst +++ b/README.rst @@ -96,6 +96,11 @@ and delegate to an executor: In case of failure, one of the usual exceptions will be raised. +``aiofiles.stdin``, ``aiofiles.stdout``, ``aiofiles.stderr``, +``aiofiles.stdin_bytes``, ``aiofiles.stdout_bytes``, and +``aiofiles.stderr_bytes`` provide async access to ``sys.stdin``, +``sys.stdout``, ``sys.stderr``, and their corresponding ``.buffer`` properties. + The ``aiofiles.os`` module contains executor-enabled coroutine versions of several useful ``os`` functions that deal with files: @@ -180,6 +185,8 @@ History `#146 <https://github.com/Tinche/aiofiles/pull/146>`_ * Removed ``aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.softspace``. `#151 <https://github.com/Tinche/aiofiles/pull/151>`_ +* Added ``aiofiles.stdin``, ``aiofiles.stdin_bytes``, and other stdio streams. + `#154 <https://github.com/Tinche/aiofiles/pull/154>`_ 22.1.0 (2022-09-04) ``````````````````` diff --git a/src/aiofiles/__init__.py b/src/aiofiles/__init__.py index b0114ee..9e75111 100644 --- a/src/aiofiles/__init__.py +++ b/src/aiofiles/__init__.py @@ -1,5 +1,22 @@ """Utilities for asyncio-friendly file handling.""" -from .threadpool import open +from .threadpool import ( + open, + stdin, + stdout, + stderr, + stdin_bytes, + stdout_bytes, + stderr_bytes, +) from . import tempfile -__all__ = ["open", "tempfile"] +__all__ = [ + "open", + "tempfile", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +] diff --git a/src/aiofiles/base.py b/src/aiofiles/base.py index f64d00d..6201d95 100644 --- a/src/aiofiles/base.py +++ b/src/aiofiles/base.py @@ -1,13 +1,18 @@ """Various base classes.""" from types import coroutine from collections.abc import Coroutine +from asyncio import get_running_loop class AsyncBase: def __init__(self, file, loop, executor): self._file = file - self._loop = loop self._executor = executor + self._ref_loop = loop + + @property + def _loop(self): + return self._ref_loop or get_running_loop() def __aiter__(self): """We are our own iterator.""" @@ -25,6 +30,21 @@ class AsyncBase: raise StopAsyncIteration +class AsyncIndirectBase(AsyncBase): + def __init__(self, name, loop, executor, indirect): + self._indirect = indirect + self._name = name + super().__init__(None, loop, executor) + + @property + def _file(self): + return self._indirect() + + @_file.setter + def _file(self, v): + pass # discard writes + + class _ContextManager(Coroutine): __slots__ = ("_coro", "_obj") diff --git a/src/aiofiles/threadpool/__init__.py b/src/aiofiles/threadpool/__init__.py index 7bb18d7..522b251 100644 --- a/src/aiofiles/threadpool/__init__.py +++ b/src/aiofiles/threadpool/__init__.py @@ -1,5 +1,6 @@ """Handle files using a thread pool executor.""" import asyncio +import sys from types import coroutine from io import ( @@ -8,16 +9,32 @@ from io import ( BufferedReader, BufferedWriter, BufferedRandom, + BufferedIOBase, ) from functools import partial, singledispatch -from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO -from .text import AsyncTextIOWrapper +from .binary import ( + AsyncBufferedIOBase, + AsyncBufferedReader, + AsyncFileIO, + AsyncIndirectBufferedIOBase, + AsyncIndirectBufferedReader, + AsyncIndirectFileIO, +) +from .text import AsyncTextIOWrapper, AsyncTextIndirectIOWrapper from ..base import AiofilesContextManager sync_open = open -__all__ = ("open",) +__all__ = ( + "open", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +) def open( @@ -93,6 +110,7 @@ def _(file, *, loop=None, executor=None): @wrap.register(BufferedWriter) [email protected](BufferedIOBase) def _(file, *, loop=None, executor=None): return AsyncBufferedIOBase(file, loop=loop, executor=executor) @@ -105,4 +123,12 @@ def _(file, *, loop=None, executor=None): @wrap.register(FileIO) def _(file, *, loop=None, executor=None): - return AsyncFileIO(file, loop, executor) + return AsyncFileIO(file, loop=loop, executor=executor) + + +stdin = AsyncTextIndirectIOWrapper('sys.stdin', None, None, indirect=lambda: sys.stdin) +stdout = AsyncTextIndirectIOWrapper('sys.stdout', None, None, indirect=lambda: sys.stdout) +stderr = AsyncTextIndirectIOWrapper('sys.stderr', None, None, indirect=lambda: sys.stderr) +stdin_bytes = AsyncIndirectBufferedIOBase('sys.stdin.buffer', None, None, indirect=lambda: sys.stdin.buffer) +stdout_bytes = AsyncIndirectBufferedIOBase('sys.stdout.buffer', None, None, indirect=lambda: sys.stdout.buffer) +stderr_bytes = AsyncIndirectBufferedIOBase('sys.stderr.buffer', None, None, indirect=lambda: sys.stderr.buffer) diff --git a/src/aiofiles/threadpool/binary.py b/src/aiofiles/threadpool/binary.py index 3568ed0..52d0cb3 100644 --- a/src/aiofiles/threadpool/binary.py +++ b/src/aiofiles/threadpool/binary.py @@ -1,4 +1,4 @@ -from ..base import AsyncBase +from ..base import AsyncBase, AsyncIndirectBase from .utils import ( delegate_to_executor, proxy_method_directly, @@ -26,7 +26,7 @@ from .utils import ( @proxy_method_directly("detach", "fileno", "readable") @proxy_property_directly("closed", "raw", "name", "mode") class AsyncBufferedIOBase(AsyncBase): - """The asyncio executor version of io.BufferedWriter.""" + """The asyncio executor version of io.BufferedWriter and BufferedIOBase.""" @delegate_to_executor("peek") @@ -55,3 +55,54 @@ class AsyncBufferedReader(AsyncBufferedIOBase): @proxy_property_directly("closed", "name", "mode") class AsyncFileIO(AsyncBase): """The asyncio executor version of io.FileIO.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "read1", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly("closed", "raw", "name", "mode") +class AsyncIndirectBufferedIOBase(AsyncIndirectBase): + """The indirect asyncio executor version of io.BufferedWriter and BufferedIOBase.""" + + +@delegate_to_executor("peek") +class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase): + """The indirect asyncio executor version of io.BufferedReader and Random.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("fileno", "readable") +@proxy_property_directly("closed", "name", "mode") +class AsyncIndirectFileIO(AsyncIndirectBase): + """The indirect asyncio executor version of io.FileIO.""" diff --git a/src/aiofiles/threadpool/text.py b/src/aiofiles/threadpool/text.py index 41cdbbf..1323009 100644 --- a/src/aiofiles/threadpool/text.py +++ b/src/aiofiles/threadpool/text.py @@ -1,4 +1,4 @@ -from ..base import AsyncBase +from ..base import AsyncBase, AsyncIndirectBase from .utils import ( delegate_to_executor, proxy_method_directly, @@ -35,3 +35,34 @@ from .utils import ( ) class AsyncTextIOWrapper(AsyncBase): """The asyncio executor version of io.TextIOWrapper.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readable", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "write", + "writable", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly( + "buffer", + "closed", + "encoding", + "errors", + "line_buffering", + "newlines", + "name", + "mode", +) +class AsyncTextIndirectIOWrapper(AsyncIndirectBase): + """The indirect asyncio executor version of io.TextIOWrapper."""
Tinche/aiofiles
6193d83df1d7671e50242da64d74f245fd6d15f9
diff --git a/tests/test_os.py b/tests/test_os.py index 2d920d1..34b4b63 100644 --- a/tests/test_os.py +++ b/tests/test_os.py @@ -75,9 +75,9 @@ async def test_renames(): assert exists(old_filename) is False and exists(new_filename) await aiofiles.os.renames(new_filename, old_filename) assert ( - exists(old_filename) and - exists(new_filename) is False and - exists(dirname(new_filename)) is False + exists(old_filename) + and exists(new_filename) is False + and exists(dirname(new_filename)) is False ) @@ -323,6 +323,7 @@ async def test_listdir_dir_with_only_one_file(): await aiofiles.os.remove(some_file) await aiofiles.os.rmdir(some_dir) + @pytest.mark.asyncio async def test_listdir_dir_with_only_one_dir(): """Test the listdir call when the dir has one dir.""" @@ -335,6 +336,7 @@ async def test_listdir_dir_with_only_one_dir(): await aiofiles.os.rmdir(other_dir) await aiofiles.os.rmdir(some_dir) + @pytest.mark.asyncio async def test_listdir_dir_with_multiple_files(): """Test the listdir call when the dir has multiple files.""" @@ -353,6 +355,7 @@ async def test_listdir_dir_with_multiple_files(): await aiofiles.os.remove(other_file) await aiofiles.os.rmdir(some_dir) + @pytest.mark.asyncio async def test_listdir_dir_with_a_file_and_a_dir(): """Test the listdir call when the dir has files and other dirs.""" @@ -406,6 +409,7 @@ async def test_scandir_dir_with_only_one_file(): await aiofiles.os.remove(some_file) await aiofiles.os.rmdir(some_dir) + @pytest.mark.asyncio async def test_scandir_dir_with_only_one_dir(): """Test the scandir call when the dir has one dir.""" diff --git a/tests/test_stdio.py b/tests/test_stdio.py new file mode 100644 index 0000000..61442af --- /dev/null +++ b/tests/test_stdio.py @@ -0,0 +1,25 @@ +import sys +import pytest +from aiofiles import stdin, stdout, stderr, stdin_bytes, stdout_bytes, stderr_bytes + + [email protected] +async def test_stdio(capsys): + await stdout.write("hello") + await stderr.write("world") + out, err = capsys.readouterr() + assert out == "hello" + assert err == "world" + with pytest.raises(OSError): + await stdin.read() + + [email protected] +async def test_stdio_bytes(capsysbinary): + await stdout_bytes.write(b"hello") + await stderr_bytes.write(b"world") + out, err = capsysbinary.readouterr() + assert out == b"hello" + assert err == b"world" + with pytest.raises(OSError): + await stdin_bytes.read() diff --git a/tests/test_tempfile.py b/tests/test_tempfile.py index 9bf743e..3ebb149 100644 --- a/tests/test_tempfile.py +++ b/tests/test_tempfile.py @@ -69,9 +69,9 @@ async def test_spooled_temporary_file(mode): @pytest.mark.skipif( sys.version_info < (3, 7), reason=( - "text-mode SpooledTemporaryFile is implemented with StringIO in py3.6" - "it doesn't support `newlines`" - ) + "text-mode SpooledTemporaryFile is implemented with StringIO in py3.6" + "it doesn't support `newlines`" + ), ) @pytest.mark.parametrize( "test_string, newlines", [("LF\n", "\n"), ("CRLF\r\n", "\r\n")]
What is the purpose of binding each file to a particular loop? It's somewhat inconvenient that `AsyncBase._loop` exists - it makes it hard to implement a global stdout object via a module-level `stdout = aiofiles.threadpool.wrap(sys.stdout)`. What is the purpose of this attribute? If it is purely for performance reasons, would you accept a PR that changed all references to `self._loop` to `self._loop or asyncio.get_running_loop()`?
0.0
6193d83df1d7671e50242da64d74f245fd6d15f9
[ "tests/test_os.py::test_stat", "tests/test_os.py::test_remove", "tests/test_os.py::test_unlink", "tests/test_os.py::test_mkdir_and_rmdir", "tests/test_os.py::test_rename", "tests/test_os.py::test_renames", "tests/test_os.py::test_replace", "tests/test_os.py::test_sendfile_file", "tests/test_os.py::test_sendfile_socket", "tests/test_os.py::test_exists", "tests/test_os.py::test_isfile", "tests/test_os.py::test_isdir", "tests/test_os.py::test_islink", "tests/test_os.py::test_getsize", "tests/test_os.py::test_samefile", "tests/test_os.py::test_sameopenfile", "tests/test_os.py::test_getmtime", "tests/test_os.py::test_getatime", "tests/test_os.py::test_getctime", "tests/test_os.py::test_link", "tests/test_os.py::test_symlink", "tests/test_os.py::test_readlink", "tests/test_os.py::test_listdir_empty_dir", "tests/test_os.py::test_listdir_dir_with_only_one_file", "tests/test_os.py::test_listdir_dir_with_only_one_dir", "tests/test_os.py::test_listdir_dir_with_multiple_files", "tests/test_os.py::test_listdir_dir_with_a_file_and_a_dir", "tests/test_os.py::test_listdir_non_existing_dir", "tests/test_os.py::test_scantdir_empty_dir", "tests/test_os.py::test_scandir_dir_with_only_one_file", "tests/test_os.py::test_scandir_dir_with_only_one_dir", "tests/test_os.py::test_scandir_non_existing_dir", "tests/test_stdio.py::test_stdio", "tests/test_stdio.py::test_stdio_bytes", "tests/test_tempfile.py::test_temporary_file[r+]", "tests/test_tempfile.py::test_temporary_file[w+]", "tests/test_tempfile.py::test_temporary_file[rb+]", "tests/test_tempfile.py::test_temporary_file[wb+]", "tests/test_tempfile.py::test_named_temporary_file[r+]", "tests/test_tempfile.py::test_named_temporary_file[w+]", "tests/test_tempfile.py::test_named_temporary_file[rb+]", "tests/test_tempfile.py::test_named_temporary_file[wb+]", "tests/test_tempfile.py::test_spooled_temporary_file[r+]", "tests/test_tempfile.py::test_spooled_temporary_file[w+]", "tests/test_tempfile.py::test_spooled_temporary_file[rb+]", "tests/test_tempfile.py::test_spooled_temporary_file[wb+]", "tests/test_tempfile.py::test_spooled_temporary_file_newlines[LF\\n-\\n]", "tests/test_tempfile.py::test_spooled_temporary_file_newlines[CRLF\\r\\n-\\r\\n]", "tests/test_tempfile.py::test_temporary_directory[a-b]", "tests/test_tempfile.py::test_temporary_directory[c-d]", "tests/test_tempfile.py::test_temporary_directory[e-f]" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-08 17:34:17+00:00
apache-2.0
795
Tinche__cattrs-117
diff --git a/HISTORY.rst b/HISTORY.rst index 6f59b9b..9883525 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -7,6 +7,8 @@ History * ``converter.unstructure`` now supports an optional parameter, `unstructure_as`, which can be used to unstructure something as a different type. Useful for unions. * Improve support for union un/structuring hooks. Flesh out docs for advanced union handling. (`#115 <https://github.com/Tinche/cattrs/pull/115>`_) +* Fix `GenConverter` behavior with inheritance hierarchies of `attrs` classes. + (`#117 <https://github.com/Tinche/cattrs/pull/117>`_) (`#116 <https://github.com/Tinche/cattrs/issues/116>`_) 1.1.2 (2020-11-29) ------------------ diff --git a/src/cattr/converters.py b/src/cattr/converters.py index 85cd1d7..d393639 100644 --- a/src/cattr/converters.py +++ b/src/cattr/converters.py @@ -508,7 +508,9 @@ class GenConverter(Converter): omit_if_default=self.omit_if_default, **attrib_overrides ) - self.register_unstructure_hook(obj.__class__, h) + self._unstructure_func.register_cls_list( + [(obj.__class__, h)], no_singledispatch=True + ) return h(obj) def structure_attrs_fromdict( @@ -524,5 +526,8 @@ class GenConverter(Converter): if a.type in self.type_overrides } h = make_dict_structure_fn(cl, self, **attrib_overrides) - self.register_structure_hook(cl, h) + self._structure_func.register_cls_list( + [(cl, h)], no_singledispatch=True + ) + # only direct dispatch so that subclasses get separately generated return h(obj, cl) diff --git a/src/cattr/multistrategy_dispatch.py b/src/cattr/multistrategy_dispatch.py index c326663..d211f3b 100644 --- a/src/cattr/multistrategy_dispatch.py +++ b/src/cattr/multistrategy_dispatch.py @@ -15,16 +15,24 @@ class _DispatchNotFound(object): class MultiStrategyDispatch(object): """ MultiStrategyDispatch uses a - combination of FunctionDispatch and singledispatch. + combination of exact-match dispatch, singledispatch, and FunctionDispatch. - singledispatch is attempted first. If nothing is - registered for singledispatch, or an exception occurs, + Exact match dispatch is attempted first, based on a direct + lookup of the exact class type, if the hook was registered to avoid singledispatch. + singledispatch is attempted next - it will handle subclasses of base classes using MRO + If nothing is registered for singledispatch, or an exception occurs, the FunctionDispatch instance is then used. """ - __slots__ = ("_function_dispatch", "_single_dispatch", "dispatch") + __slots__ = ( + "_direct_dispatch", + "_function_dispatch", + "_single_dispatch", + "dispatch", + ) def __init__(self, fallback_func): + self._direct_dispatch = {} self._function_dispatch = FunctionDispatch() self._function_dispatch.register(lambda _: True, fallback_func) self._single_dispatch = singledispatch(_DispatchNotFound) @@ -32,6 +40,9 @@ class MultiStrategyDispatch(object): def _dispatch(self, cl): try: + direct_dispatch = self._direct_dispatch.get(cl) + if direct_dispatch is not None: + return direct_dispatch dispatch = self._single_dispatch.dispatch(cl) if dispatch is not _DispatchNotFound: return dispatch @@ -39,10 +50,15 @@ class MultiStrategyDispatch(object): pass return self._function_dispatch.dispatch(cl) - def register_cls_list(self, cls_and_handler): - """ register a class to singledispatch """ + def register_cls_list( + self, cls_and_handler, no_singledispatch: bool = False + ): + """ register a class to direct or singledispatch """ for cls, handler in cls_and_handler: - self._single_dispatch.register(cls, handler) + if no_singledispatch: + self._direct_dispatch[cls] = handler + else: + self._single_dispatch.register(cls, handler) self.dispatch.cache_clear() def register_func_list(self, func_and_handler):
Tinche/cattrs
61c944584b3a5472b5733beac79134c77580274d
diff --git a/tests/test_genconverter_inheritance.py b/tests/test_genconverter_inheritance.py new file mode 100644 index 0000000..b38d369 --- /dev/null +++ b/tests/test_genconverter_inheritance.py @@ -0,0 +1,20 @@ +from cattr.converters import GenConverter +import attr + + +def test_inheritance(): + @attr.s(auto_attribs=True) + class A: + i: int + + @attr.s(auto_attribs=True) + class B(A): + j: int + + converter = GenConverter() + + # succeeds + assert A(1) == converter.structure(dict(i=1), A) + + # fails + assert B(1, 2) == converter.structure(dict(i=1, j=2), B)
GenConverter doesn't support inheritance * cattrs version: 1.1.1 * Python version: 3.7 * Operating System: Mac ### Description The old converter supports attrs classes which inherit from each other because it doesn't use MRO-based singledispatch per type to dispatch its attrs classes - therefore, when a subclass B is encountered, it is dynamically structured based on the actual type and the attributes available in the dict. However, the new GenConverter creates and registers a single-dispatched function as soon as it sees a new type. And functools.singledispatch seems to do some MRO stuff and identifies any subclass as "being" its parent class, therefore skipping the code generation and registration process that cattrs would otherwise do for any new subclass. ### What I Did ``` from cattr.converters import GenConverter import attr @attr.s(auto_attribs=True) class A: i: int @attr.s(auto_attribs=True) class B(A): j: int def test_inheritance(): converter = GenConverter() # succeeds assert A(1) == converter.structure(dict(i=1), A) # fails assert B(1, 2) == converter.structure(dict(i=1, j=2), B) ``` the failure is ``` E AssertionError: assert B(i=1, j=2) == A(i=1) E + where B(i=1, j=2) = B(1, 2) ``` essentially, cattrs/singledispatch chooses A and then runs the A structuring code, rather than generating a new method. How to fix this? I know singledispatch should be fairly well optimized, so it would be un-fun to drop it entirely. But since this is a breaking change from the old converter to the new converter, I feel like we should try to do something. I wonder if it might be just as well to use a strict type map looking in the multistrategy dispatch before we hit the singledispatch function. Essentially, if there's an exact match, use that before even trying singledispatch. If there isn't, *and* the type is an attrs class, _skip_ singledispatch so that the class is "caught" by the fallback function dispatch. If you're willing to accept this approach, I found a patch that works nicely. I'll probably put up a PR in the next couple of days.
0.0
61c944584b3a5472b5733beac79134c77580274d
[ "tests/test_genconverter_inheritance.py::test_inheritance" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-24 04:09:07+00:00
mit
796
TomasTomecek__ansible-bender-73
diff --git a/README.md b/README.md index 498627f..3f496a7 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ be present on your host system: ### Requirements (base image) -* python interpretter — ansible-bender will try to find it (alternatively you +* python interpreter — ansible-bender will try to find it (alternatively you can specify it via `--python-interpreter`). * It can be python 2 or python 3 — on host, you have to have python 3 but inside the base image, it doesn't matter — Ansible is able to utilize @@ -105,15 +105,13 @@ be present on your host system: ### Requirements (Ansible playbook) -You need to set `hosts` to `all`: -```yaml -$ cat playbook.yaml ---- -- name: Playbook to build my fancy image - hosts: all -``` +None. + +Bender copies the playbook you provide so that it can be processed. `hosts` +variable is being overwritten in the copy and changed to the name of the +working container — where the build happens. So it doesn't matter what's the +content of the hosts variable. -Setting `hosts` to localhost will result running the playbook against localhost and not a container. ## Configuration diff --git a/ansible_bender/core.py b/ansible_bender/core.py index f136827..cec269e 100644 --- a/ansible_bender/core.py +++ b/ansible_bender/core.py @@ -45,7 +45,7 @@ from ansible_bender import callback_plugins from ansible_bender.conf import ImageMetadata, Build from ansible_bender.constants import TIMESTAMP_FORMAT from ansible_bender.exceptions import AbBuildUnsuccesful -from ansible_bender.utils import run_cmd, ap_command_exists, random_str +from ansible_bender.utils import run_cmd, ap_command_exists, random_str, graceful_get logger = logging.getLogger(__name__) A_CFG_TEMPLATE = """\ @@ -187,11 +187,33 @@ class AnsibleRunner: a_cfg_path = os.path.join(tmp, "ansible.cfg") with open(a_cfg_path, "w") as fd: self._create_ansible_cfg(fd) + + tmp_pb_path = os.path.join(tmp, "p.yaml") + with open(self.pb, "r") as fd_r: + pb_dict = yaml.safe_load(fd_r) + for idx, doc in enumerate(pb_dict): + host = doc["hosts"] + logger.debug("play[%s], host = %s", idx, host) + doc["hosts"] = self.builder.ansible_host + with open(tmp_pb_path, "w") as fd: + yaml.safe_dump(pb_dict, fd) + playbook_base = os.path.basename(self.pb).split(".", 1)[0] + timestamp = datetime.datetime.now().strftime(TIMESTAMP_FORMAT) + symlink_name = f".{playbook_base}-{timestamp}-{random_str()}.yaml" + playbook_dir = os.path.dirname(self.pb) + symlink_path = os.path.join(playbook_dir, symlink_name) + os.symlink(tmp_pb_path, symlink_path) + extra_args = None - if self.build_i.ansible_extra_args: - extra_args = shlex.split(self.build_i.ansible_extra_args) - return run_playbook(self.pb, inv_path, a_cfg_path, self.builder.ansible_connection, - debug=self.debug, environment=environment, ansible_args=extra_args) + try: + if self.build_i.ansible_extra_args: + extra_args = shlex.split(self.build_i.ansible_extra_args) + return run_playbook( + symlink_path, inv_path, a_cfg_path, self.builder.ansible_connection, + debug=self.debug, environment=environment, ansible_args=extra_args + ) + finally: + os.unlink(symlink_path) finally: shutil.rmtree(tmp) @@ -213,15 +235,21 @@ class PbVarsParser: :return: dict """ with open(self.playbook_path) as fd: - d = yaml.safe_load(fd) + plays = yaml.safe_load(fd) + + for play in plays[1:]: + bender_vars = graceful_get(play, "vars", "ansible_bender") + if bender_vars: + logger.warning("Variables are loaded only from the first play.") try: - # TODO: process all the plays - d = d[0] + # we care only about the first play, we don't want to merge dicts + d = plays[0] except IndexError: raise RuntimeError("Invalid playbook, can't access the first document.") - if "vars" not in d: + bender_vars = graceful_get(d, "vars", "ansible_bender") + if not bender_vars: return {} tmp = tempfile.mkdtemp(prefix="ab") diff --git a/docs/configuration.md b/docs/configuration.md index bd14d32..c3b7fde 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -17,6 +17,9 @@ Configuration is done using a top-level Ansible variable `ansible_bender`. All the values are nested under it. The values are processed before a build starts. The changes to values are not reflected during a playbook run. +If your playbook has multiple plays, the `ansible_bender` variable is processed +only from the first play. All the plays will end up in a single container image. + #### Top-level keys
TomasTomecek/ansible-bender
3e7b25600646333511ac7e8a1e6147d1460387c0
diff --git a/tests/data/multiplay.yaml b/tests/data/multiplay.yaml new file mode 100644 index 0000000..4297bb5 --- /dev/null +++ b/tests/data/multiplay.yaml @@ -0,0 +1,17 @@ +--- +- hosts: all + vars: + ansible_bender: {} + tasks: + - name: Run a sample command + command: 'ls -lha /' +- hosts: localhost + vars: + ansible_bender: + target_image: + name: nope + tasks: + - name: create a file + copy: + content: "killer" + dest: /queen diff --git a/tests/functional/test_buildah.py b/tests/functional/test_buildah.py index 5b62642..517c7b7 100644 --- a/tests/functional/test_buildah.py +++ b/tests/functional/test_buildah.py @@ -135,13 +135,15 @@ def test_build_basic_image_with_all_params(tmpdir, target_image): def test_build_failure(tmpdir): - target_image = "registry.example.com/ab-test-" + random_word(12) + ":oldest" + target_image_name = "registry.example.com/ab-test-" + random_word(12) + target_image_tag = "oldest" + target_image = f"{target_image_name}:{target_image_tag}" target_failed_image = target_image + "-failed" cmd = ["build", bad_playbook_path, base_image, target_image] with pytest.raises(subprocess.CalledProcessError): ab(cmd, str(tmpdir)) - out = ab(["get-logs"], str(tmpdir), return_output=True) - assert "PLAY [all]" in out + out = ab(["get-logs"], str(tmpdir), return_output=True).lstrip() + assert out.startswith("PLAY [registry") p_inspect_data = json.loads(subprocess.check_output(["podman", "inspect", "-t", "image", target_failed_image]))[0] image_id = p_inspect_data["Id"] diff --git a/tests/functional/test_cli.py b/tests/functional/test_cli.py index 331cefe..58d1a09 100644 --- a/tests/functional/test_cli.py +++ b/tests/functional/test_cli.py @@ -61,8 +61,8 @@ metadata: def test_get_logs(target_image, tmpdir): cmd = ["build", basic_playbook_path, base_image, target_image] ab(cmd, str(tmpdir)) - out = ab(["get-logs"], str(tmpdir), return_output=True) - assert "PLAY [all]" in out + out = ab(["get-logs"], str(tmpdir), return_output=True).lstrip() + assert out.startswith("PLAY [registry") assert "TASK [Gathering Facts]" in out assert "failed=0" in out assert "TASK [print local env vars]" in out diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py index 6705c5c..8247527 100644 --- a/tests/integration/test_api.py +++ b/tests/integration/test_api.py @@ -5,13 +5,14 @@ import os import shutil import yaml +from ansible_bender.builders.buildah_builder import podman_run_cmd from flexmock import flexmock from ansible_bender.api import Application from ansible_bender.conf import Build from ansible_bender.utils import random_str, run_cmd from tests.spellbook import (dont_cache_playbook_path, change_layering_playbook, data_dir, - dont_cache_playbook_path_pre, non_ex_pb) + dont_cache_playbook_path_pre, non_ex_pb, multiplay_path) from ..spellbook import small_basic_playbook_path @@ -22,8 +23,8 @@ def test_build_db_metadata(target_image, application, build): assert build.build_finished_time is not None assert build.build_start_time is not None assert build.log_lines is not None - logs = "\n".join(build.log_lines) - assert "PLAY [all]" in logs + logs = "\n".join([l for l in build.log_lines if l]) + assert logs.startswith("PLAY [registry") assert "TASK [Gathering Facts]" in logs assert "failed=0" in logs @@ -229,3 +230,16 @@ def test_caching_non_ex_image_w_mocking(tmpdir, build): assert not build.layers[-1].cached finally: application.clean() + + +def test_multiplay(build, application): + im = "multiplay" + build.playbook_path = multiplay_path + build.target_image = im + application.build(build) + try: + build = application.db.get_build(build.build_id) + podman_run_cmd(im, ["ls", "/queen"]) # the file has to be in there + assert len(build.layers) == 3 + finally: + run_cmd(["buildah", "rmi", im], ignore_status=True, print_output=True) diff --git a/tests/integration/test_conf.py b/tests/integration/test_conf.py index 07a6f51..8519436 100644 --- a/tests/integration/test_conf.py +++ b/tests/integration/test_conf.py @@ -2,11 +2,12 @@ import os import jsonschema import pytest +from ansible_bender.utils import set_logging from ansible_bender.conf import ImageMetadata, Build from ansible_bender.core import PbVarsParser -from tests.spellbook import b_p_w_vars_path, basic_playbook_path, full_conf_pb_path +from tests.spellbook import b_p_w_vars_path, basic_playbook_path, full_conf_pb_path, multiplay_path def test_expand_pb_vars(): @@ -78,3 +79,13 @@ def test_validation_err_ux(): assert "is not of type" in s assert "Failed validating 'type' in schema" in s + + +def test_multiplay(caplog): + set_logging() + p = PbVarsParser(multiplay_path) + b, m = p.get_build_and_metadata() + + assert b.target_image != "nope" + assert "Variables are loaded only from the first play." == caplog.records[0].msg + assert "no bender data found in the playbook" == caplog.records[1].msg diff --git a/tests/spellbook.py b/tests/spellbook.py index 347a5a0..723f4fe 100644 --- a/tests/spellbook.py +++ b/tests/spellbook.py @@ -18,6 +18,7 @@ project_dir = os.path.dirname(tests_dir) data_dir = os.path.abspath(os.path.join(tests_dir, "data")) buildah_inspect_data_path = os.path.join(data_dir, "buildah_inspect.json") basic_playbook_path = os.path.join(data_dir, "basic_playbook.yaml") +multiplay_path = os.path.join(data_dir, "multiplay.yaml") non_ex_pb = os.path.join(data_dir, "non_ex_pb.yaml") b_p_w_vars_path = os.path.join(data_dir, "b_p_w_vars.yaml") p_w_vars_files_path = os.path.join(data_dir, "p_w_vars_files.yaml")
playbook: `hosts: all` vs `hosts: localhost` * [x] try running bender with `hosts: localhost` * [x] document the outcome * [x] write a test
0.0
3e7b25600646333511ac7e8a1e6147d1460387c0
[ "tests/integration/test_conf.py::test_multiplay" ]
[ "tests/functional/test_buildah.py::test_buildah_err_output", "tests/integration/test_conf.py::test_b_m_empty", "tests/integration/test_conf.py::test_validation_err_ux" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-02-25 22:44:55+00:00
mit
797
TomasTomecek__ansible-bender-82
diff --git a/ansible_bender/core.py b/ansible_bender/core.py index cec269e..a01f098 100644 --- a/ansible_bender/core.py +++ b/ansible_bender/core.py @@ -45,7 +45,8 @@ from ansible_bender import callback_plugins from ansible_bender.conf import ImageMetadata, Build from ansible_bender.constants import TIMESTAMP_FORMAT from ansible_bender.exceptions import AbBuildUnsuccesful -from ansible_bender.utils import run_cmd, ap_command_exists, random_str, graceful_get +from ansible_bender.utils import run_cmd, ap_command_exists, random_str, graceful_get, \ + is_ansibles_python_2 logger = logging.getLogger(__name__) A_CFG_TEMPLATE = """\ @@ -78,6 +79,12 @@ def run_playbook(playbook_path, inventory_path, a_cfg_path, connection, extra_va :return: output """ ap = ap_command_exists() + if is_ansibles_python_2(ap): + raise RuntimeError( + "ansible-bender is written in python 3 and does not work in python 2,\n" + f"it seems that {ap} is using python 2 - ansible-bender will not" + "work in such environment\n" + ) cmd_args = [ ap, "-c", connection, diff --git a/ansible_bender/utils.py b/ansible_bender/utils.py index 2f23892..ac0fac2 100644 --- a/ansible_bender/utils.py +++ b/ansible_bender/utils.py @@ -4,6 +4,7 @@ Utility functions. This module can't depend on anything within ab. import logging import os import random +import re import shutil import string import subprocess @@ -126,14 +127,14 @@ def env_get_or_fail_with(env_name, err_msg): raise RuntimeError(err_msg) -def one_of_commands_exists(commands, exc_msg): +def one_of_commands_exists(commands, exc_msg) -> str: """ Verify that the provided command exists. Raise CommandDoesNotExistException in case of an error or if the command does not exist. :param commands: str, command to check (python 3 only) :param exc_msg: str, message of exception when command does not exist - :return: bool, True if everything's all right (otherwise exception is thrown) + :return: str, the command which exists """ found = False for command in commands: @@ -233,3 +234,29 @@ def random_str(size=10): :return: the string """ return ''.join(random.choice(string.ascii_lowercase) for _ in range(size)) + + +def is_ansibles_python_2(ap_exe: str) -> bool: + """ + Discover whether ansible-playbook is using python 2. + + :param ap_exe: path to the python executable + + :return: True if it's 2 + """ + out = run_cmd([ap_exe, "--version"], log_stderr=True, return_output=True) + + # python version = 3.7.2 + reg = r"python version = (\d)" + + reg_grp = re.findall(reg, out) + try: + py_version = reg_grp[0] + except IndexError: + logger.warning("could not figure out which python is %s using", ap_exe) + return False # we don't know, fingers crossed + if py_version == "2": + logger.info("%s is using python 2", ap_exe) + return True + logger.debug("it seems that %s is not using python 2", ap_exe) + return False
TomasTomecek/ansible-bender
1f005b0e6b5b442f522247b6159c5bed802f6822
diff --git a/tests/integration/test_core.py b/tests/integration/test_core.py new file mode 100644 index 0000000..c462889 --- /dev/null +++ b/tests/integration/test_core.py @@ -0,0 +1,17 @@ +""" +Tests for ansible invocation +""" +import pytest +from flexmock import flexmock + +from ansible_bender import utils +from ansible_bender.core import run_playbook +from tests.spellbook import C7_AP_VER_OUT + + +def test_ansibles_python(): + flexmock(utils, run_cmd=lambda *args, **kwargs: C7_AP_VER_OUT), + with pytest.raises(RuntimeError) as ex: + run_playbook(None, None, None, None) + assert str(ex.value).startswith( + "ansible-bender is written in python 3 and does not work in python 2,\n") diff --git a/tests/spellbook.py b/tests/spellbook.py index 723f4fe..1635998 100644 --- a/tests/spellbook.py +++ b/tests/spellbook.py @@ -31,6 +31,15 @@ change_layering_playbook = os.path.join(data_dir, "change_layering.yaml") bad_playbook_path = os.path.join(data_dir, "bad_playbook.yaml") base_image = "docker.io/library/python:3-alpine" +C7_AP_VER_OUT = """\ +ansible-playbook 2.4.2.0 + config file = /etc/ansible/ansible.cfg + configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] + ansible python module location = /usr/lib/python2.7/site-packages/ansible + executable location = /usr/bin/ansible-playbook + python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] +""" + def random_word(length): # https://stackoverflow.com/a/2030081/909579 diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 0eb0883..5960da9 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -1,9 +1,12 @@ import re import pytest +from flexmock import flexmock +from ansible_bender import utils from ansible_bender.db import generate_working_cont_name -from ansible_bender.utils import run_cmd, graceful_get +from ansible_bender.utils import run_cmd, graceful_get, ap_command_exists, is_ansibles_python_2 +from tests.spellbook import C7_AP_VER_OUT def test_run_cmd(): @@ -39,3 +42,20 @@ def test_graceful_g_w_default(): assert graceful_get(inp, 1, default="asd") == {2: 3} assert graceful_get(inp, 1, 2, default="asd") == 3 assert graceful_get(inp, 1, 2, 4, default="asd") == "asd" + + [email protected]("m,is_py2", ( + (object, False), # no mocking + ( + lambda: flexmock(utils, run_cmd=lambda *args, **kwargs: C7_AP_VER_OUT), + True + ), + ( + lambda: flexmock(utils, run_cmd=lambda *args, **kwargs: "nope"), + False + ), +)) +def test_ansibles_python(m, is_py2): + m() + cmd = ap_command_exists() + assert is_ansibles_python_2(cmd) == is_py2
get python version of local ansible and exit if it's 2 This is a dupe of #76 because the problem with that issue is that ansible is buitl with python 2 and bender's callback plugin can't be imported b/c it's py 3 only code. TODO * [x] detect python version via `ansible-playbook --version` * we can't use the API because bender may be running in a venv * [x] if the py version is < 3, halt and refuse to continue
0.0
1f005b0e6b5b442f522247b6159c5bed802f6822
[ "tests/unit/test_utils.py::test_run_cmd", "tests/unit/test_utils.py::test_gen_work_cont_name[lojza-^lojza-\\\\d{8}-\\\\d{12}-cont$]", "tests/unit/test_utils.py::test_gen_work_cont_name[172.30.1.1:5000/myproject/just-built-ansible-bender:latest-^172-30-1-1-5000-myproject-just-built-ansible-bender-latest-\\\\d{8}-\\\\d{12}-cont$]", "tests/unit/test_utils.py::test_graceful_g[inp0-path0-2]", "tests/unit/test_utils.py::test_graceful_g[inp1-path1-3]", "tests/unit/test_utils.py::test_graceful_g[inp2-path2-3]", "tests/unit/test_utils.py::test_graceful_g[inp3-path3-None]", "tests/unit/test_utils.py::test_graceful_g[None-path4-None]", "tests/unit/test_utils.py::test_graceful_g[inp5-path5-None]", "tests/unit/test_utils.py::test_graceful_g_w_default" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-02 08:20:27+00:00
mit
798
Turbo87__utm-31
diff --git a/utm/conversion.py b/utm/conversion.py old mode 100755 new mode 100644 index d21742a..449f3d1 --- a/utm/conversion.py +++ b/utm/conversion.py @@ -216,13 +216,13 @@ def latlon_to_zone_number(latitude, longitude): return 32 if 72 <= latitude <= 84 and longitude >= 0: - if longitude <= 9: + if longitude < 9: return 31 - elif longitude <= 21: + elif longitude < 21: return 33 - elif longitude <= 33: + elif longitude < 33: return 35 - elif longitude <= 42: + elif longitude < 42: return 37 return int((longitude + 180) / 6) + 1
Turbo87/utm
4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f
diff --git a/test/test_utm.py b/test/test_utm.py index 55686d7..c820cea 100755 --- a/test/test_utm.py +++ b/test/test_utm.py @@ -231,5 +231,22 @@ class Zone32V(unittest.TestCase): self.assert_zone_equal(UTM.from_latlon(64, 12), 33, 'W') +class TestRightBoundaries(unittest.TestCase): + + def assert_zone_equal(self, result, expected_number): + self.assertEqual(result[2], expected_number) + + def test_limits(self): + self.assert_zone_equal(UTM.from_latlon(40, 0), 31) + self.assert_zone_equal(UTM.from_latlon(40, 5.999999), 31) + self.assert_zone_equal(UTM.from_latlon(40, 6), 32) + + self.assert_zone_equal(UTM.from_latlon(72, 0), 31) + self.assert_zone_equal(UTM.from_latlon(72, 5.999999), 31) + self.assert_zone_equal(UTM.from_latlon(72, 6), 31) + self.assert_zone_equal(UTM.from_latlon(72, 8.999999), 31) + self.assert_zone_equal(UTM.from_latlon(72, 9), 33) + + if __name__ == '__main__': unittest.main()
UTM zone exceptions error By definition zones are left-closed, right-open intervals, e.g. zone 31: 0 <= latitude < 6. In function latlon_to_zone_number: ``` if 72 <= latitude <= 84 and longitude >= 0: if longitude <= 9: return 31 elif longitude <= 21: return 33 elif longitude <= 33: return 35 elif longitude <= 42: return 37 ``` For latitudes >=72, this results in: zone 31: 0 <= longitude <= 9 zone 33: 9 < longitude <= 21 zone 35: 21< longitude <= 33 zone 37: 33< longitude <= 42 but for latitudes < 72: zone 37: 36 <= latitude < 42
0.0
4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f
[ "test/test_utm.py::TestRightBoundaries::test_limits" ]
[ "test/test_utm.py::KnownValues::test_from_latlon", "test/test_utm.py::KnownValues::test_to_latlon", "test/test_utm.py::BadInput::test_from_latlon_range_checks", "test/test_utm.py::BadInput::test_to_latlon_range_checks", "test/test_utm.py::Zone32V::test_above", "test/test_utm.py::Zone32V::test_below", "test/test_utm.py::Zone32V::test_inside", "test/test_utm.py::Zone32V::test_left_of", "test/test_utm.py::Zone32V::test_right_of" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-06-26 10:44:15+00:00
mit
799
UC-Davis-molecular-computing__scadnano-python-package-152
diff --git a/examples/circular.py b/examples/circular.py new file mode 100644 index 0000000..2116836 --- /dev/null +++ b/examples/circular.py @@ -0,0 +1,18 @@ +import scadnano as sc +import modifications as mod +import dataclasses + +def create_design(): + helices = [sc.Helix(max_offset=30) for _ in range(2)] + design = sc.Design(helices=helices, grid=sc.square) + + design.strand(0,0).move(10).cross(1).move(-10).as_circular() + design.strand(0,10).move(10).loopout(1, 5).move(-10).as_circular() + design.strand(0,20).move(10).cross(1).move(-10) + + return design + + +if __name__ == '__main__': + design = create_design() + design.write_scadnano_file(directory='output_designs') diff --git a/examples/output_designs/circular.sc b/examples/output_designs/circular.sc new file mode 100644 index 0000000..82f0bd4 --- /dev/null +++ b/examples/output_designs/circular.sc @@ -0,0 +1,34 @@ +{ + "version": "0.13.0", + "grid": "square", + "helices": [ + {"grid_position": [0, 0]}, + {"grid_position": [0, 1]} + ], + "strands": [ + { + "circular": true, + "color": "#f74308", + "domains": [ + {"helix": 0, "forward": true, "start": 0, "end": 10}, + {"helix": 1, "forward": false, "start": 0, "end": 10} + ] + }, + { + "circular": true, + "color": "#57bb00", + "domains": [ + {"helix": 0, "forward": true, "start": 10, "end": 20}, + {"loopout": 5}, + {"helix": 1, "forward": false, "start": 10, "end": 20} + ] + }, + { + "color": "#888888", + "domains": [ + {"helix": 0, "forward": true, "start": 20, "end": 30}, + {"helix": 1, "forward": false, "start": 20, "end": 30} + ] + } + ] +} \ No newline at end of file diff --git a/scadnano/scadnano.py b/scadnano/scadnano.py index a0b0459..185c419 100644 --- a/scadnano/scadnano.py +++ b/scadnano/scadnano.py @@ -44,7 +44,7 @@ so the user must take care not to set them. # commented out for now to support Py3.6, which does not support this feature # from __future__ import annotations -__version__ = "0.13.0" # version line; WARNING: do not remove or change this line or comment +__version__ = "0.13.1" # version line; WARNING: do not remove or change this line or comment import dataclasses from abc import abstractmethod, ABC, ABCMeta @@ -749,6 +749,7 @@ position_origin_key = 'origin' # Strand keys strand_name_key = 'name' +circular_key = 'circular' color_key = 'color' dna_sequence_key = 'sequence' legacy_dna_sequence_keys = ['dna_sequence'] # support legacy names for these ideas @@ -2201,6 +2202,17 @@ class StrandBuilder(Generic[StrandLabel, DomainLabel]): return self + def as_circular(self) -> 'StrandBuilder[StrandLabel, DomainLabel]': + """ + Makes :any:`Strand` being built circular. + + :return: self + """ + if self._strand is None: + raise ValueError('no Strand created yet; make at least one domain first') + self._strand.set_circular() + return self + # remove quotes when Py3.6 support dropped def as_scaffold(self) -> 'StrandBuilder[StrandLabel, DomainLabel]': """ @@ -2477,6 +2489,13 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): and could be either single-stranded or double-stranded, whereas each :any:`Loopout` is single-stranded and has no associated :any:`Helix`.""" + circular: bool = False + """If True, this :any:`Strand` is circular and has no 5' or 3' end. Although there is still a + first and last :any:`Domain`, we interpret there to be a crossover from the 3' end of the last domain + to the 5' end of the first domain, and any circular permutation of :py:data:`Strand.domains` + should result in a functionally equivalent :any:`Strand`. It is illegal to have a + :any:`Modification5Prime` or :any:`Modification3Prime` on a circular :any:`Strand`.""" + dna_sequence: Optional[str] = None """Do not assign directly to this field. Always use :any:`Design.assign_dna` (for complementarity checking) or :any:`Strand.set_dna_sequence` @@ -2509,10 +2528,16 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): :any:`Design` is a scaffold, then the design is considered a DNA origami design.""" modification_5p: Optional[Modification5Prime] = None - """5' modification; None if there is no 5' modification.""" + """ + 5' modification; None if there is no 5' modification. + Illegal to have if :py:data:`Strand.circular` is True. + """ modification_3p: Optional[Modification3Prime] = None - """3' modification; None if there is no 5' modification.""" + """ + 3' modification; None if there is no 3' modification. + Illegal to have if :py:data:`Strand.circular` is True. + """ modifications_int: Dict[int, ModificationInternal] = field(default_factory=dict) """:any:`Modification`'s to the DNA sequence (e.g., biotin, Cy3/Cy5 fluorphores). Maps offset to @@ -2574,6 +2599,8 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): dct: Dict[str, Any] = OrderedDict() if self.name is not None: dct[strand_name_key] = self.name + if self.circular: + dct[circular_key] = self.circular if self.color is not None: dct[color_key] = self.color.to_json_serializable(suppress_indent) if self.dna_sequence is not None: @@ -2617,6 +2644,7 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): raise IllegalDesignError('Loopout at end of Strand not supported') is_scaffold = json_map.get(is_scaffold_key, False) + circular = json_map.get(circular_key, False) dna_sequence = optional_field(None, json_map, dna_sequence_key, *legacy_dna_sequence_keys) @@ -2638,6 +2666,7 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): return Strand( domains=domains, dna_sequence=dna_sequence, + circular=circular, color=color, idt=idt, is_scaffold=is_scaffold, @@ -2699,6 +2728,28 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): """Sets color of this :any:`Strand`.""" self.color = color + def set_circular(self, circular: bool = True) -> None: + """ + Sets this to be a circular :any:`Strand` (or non-circular if optional parameter is False. + + :param circular: + whether to make this :any:`Strand` circular (True) or linear (False) + :raises StrandError: + if this :any:`Strand` has a 5' or 3' modification + """ + if circular and self.modification_5p is not None: + raise StrandError(self, "cannot have a 5' modification on a circular strand") + if circular and self.modification_3p is not None: + raise StrandError(self, "cannot have a 3' modification on a circular strand") + self.circular = circular + + def set_linear(self) -> None: + """ + Makes this a linear (non-circular) :any:`Strand`. Equivalent to calling + `self.set_circular(False)`. + """ + self.set_circular(False) + def set_default_idt(self, use_default_idt: bool = True, skip_scaffold: bool = True, unique_names: bool = False) -> None: """ @@ -2744,11 +2795,15 @@ class Strand(_JSONSerializable, Generic[StrandLabel, DomainLabel]): self.idt = None def set_modification_5p(self, mod: Modification5Prime = None) -> None: - """Sets 5' modification to be `mod`.""" + """Sets 5' modification to be `mod`. `mod` cannot be non-None if :any:`Strand.circular` is True.""" + if self.circular and mod is not None: + raise StrandError(self, "cannot have a 5' modification on a circular strand") self.modification_5p = mod def set_modification_3p(self, mod: Modification3Prime = None) -> None: - """Sets 3' modification to be `mod`.""" + """Sets 3' modification to be `mod`. `mod` cannot be non-None if :any:`Strand.circular` is True.""" + if self.circular and mod is not None: + raise StrandError(self, "cannot have a 3' modification on a circular strand") self.modification_3p = mod def remove_modification_5p(self) -> None:
UC-Davis-molecular-computing/scadnano-python-package
9d1ac962405a73bb314fcb9d3ee161d04a0c0fce
diff --git a/tests/scadnano_tests.py b/tests/scadnano_tests.py index fc584bd..bf58fc1 100644 --- a/tests/scadnano_tests.py +++ b/tests/scadnano_tests.py @@ -3601,6 +3601,46 @@ def set_colors_black(*strands) -> None: strand.set_color(sc.Color(r=0, g=0, b=0)) +class TestCircularStrands(unittest.TestCase): + + def setUp(self) -> None: + helices = [sc.Helix(max_offset=10) for _ in range(2)] + self.design = sc.Design(helices=helices, strands=[]) + self.design.strand(0, 0).move(10).cross(1).move(-10) + self.strand = self.design.strands[0] + r''' + 0 [--------\ + | + 1 <--------/ + ''' + + def test_can_add_internal_mod_to_circular_strand(self) -> None: + self.strand.set_circular() + self.assertEqual(True, self.strand.circular) + self.strand.set_modification_internal(2, mod.biotin_int) + self.assertEqual(1, len(self.strand.modifications_int)) + + def test_cannot_make_strand_circular_if_5p_mod(self) -> None: + self.strand.set_modification_5p(mod.biotin_5p) + with self.assertRaises(sc.StrandError): + self.strand.set_circular(True) + + def test_cannot_make_strand_circular_if_3p_mod(self) -> None: + self.strand.set_modification_3p(mod.biotin_3p) + with self.assertRaises(sc.StrandError): + self.strand.set_circular(True) + + def test_add_5p_mod_to_circular_strand(self) -> None: + self.strand.set_circular(True) + with self.assertRaises(sc.StrandError): + self.strand.set_modification_5p(mod.biotin_5p) + + def test_add_3p_mod_to_circular_strand(self) -> None: + self.strand.set_circular(True) + with self.assertRaises(sc.StrandError): + self.strand.set_modification_3p(mod.biotin_3p) + + class TestAddStrand(unittest.TestCase): def test_add_strand__with_loopout(self) -> None:
circular Strands Add a Boolean field `Strand.circular` and draw a crossover from last substrand to first. Any equivalent cyclic permutation of the substrands should display in the same way. Even if one doesn't wish the final design to have circular strands, this will help to avoid the problem that sometimes an intermediate design temporarily creates a circular `Strand`, even though subsequent edits make it linear again. Currently such designs are simply not allowed. See https://github.com/UC-Davis-molecular-computing/scadnano/issues/5.
0.0
9d1ac962405a73bb314fcb9d3ee161d04a0c0fce
[ "tests/scadnano_tests.py::TestCircularStrands::test_add_3p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrands::test_add_5p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrands::test_can_add_internal_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrands::test_cannot_make_strand_circular_if_3p_mod", "tests/scadnano_tests.py::TestCircularStrands::test_cannot_make_strand_circular_if_5p_mod" ]
[ "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5__reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_then_update_to_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_decrease_increase_reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_increase_decrease_forward", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_update_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__h0_off0_to_off10_cross_h1_to_off5_loopout_length3_h2_to_off15", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels_to_json", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_other_order", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_no_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_forward_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_reverse_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateHelix::test_helix_constructor_no_max_offset_with_major_ticks", "tests/scadnano_tests.py::TestM13::test_p7249", "tests/scadnano_tests.py::TestM13::test_p7560", "tests/scadnano_tests.py::TestM13::test_p8064", "tests/scadnano_tests.py::TestModifications::test_Cy3", "tests/scadnano_tests.py::TestModifications::test_biotin", "tests/scadnano_tests.py::TestModifications::test_mod_illegal_exceptions_raised", "tests/scadnano_tests.py::TestModifications::test_to_json_serializable", "tests/scadnano_tests.py::TestImportCadnanoV2::test_32_helix_rectangle", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Nature09_monolith", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Science09_prot120_98_v3", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order", "tests/scadnano_tests.py::TestImportCadnanoV2::test_huge_hex", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_purifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_scales", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_sequences", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_same_sequence", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportCadnanoV2::test_16_helix_origami_rectangle_no_twist", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple_2", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_bundle_honeycomb", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_origami_rectangle", "tests/scadnano_tests.py::TestExportCadnanoV2::test_bad_cases", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group_not_same_grid", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__from_and_to_file_contents", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others_mixed_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices_mixed_with_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__three_strands", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__one_strand", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__three_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains_two_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_deletions", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_insertions", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_full_crossover__small_design_H0_forward", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_full_crossover__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_full_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_full_crossover__small_design_illegal_only_one_helix_has_domain", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_half_crossover__small_design_H0_reverse_0", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_half_crossover__small_design_H0_reverse_15", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_half_crossover__small_design_H0_reverse_8", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_half_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__6_helix_rectangle", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__small_design_H0_forward", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__small_design_H1_forward", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__small_design_H1_reverse", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__small_design_no_nicks_added", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick__twice_on_same_domain", "tests/scadnano_tests.py::TestNickAndCrossover::test_add_nick_then_add_crossovers__6_helix_rectangle", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_max_offset", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_autocalculated", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_explicitly_specified", "tests/scadnano_tests.py::TestSetHelixIdx::test_set_helix_idx", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_no_groups_but_helices_reference_groups", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_grid", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_helices_view_order", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_fail_nonexistent", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_to_from_JSON", "tests/scadnano_tests.py::TestNames::test_strand_domain_names_json", "tests/scadnano_tests.py::TestNames::test_strand_names_can_be_nonunique", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_periodic_distances", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_start_default_min_offset", "tests/scadnano_tests.py::TestJSON::test_NoIndent_on_helix_without_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_color_specified_with_integer", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_default_order", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_nondefault_order", "tests/scadnano_tests.py::TestJSON::test_domain_labels", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_end_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_forward_and_right_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_helix_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_start_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_grid_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_strands_missing", "tests/scadnano_tests.py::TestJSON::test_json_tristan_example_issue_32", "tests/scadnano_tests.py::TestJSON::test_lack_of_NoIndent_on_helix_if_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_legacy_dna_sequence_key", "tests/scadnano_tests.py::TestJSON::test_legacy_right_key", "tests/scadnano_tests.py::TestJSON::test_legacy_substrands_key", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry_some_default", "tests/scadnano_tests.py::TestJSON::test_position_specified_with_origin_keyword", "tests/scadnano_tests.py::TestJSON::test_strand_idt", "tests/scadnano_tests.py::TestJSON::test_strand_labels", "tests/scadnano_tests.py::TestJSON::test_to_json__hairpin", "tests/scadnano_tests.py::TestJSON::test_to_json__roll", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_directly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_indirectly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_consecutive_domains_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_four_legally_leapfrogging_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_just_inside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_outside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_overlapping_caught_in_strange_counterexample", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_singleton_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_offset_beyond_maxbases", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_references_nonexistent_helix", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_and_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_illegally_overlapping_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_nonconsecutive_illegally_overlapping_strands", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_3_helix_before_design", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_append_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_insert_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_first_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_last_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_middle_domain_with_sequence", "tests/scadnano_tests.py::TestLabels::test_with_domain_label", "tests/scadnano_tests.py::TestLabels::test_with_domain_label__and__with_label", "tests/scadnano_tests.py::TestLabels::test_with_label__dict", "tests/scadnano_tests.py::TestLabels::test_with_label__str", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__illegal_overlapping_domains", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__2helix_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_insertions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_from_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_seq_with_wildcards", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_to_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_left_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_right_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix_wildcards_both_ends", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__from_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__hairpin", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_helix_with_one_bottom_strand_and_three_top_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_strand_assigned_by_complement_from_two_other_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_other_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_self_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__to_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_equal_length_strands_on_one_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_helices_with_multiple_domain_intersections", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__upper_left_edge_staple_of_16H_origami_rectangle", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__wildcards_simple", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__domain_sequence_too_long_error", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__to_individual_domains__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_method_chaining_with_domain_sequence", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions_and_insertions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_insertions" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-12-13 17:10:29+00:00
mit
800
UC-Davis-molecular-computing__scadnano-python-package-269
diff --git a/scadnano/scadnano.py b/scadnano/scadnano.py index 08a8953..f51f6de 100644 --- a/scadnano/scadnano.py +++ b/scadnano/scadnano.py @@ -1763,35 +1763,44 @@ class Helix(_JSONSerializable): angle %= 360 return angle - def crossovers(self) -> List[Tuple[int, int, bool]]: + def crossover_addresses(self) -> List[Tuple[int, int, bool]]: """ :return: - list of triples (`offset`, `helix_idx`, `forward`) of all crossovers incident to this + list of triples (`helix_idx`, `offset`, `forward`) of all crossovers incident to this :any:`Helix`, where `offset` is the offset of the crossover and `helix_idx` is the :data:`Helix.idx` of the other :any:`Helix` incident to the crossover. """ - crossovers: List[Tuple[int, int, bool]] = [] + addresses: List[Tuple[int, int, bool]] = [] for domain in self.domains: strand = domain.strand() domains_on_strand = strand.bound_domains() num_domains = len(domains_on_strand) domain_idx = domains_on_strand.index(domain) + domain_idx_in_substrands = strand.domains.index(domain) # if not first domain, then there is a crossover to the previous domain if domain_idx > 0: - offset = domain.offset_5p() - other_domain = domains_on_strand[domain_idx - 1] - other_helix_idx = other_domain.helix - crossovers.append((offset, other_helix_idx, domain.forward)) + # ... unless there's a loopout between them + previous_substrand = strand.domains[domain_idx_in_substrands - 1] + if isinstance(previous_substrand, Domain): + offset = domain.offset_5p() + other_domain = domains_on_strand[domain_idx - 1] + assert previous_substrand == other_domain + other_helix_idx = other_domain.helix + addresses.append((other_helix_idx, offset, domain.forward)) # if not last domain, then there is a crossover to the next domain if domain_idx < num_domains - 1: - offset = domain.offset_3p() - other_domain = domains_on_strand[domain_idx + 1] - other_helix_idx = other_domain.helix - crossovers.append((offset, other_helix_idx, domain.forward)) + # ... unless there's a loopout between them + next_substrand = strand.domains[domain_idx_in_substrands + 1] + if isinstance(next_substrand, Domain): + offset = domain.offset_3p() + other_domain = domains_on_strand[domain_idx + 1] + assert next_substrand == other_domain + other_helix_idx = other_domain.helix + addresses.append((other_helix_idx, offset, domain.forward)) - return crossovers + return addresses def relax_roll(self, helices: Dict[int, Helix], grid: Grid, geometry: Geometry) -> None: """ @@ -1806,7 +1815,7 @@ class Helix(_JSONSerializable): rather than changing the field :data:`Helix.roll`. """ angles = [] - for offset, helix_idx, forward in self.crossovers(): + for helix_idx, offset, forward in self.crossover_addresses(): other_helix = helices[helix_idx] angle_of_other_helix = angle_from_helix_to_helix(self, other_helix, grid, geometry) crossover_angle = self.backbone_angle_at_offset(offset, forward, geometry)
UC-Davis-molecular-computing/scadnano-python-package
e832e532199bcd8d727a813aa3a4562007483031
diff --git a/tests/scadnano_tests.py b/tests/scadnano_tests.py index 71f17c7..07c54b6 100644 --- a/tests/scadnano_tests.py +++ b/tests/scadnano_tests.py @@ -8215,6 +8215,78 @@ class TestHelixRollRelax(unittest.TestCase): self.assertAlmostEqual(exp_h1_roll, design3h.helices[1].roll) self.assertAlmostEqual(exp_h2_roll, design3h.helices[2].roll) + def test_3_helix_2_crossovers_1_loopout_crossovers_method(self) -> None: + ''' + 0 1 2 + 012345678901234567890 + 0 [---+[------+[------+ + | | \ + 1 [---+ | | + | / + 2 <------+<------+ + ''' + helices = [sc.Helix(max_offset=60) for _ in range(3)] + helices[2].grid_position = (1, 0) + design3h = sc.Design(helices=helices, grid=sc.square) + design3h.draw_strand(0, 0).move(5).cross(1).move(-5) + design3h.draw_strand(0, 5).move(8).cross(2).move(-8) + design3h.draw_strand(0, 13).move(8).loopout(2, 3).move(-8) + + crossover_addresses_h0 = helices[0].crossover_addresses() + crossover_addresses_h1 = helices[1].crossover_addresses() + crossover_addresses_h2 = helices[2].crossover_addresses() + + self.assertEqual(2, len(crossover_addresses_h0)) + self.assertEqual(1, len(crossover_addresses_h1)) + self.assertEqual(1, len(crossover_addresses_h2)) + + self.assertEqual((1, 4, True), crossover_addresses_h0[0]) + self.assertEqual((2, 12, True), crossover_addresses_h0[1]) + + self.assertEqual((0, 4, False), crossover_addresses_h1[0]) + + self.assertEqual((0, 12, False), crossover_addresses_h2[0]) + + def test_3_helix_2_crossovers_1_loopout(self) -> None: + ''' + 0 1 2 + 012345678901234567890 + 0 [---+[------+[------+ + | | \ + 1 [---+ | | + | / + 2 <------+<------+ + ''' + helices = [sc.Helix(max_offset=60) for _ in range(3)] + helices[2].grid_position = (1, 0) + design3h = sc.Design(helices=helices, grid=sc.square) + design3h.draw_strand(0, 0).move(5).cross(1).move(-5) + design3h.draw_strand(0, 5).move(8).cross(2).move(-8) + design3h.draw_strand(0, 13).move(8).loopout(2, 3).move(-8) + f1 = 4 / 10.5 + f2 = 12 / 10.5 + a1 = f1 * 360 % 360 + a2 = f2 * 360 % 360 + + # rules for angles: + # - add 150 if on reverse strand to account of minor groove + # - subtract angle of helix crossover is connecting to + + ave_h0 = (a1 - 180 + a2 - 90) / 2 # helix 1 at 180 degrees, helix 2 at 90 degrees + exp_h0_roll = (-ave_h0) % 360 + + ave_h1 = a1 + 150 # helix 0 at 0 degrees relative to helix 1 + exp_h1_roll = (-ave_h1) % 360 + + ave_h2 = a2 + 150 - (-90) # helix 0 at -90 degrees relative to helix 2 + exp_h2_roll = (-ave_h2) % 360 + + design3h.relax_helix_rolls() + + self.assertAlmostEqual(exp_h0_roll, design3h.helices[0].roll) + self.assertAlmostEqual(exp_h1_roll, design3h.helices[1].roll) + self.assertAlmostEqual(exp_h2_roll, design3h.helices[2].roll) + def test_3_helix_6_crossover(self) -> None: ''' 0 1 2 3 4 5 6 @@ -8275,7 +8347,7 @@ class TestHelixRollRelax(unittest.TestCase): 1 <---]<--------] ''' - initial_roll = 30 + initial_roll = 30.0 helices = [sc.Helix(max_offset=60, roll=initial_roll) for _ in range(2)] design2h = sc.Design(helices=helices, grid=sc.square) design2h.draw_strand(0, 0).move(5) @@ -8313,11 +8385,11 @@ class TestHelixRollRelax(unittest.TestCase): def test_helix_crossovers(self) -> None: ############################################ # 3-helix design with 3 strands - xs0 = self.design3helix3strand.helices[0].crossovers() + xs0 = self.design3helix3strand.helices[0].crossover_addresses() self.assertEqual(len(xs0), 3) - o0, h0, f0 = xs0[0] - o1, h1, f1 = xs0[1] - o2, h2, f2 = xs0[2] + h0, o0, f0 = xs0[0] + h1, o1, f1 = xs0[1] + h2, o2, f2 = xs0[2] self.assertEqual(o0, 4) self.assertEqual(o1, 14) self.assertEqual(o2, 26) @@ -8328,10 +8400,10 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f1, True) self.assertEqual(f2, True) - xs1 = self.design3helix3strand.helices[1].crossovers() + xs1 = self.design3helix3strand.helices[1].crossover_addresses() self.assertEqual(len(xs1), 2) - o0, h0, f0 = xs1[0] - o1, h1, f1 = xs1[1] + h0, o0, f0 = xs1[0] + h1, o1, f1 = xs1[1] self.assertEqual(o0, 4) self.assertEqual(o1, 26) self.assertEqual(h0, 0) @@ -8339,20 +8411,20 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f0, False) self.assertEqual(f1, False) - xs2 = self.design3helix3strand.helices[2].crossovers() + xs2 = self.design3helix3strand.helices[2].crossover_addresses() self.assertEqual(len(xs2), 1) - o0, h0, f0 = xs2[0] + h0, o0, f0 = xs2[0] self.assertEqual(o0, 14) self.assertEqual(h0, 0) self.assertEqual(h0, False) ############################################ # 2-helix design - xs0 = self.design2h.helices[0].crossovers() + xs0 = self.design2h.helices[0].crossover_addresses() self.assertEqual(len(xs0), 3) - o0, h0, f0 = xs0[0] - o1, h1, f1 = xs0[1] - o2, h2, f2 = xs0[2] + h0, o0, f0 = xs0[0] + h1, o1, f1 = xs0[1] + h2, o2, f2 = xs0[2] self.assertEqual(o0, 4) self.assertEqual(o1, 14) self.assertEqual(o2, 26) @@ -8363,11 +8435,11 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(h1, True) self.assertEqual(h2, True) - xs1 = self.design2h.helices[1].crossovers() + xs1 = self.design2h.helices[1].crossover_addresses() self.assertEqual(len(xs1), 3) - o0, h0, f0 = xs1[0] - o1, h1, f1 = xs1[1] - o2, h2, f2 = xs1[2] + h0, o0, f0 = xs1[0] + h1, o1, f1 = xs1[1] + h2, o2, f2 = xs1[2] self.assertEqual(o0, 4) self.assertEqual(o1, 14) self.assertEqual(o2, 26)
ignore loopouts when relaxing helix rolls The feature implemented from issue #257 has a bug, because it treats any two consecutive domains on a strand as though they have a crossover between them, even if they actually have a loopout between them. Re-write the algorithm for finding crossovers (https://scadnano-python-package.readthedocs.io/en/latest/#scadnano.Helix.crossovers) to ignore loopouts.
0.0
e832e532199bcd8d727a813aa3a4562007483031
[ "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout_crossovers_method", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossovers" ]
[ "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5__reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__5p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_then_update_to_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_decrease_increase_reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_increase_decrease_forward", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_update_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_loopout_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_on_circular_strand_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_5p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_with_name", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__h0_off0_to_off10_cross_h1_to_off5_loopout_length3_h2_to_off15", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels_and_colors_to_json", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_other_order", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_no_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_forward_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_reverse_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_domain_sequence_on_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_relative_offset", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_5p_extension", "tests/scadnano_tests.py::TestCreateHelix::test_helix_constructor_no_max_offset_with_major_ticks", "tests/scadnano_tests.py::TestM13::test_p7249", "tests/scadnano_tests.py::TestM13::test_p7560", "tests/scadnano_tests.py::TestM13::test_p8064", "tests/scadnano_tests.py::TestModifications::test_Cy3", "tests/scadnano_tests.py::TestModifications::test_biotin", "tests/scadnano_tests.py::TestModifications::test_mod_illegal_exceptions_raised", "tests/scadnano_tests.py::TestModifications::test_to_json__names_not_unique_for_modifications_raises_error", "tests/scadnano_tests.py::TestModifications::test_to_json__names_unique_for_modifications_raises_no_error", "tests/scadnano_tests.py::TestModifications::test_to_json_serializable", "tests/scadnano_tests.py::TestImportCadnanoV2::test_2_stape_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestImportCadnanoV2::test_32_helix_rectangle", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Nature09_monolith", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Science09_prot120_98_v3", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order2", "tests/scadnano_tests.py::TestImportCadnanoV2::test_huge_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestImportCadnanoV2::test_same_helix_crossover", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_purifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_scales", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_sequences", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_same_sequence", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_write_idt_plate_excel_file", "tests/scadnano_tests.py::TestExportCadnanoV2::test_16_helix_origami_rectangle_no_twist", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple_2", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_bundle_honeycomb", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_origami_rectangle", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples_hex", "tests/scadnano_tests.py::TestExportCadnanoV2::test_circular_strand", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group_not_same_grid", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_no_whitespace", "tests/scadnano_tests.py::TestExportCadnanoV2::test_extension", "tests/scadnano_tests.py::TestExportCadnanoV2::test_loopout", "tests/scadnano_tests.py::TestExportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestExportCadnanoV2::test_parity_issue", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__from_and_to_file_contents", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others_mixed_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices_mixed_with_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__three_strands", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__one_strand", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__three_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains_two_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_deletions", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_insertions", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_no_deletion_after_loopout", "tests/scadnano_tests.py::TestInlineInsDel::test_no_insertion_after_loopout", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal_only_one_helix_has_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__both_scaffolds_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__first_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__neither_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__second_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_0", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_15", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_8", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_no_nicks_added_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick_then_add_crossovers__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_ligate_all", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_no_ligation_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_extension_side_should_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_non_extension_side_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_nick_on_extension", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_max_offset", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_autocalculated", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_explicitly_specified", "tests/scadnano_tests.py::TestSetHelixIdx::test_set_helix_idx", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_pitch_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_roll_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_yaw_of_helix", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_no_groups_but_helices_reference_groups", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_grid", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_helices_view_order", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_fail_nonexistent", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_to_from_JSON", "tests/scadnano_tests.py::TestNames::test_strand_domain_names_json", "tests/scadnano_tests.py::TestNames::test_strand_names_can_be_nonunique", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_periodic_distances", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_start_default_min_offset", "tests/scadnano_tests.py::TestJSON::test_NoIndent_on_helix_without_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_both_helix_groups_and_helices_do_not_specify_pitch_nor_yaw", "tests/scadnano_tests.py::TestJSON::test_color_specified_with_integer", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_default_order", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_nondefault_order", "tests/scadnano_tests.py::TestJSON::test_domain_labels", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_end_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_forward_and_right_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_helix_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_start_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_grid_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_strands_missing", "tests/scadnano_tests.py::TestJSON::test_from_json_extension_design", "tests/scadnano_tests.py::TestJSON::test_grid_design_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_grid_helix_group_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_json_tristan_example_issue_32", "tests/scadnano_tests.py::TestJSON::test_lack_of_NoIndent_on_helix_if_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_legacy_dna_sequence_key", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__no_strand_name", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__strand_name_exists", "tests/scadnano_tests.py::TestJSON::test_legacy_right_key", "tests/scadnano_tests.py::TestJSON::test_legacy_substrands_key", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw_invalid", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry_some_default", "tests/scadnano_tests.py::TestJSON::test_only_helix_groups_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_only_individual_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_position_specified_with_origin_keyword", "tests/scadnano_tests.py::TestJSON::test_single_helix_group_and_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_strand_idt", "tests/scadnano_tests.py::TestJSON::test_strand_labels", "tests/scadnano_tests.py::TestJSON::test_to_json__hairpin", "tests/scadnano_tests.py::TestJSON::test_to_json__roll", "tests/scadnano_tests.py::TestJSON::test_to_json_extension_design__extension", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_directly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_indirectly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_consecutive_domains_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_domains_not_none_in_Strand_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_four_legally_leapfrogging_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_just_inside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_outside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_overlapping_caught_in_strange_counterexample", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_singleton_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_offset_beyond_maxbases", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_references_nonexistent_helix", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_and_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_illegally_overlapping_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_nonconsecutive_illegally_overlapping_strands", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_3_helix_before_design", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_append_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_insert_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_first_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_last_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_middle_domain_with_sequence", "tests/scadnano_tests.py::TestLabels::test_with_domain_label", "tests/scadnano_tests.py::TestLabels::test_with_domain_label__and__with_label", "tests/scadnano_tests.py::TestLabels::test_with_label__dict", "tests/scadnano_tests.py::TestLabels::test_with_label__str", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_3p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_5p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_can_add_internal_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_3p_mod", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_5p_mod", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_crossover_from_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_second_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_last_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_middle_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_ligate_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__illegal_overlapping_domains", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__2helix_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_insertions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_from_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_seq_with_wildcards", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_to_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_left_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_right_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix_wildcards_both_ends", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__from_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__hairpin", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_helix_with_one_bottom_strand_and_three_top_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_strand_assigned_by_complement_from_two_other_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_other_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_self_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__to_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_equal_length_strands_on_one_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_helices_with_multiple_domain_intersections", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__upper_left_edge_staple_of_16H_origami_rectangle", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__wildcards_simple", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__domain_sequence_too_long_error", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__to_individual_domains__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_method_chaining_with_domain_sequence", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions_and_insertions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_insertions", "tests/scadnano_tests.py::TestOxviewExport::test_bp", "tests/scadnano_tests.py::TestOxviewExport::test_export", "tests/scadnano_tests.py::TestOxviewExport::test_export_file", "tests/scadnano_tests.py::TestOxdnaExport::test_basic_design", "tests/scadnano_tests.py::TestOxdnaExport::test_deletion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_file_output", "tests/scadnano_tests.py::TestOxdnaExport::test_helix_groups", "tests/scadnano_tests.py::TestOxdnaExport::test_honeycomb_design", "tests/scadnano_tests.py::TestOxdnaExport::test_insertion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_loopout_design", "tests/scadnano_tests.py::TestPlateMaps::test_plate_map_markdown", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_angle_key_contains_non_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_length_key_contains_non_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__extension_key_contains_num_bases", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__label_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__name_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_angle_key_when_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_length_key_when_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_label_key_when_default_label", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_name_key_when_default_name", "tests/scadnano_tests.py::TestBasePairs::test_base_pairs_on_forward_strand_ahead_of_reverse_strand", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions_mismatch_in_insertion", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_dna_on_some_strands_and_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_dna", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_find_overlapping_domains", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_forward_strand", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_reverse_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_no_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_6_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_0_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_20", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_45_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_10_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_1_359", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_30_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_350_0_40", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_20_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_50_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_80_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_174_179_184_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_179_181_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_181_183_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_10_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_40_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0_and_20_0_310_relative_to_10" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2023-08-20 00:07:45+00:00
mit
801
UC-Davis-molecular-computing__scadnano-python-package-274
diff --git a/scadnano/scadnano.py b/scadnano/scadnano.py index 14b96ac..6cc4a22 100644 --- a/scadnano/scadnano.py +++ b/scadnano/scadnano.py @@ -1764,15 +1764,32 @@ class Helix(_JSONSerializable): angle %= 360 return angle - def crossover_addresses(self, allow_intrahelix=True) -> List[Tuple[int, int, bool]]: + def crossover_addresses(self, + helices: Dict[int, Helix], + allow_intrahelix: bool = True, + allow_intergroup: bool = True) -> List[Tuple[int, int, bool]]: """ + :param helices: + The dict of helices in which this :any:`Helix` is contained, that contains other helices + to which it might be connected by crossovers. :param allow_intrahelix: if ``False``, then do not return crossovers to the same :any:`Helix` as this :any:`Helix` + :param allow_intergroup: + if ``False``, then do not return crossovers to a :any:`Helix` in a different helix group + as this :any:`Helix` :return: list of triples (`helix_idx`, `offset`, `forward`) of all crossovers incident to this :any:`Helix`, where `offset` is the offset of the crossover and `helix_idx` is the :data:`Helix.idx` of the other :any:`Helix` incident to the crossover. """ + + def allow_crossover_to(other_helix: Helix) -> bool: + if not allow_intrahelix and other_helix.idx == self.idx: + return False + if not allow_intergroup and other_helix.group != self.group: + return False + return True + addresses: List[Tuple[int, int, bool]] = [] for domain in self.domains: strand = domain.strand() @@ -1790,7 +1807,8 @@ class Helix(_JSONSerializable): other_domain = domains_on_strand[domain_idx - 1] assert previous_substrand == other_domain other_helix_idx = other_domain.helix - if allow_intrahelix or other_helix_idx != self.idx: + other_helix = helices[other_helix_idx] + if allow_crossover_to(other_helix): addresses.append((other_helix_idx, offset, domain.forward)) # if not last domain, then there is a crossover to the next domain @@ -1802,7 +1820,8 @@ class Helix(_JSONSerializable): other_domain = domains_on_strand[domain_idx + 1] assert next_substrand == other_domain other_helix_idx = other_domain.helix - if allow_intrahelix or other_helix_idx != self.idx: + other_helix = helices[other_helix_idx] + if allow_crossover_to(other_helix): addresses.append((other_helix_idx, offset, domain.forward)) return addresses @@ -1820,7 +1839,7 @@ class Helix(_JSONSerializable): without actually altering the field :data:`Helix.roll`. """ angles = [] - addresses = self.crossover_addresses(allow_intrahelix=False) + addresses = self.crossover_addresses(helices, allow_intrahelix=False) for helix_idx, offset, forward in addresses: other_helix = helices[helix_idx] angle_of_other_helix = angle_from_helix_to_helix(self, other_helix, grid, geometry)
UC-Davis-molecular-computing/scadnano-python-package
d3a6d7d79196f39a6097e40ee4d73d17bd4643e8
diff --git a/tests/scadnano_tests.py b/tests/scadnano_tests.py index 7ed6cbd..b50c487 100644 --- a/tests/scadnano_tests.py +++ b/tests/scadnano_tests.py @@ -8149,7 +8149,7 @@ class TestHelixRollRelax(unittest.TestCase): 0123456789012345678901234567890123456789 0 [---+[--------+[----------+ | | | - 1 [---+<--------+<----------+ + 1 <---+<--------+<----------+ ''' self.design2h = sc.Design(helices=[sc.Helix(max_offset=50) for _ in range(2)]) # helix 0 forward @@ -8161,7 +8161,7 @@ class TestHelixRollRelax(unittest.TestCase): 0123456789012345678901234567890123456789 0 [---+[--------+[----------+ | | | - 1 [---+ |<----------+ + 1 <---+ |<----------+ | 2 <--------+ ''' @@ -8177,7 +8177,7 @@ class TestHelixRollRelax(unittest.TestCase): 012345678901234 0 [---+[------+ | | - 1 [---+ | + 1 <---+ | | 2 <------+ ''' @@ -8216,7 +8216,7 @@ class TestHelixRollRelax(unittest.TestCase): 012345678901234567890 0 [---+[------+[------+ | | \ - 1 [---+ | | + 1 <---+ | | | / 2 <------+<------+ ''' @@ -8227,9 +8227,9 @@ class TestHelixRollRelax(unittest.TestCase): design3h.draw_strand(0, 5).move(8).cross(2).move(-8) design3h.draw_strand(0, 13).move(8).loopout(2, 3).move(-8) - crossover_addresses_h0 = helices[0].crossover_addresses() - crossover_addresses_h1 = helices[1].crossover_addresses() - crossover_addresses_h2 = helices[2].crossover_addresses() + crossover_addresses_h0 = helices[0].crossover_addresses(design3h.helices) + crossover_addresses_h1 = helices[1].crossover_addresses(design3h.helices) + crossover_addresses_h2 = helices[2].crossover_addresses(design3h.helices) self.assertEqual(2, len(crossover_addresses_h0)) self.assertEqual(1, len(crossover_addresses_h1)) @@ -8248,7 +8248,7 @@ class TestHelixRollRelax(unittest.TestCase): 012345678901234567890 0 [---+[------+[------+ | | \ - 1 [---+ | | + 1 <---+ | | | / 2 <------+<------+ ''' @@ -8288,7 +8288,7 @@ class TestHelixRollRelax(unittest.TestCase): 012345678901234567890123456789012345678901234567890123456789 0 [---+[--------+[----------+[------+[--------+[--------+ | | | | | | - 1 [---+<--------+<----------+ | | | + 1 <---+<--------+<----------+ | | | | | | 2 <------+<--------+<--------+ ''' @@ -8436,7 +8436,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertAlmostEqual(exp_h1_roll, design2h.helices[1].roll) def test_helix_crossover_addresses_3_helix_3_strand(self) -> None: - xs0 = self.design3helix3strand.helices[0].crossover_addresses() + xs0 = self.design3helix3strand.helices[0].crossover_addresses(self.design3helix3strand.helices) self.assertEqual(len(xs0), 3) h0, o0, f0 = xs0[0] h1, o1, f1 = xs0[1] @@ -8451,7 +8451,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f1, True) self.assertEqual(f2, True) - xs1 = self.design3helix3strand.helices[1].crossover_addresses() + xs1 = self.design3helix3strand.helices[1].crossover_addresses(self.design3helix3strand.helices) self.assertEqual(len(xs1), 2) h0, o0, f0 = xs1[0] h1, o1, f1 = xs1[1] @@ -8462,7 +8462,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f0, False) self.assertEqual(f1, False) - xs2 = self.design3helix3strand.helices[2].crossover_addresses() + xs2 = self.design3helix3strand.helices[2].crossover_addresses(self.design3helix3strand.helices) self.assertEqual(len(xs2), 1) h0, o0, f0 = xs2[0] self.assertEqual(o0, 14) @@ -8470,7 +8470,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(h0, False) def test_helix_crossover_addresses_2_helix_3_strand(self) -> None: - xs0 = self.design2h.helices[0].crossover_addresses() + xs0 = self.design2h.helices[0].crossover_addresses(self.design2h.helices) self.assertEqual(len(xs0), 3) h0, o0, f0 = xs0[0] h1, o1, f1 = xs0[1] @@ -8485,7 +8485,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(h1, True) self.assertEqual(h2, True) - xs1 = self.design2h.helices[1].crossover_addresses() + xs1 = self.design2h.helices[1].crossover_addresses(self.design2h.helices) self.assertEqual(len(xs1), 3) h0, o0, f0 = xs1[0] h1, o1, f1 = xs1[1] @@ -8505,12 +8505,64 @@ class TestHelixRollRelax(unittest.TestCase): 0123456789012345678901234567890123456789 0 [---+[--------+[----------+[--+c+--> | | | - 1 [---+<--------+<----------+<--+c+--] + 1 <---+<--------+<----------+<--+c+--] ''' self.design2h.draw_strand(0, 27).move(4).cross(0, 32).move(4) self.design2h.draw_strand(1, 36).move(-4).cross(1, 31).move(-4) - xs0 = self.design2h.helices[0].crossover_addresses(allow_intrahelix=False) + xs0 = self.design2h.helices[0].crossover_addresses(self.design2h.helices, allow_intrahelix=False) + self.assertEqual(len(xs0), 3) + h0, o0, f0 = xs0[0] + h1, o1, f1 = xs0[1] + h2, o2, f2 = xs0[2] + self.assertEqual(o0, 4) + self.assertEqual(o1, 14) + self.assertEqual(o2, 26) + self.assertEqual(h0, 1) + self.assertEqual(h1, 1) + self.assertEqual(h2, 1) + self.assertEqual(f0, True) + self.assertEqual(f1, True) + self.assertEqual(f2, True) + + xs1 = self.design2h.helices[1].crossover_addresses(self.design2h.helices, allow_intrahelix=False) + self.assertEqual(len(xs1), 3) + h0, o0, f0 = xs1[0] + h1, o1, f1 = xs1[1] + h2, o2, f2 = xs1[2] + self.assertEqual(o0, 4) + self.assertEqual(o1, 14) + self.assertEqual(o2, 26) + self.assertEqual(h0, 0) + self.assertEqual(h1, 0) + self.assertEqual(h2, 0) + self.assertEqual(f0, False) + self.assertEqual(f1, False) + self.assertEqual(f2, False) + + def test_helix_crossover_addresses_2_helix_disallow_intergroup_crossovers(self) -> None: + ''' 1 2 3 + 0123456789012345678901234567890123456789 + 0 [---+[--------+[----------+[--+ + | | | | + 1 <---+<--------+<----------+ | + | + group 2 | + 2 <--+ + ''' + group2name = 'group 2' + group2 = sc.HelixGroup(position=sc.Position3D(x=0, y=-10, z=0), grid=sc.square, + helices_view_order=[2]) + self.design2h.groups[group2name] = group2 + self.design2h.add_helix(2, sc.Helix(max_offset=50, group=group2name)) + self.design2h.draw_strand(0, 27).move(4).cross(2).move(-4) + + self.assertEqual(2, len(self.design2h.groups)) + + exp_group_names = list(self.design2h.groups.keys()) + self.assertListEqual([sc.default_group_name, group2name], exp_group_names) + + xs0 = self.design2h.helices[0].crossover_addresses(self.design2h.helices, allow_intergroup=False) self.assertEqual(len(xs0), 3) h0, o0, f0 = xs0[0] h1, o1, f1 = xs0[1] @@ -8525,7 +8577,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f1, True) self.assertEqual(f2, True) - xs1 = self.design2h.helices[1].crossover_addresses(allow_intrahelix=False) + xs1 = self.design2h.helices[1].crossover_addresses(self.design2h.helices, allow_intergroup=False) self.assertEqual(len(xs1), 3) h0, o0, f0 = xs1[0] h1, o1, f1 = xs1[1] @@ -8540,6 +8592,9 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f1, False) self.assertEqual(f2, False) + xs2 = self.design2h.helices[2].crossover_addresses(self.design2h.helices, allow_intergroup=False) + self.assertEqual(len(xs2), 0) + def test_helix_crossover_addresses_2_helix_allow_intrahelix_crossovers(self) -> None: ''' 1 2 3 0123456789012345678901234567890123456789 @@ -8550,7 +8605,7 @@ class TestHelixRollRelax(unittest.TestCase): self.design2h.draw_strand(0, 27).move(4).cross(0, 32).move(4) self.design2h.draw_strand(1, 36).move(-4).cross(1, 31).move(-4) - xs0 = self.design2h.helices[0].crossover_addresses(allow_intrahelix=True) + xs0 = self.design2h.helices[0].crossover_addresses(self.design2h.helices, allow_intrahelix=True) self.assertEqual(len(xs0), 5) h0, o0, f0 = xs0[0] h1, o1, f1 = xs0[1] @@ -8573,7 +8628,7 @@ class TestHelixRollRelax(unittest.TestCase): self.assertEqual(f3, True) self.assertEqual(f4, True) - xs1 = self.design2h.helices[1].crossover_addresses(allow_intrahelix=True) + xs1 = self.design2h.helices[1].crossover_addresses(self.design2h.helices, allow_intrahelix=True) self.assertEqual(len(xs1), 5) h0, o0, f0 = xs1[0] h1, o1, f1 = xs1[1]
deal with inter-helix-group crossovers when relaxing helix rolls Currently, when relaxing helix rolls, all inter-helix crossovers are accounted for, but actually the calculation of the relative angle from one helix to another (based on the position of their 0 offset) only makes sense if the helices are in the same helix group, i.e., are parallel. If they are in different helix groups, we should do one of two things (possibly configurable with an option): 1. (easy) ignore those crossovers 2. (hard) do a more detailed calculation of the angle of the other helix, based not only on the helix's origin position, but also on the offsets of the two points on the helices the crossover connects.
0.0
d3a6d7d79196f39a6097e40ee4d73d17bd4643e8
[ "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_allow_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intergroup_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intrahelix_crossovers" ]
[ "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5__reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__5p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_then_update_to_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_decrease_increase_reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_increase_decrease_forward", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_update_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_loopout_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_on_circular_strand_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_5p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_with_name", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__h0_off0_to_off10_cross_h1_to_off5_loopout_length3_h2_to_off15", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels_and_colors_to_json", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_other_order", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_no_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_forward_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_reverse_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_domain_sequence_on_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_relative_offset", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_5p_extension", "tests/scadnano_tests.py::TestCreateHelix::test_helix_constructor_no_max_offset_with_major_ticks", "tests/scadnano_tests.py::TestM13::test_p7249", "tests/scadnano_tests.py::TestM13::test_p7560", "tests/scadnano_tests.py::TestM13::test_p8064", "tests/scadnano_tests.py::TestModifications::test_Cy3", "tests/scadnano_tests.py::TestModifications::test_biotin", "tests/scadnano_tests.py::TestModifications::test_mod_illegal_exceptions_raised", "tests/scadnano_tests.py::TestModifications::test_to_json__names_not_unique_for_modifications_raises_error", "tests/scadnano_tests.py::TestModifications::test_to_json__names_unique_for_modifications_raises_no_error", "tests/scadnano_tests.py::TestModifications::test_to_json_serializable", "tests/scadnano_tests.py::TestImportCadnanoV2::test_2_stape_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestImportCadnanoV2::test_32_helix_rectangle", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Nature09_monolith", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Science09_prot120_98_v3", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order2", "tests/scadnano_tests.py::TestImportCadnanoV2::test_huge_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestImportCadnanoV2::test_same_helix_crossover", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_purifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_scales", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_sequences", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_same_sequence", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_write_idt_plate_excel_file", "tests/scadnano_tests.py::TestExportCadnanoV2::test_16_helix_origami_rectangle_no_twist", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple_2", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_bundle_honeycomb", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_origami_rectangle", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples_hex", "tests/scadnano_tests.py::TestExportCadnanoV2::test_circular_strand", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group_not_same_grid", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_no_whitespace", "tests/scadnano_tests.py::TestExportCadnanoV2::test_extension", "tests/scadnano_tests.py::TestExportCadnanoV2::test_loopout", "tests/scadnano_tests.py::TestExportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestExportCadnanoV2::test_parity_issue", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__from_and_to_file_contents", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others_mixed_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices_mixed_with_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__three_strands", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__one_strand", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__three_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains_two_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_deletions", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_insertions", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_no_deletion_after_loopout", "tests/scadnano_tests.py::TestInlineInsDel::test_no_insertion_after_loopout", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal_only_one_helix_has_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__both_scaffolds_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__first_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__neither_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__second_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_0", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_15", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_8", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_no_nicks_added_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick_then_add_crossovers__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_ligate_all", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_no_ligation_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_extension_side_should_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_non_extension_side_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_nick_on_extension", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_max_offset", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_autocalculated", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_explicitly_specified", "tests/scadnano_tests.py::TestSetHelixIdx::test_set_helix_idx", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_pitch_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_roll_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_yaw_of_helix", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_no_groups_but_helices_reference_groups", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_grid", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_helices_view_order", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_fail_nonexistent", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_to_from_JSON", "tests/scadnano_tests.py::TestNames::test_strand_domain_names_json", "tests/scadnano_tests.py::TestNames::test_strand_names_can_be_nonunique", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_periodic_distances", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_start_default_min_offset", "tests/scadnano_tests.py::TestJSON::test_NoIndent_on_helix_without_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_both_helix_groups_and_helices_do_not_specify_pitch_nor_yaw", "tests/scadnano_tests.py::TestJSON::test_color_specified_with_integer", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_default_order", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_nondefault_order", "tests/scadnano_tests.py::TestJSON::test_domain_labels", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_end_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_forward_and_right_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_helix_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_start_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_grid_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_strands_missing", "tests/scadnano_tests.py::TestJSON::test_from_json_extension_design", "tests/scadnano_tests.py::TestJSON::test_grid_design_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_grid_helix_group_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_json_tristan_example_issue_32", "tests/scadnano_tests.py::TestJSON::test_lack_of_NoIndent_on_helix_if_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_legacy_dna_sequence_key", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__no_strand_name", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__strand_name_exists", "tests/scadnano_tests.py::TestJSON::test_legacy_right_key", "tests/scadnano_tests.py::TestJSON::test_legacy_substrands_key", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw_invalid", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry_some_default", "tests/scadnano_tests.py::TestJSON::test_only_helix_groups_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_only_individual_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_position_specified_with_origin_keyword", "tests/scadnano_tests.py::TestJSON::test_single_helix_group_and_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_strand_idt", "tests/scadnano_tests.py::TestJSON::test_strand_labels", "tests/scadnano_tests.py::TestJSON::test_to_json__hairpin", "tests/scadnano_tests.py::TestJSON::test_to_json__roll", "tests/scadnano_tests.py::TestJSON::test_to_json_extension_design__extension", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_directly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_indirectly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_consecutive_domains_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_domains_not_none_in_Strand_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_four_legally_leapfrogging_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_just_inside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_outside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_overlapping_caught_in_strange_counterexample", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_singleton_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_offset_beyond_maxbases", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_references_nonexistent_helix", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_and_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_illegally_overlapping_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_nonconsecutive_illegally_overlapping_strands", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_3_helix_before_design", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_append_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_insert_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_first_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_last_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_middle_domain_with_sequence", "tests/scadnano_tests.py::TestLabels::test_with_domain_label", "tests/scadnano_tests.py::TestLabels::test_with_domain_label__and__with_label", "tests/scadnano_tests.py::TestLabels::test_with_label__dict", "tests/scadnano_tests.py::TestLabels::test_with_label__str", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_3p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_5p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_can_add_internal_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_3p_mod", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_5p_mod", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_crossover_from_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_second_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_last_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_middle_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_ligate_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__illegal_overlapping_domains", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__2helix_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_insertions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_from_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_seq_with_wildcards", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_to_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_left_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_right_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix_wildcards_both_ends", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__from_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__hairpin", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_helix_with_one_bottom_strand_and_three_top_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_strand_assigned_by_complement_from_two_other_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_other_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_self_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__to_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_equal_length_strands_on_one_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_helices_with_multiple_domain_intersections", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__upper_left_edge_staple_of_16H_origami_rectangle", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__wildcards_simple", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__domain_sequence_too_long_error", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__to_individual_domains__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_method_chaining_with_domain_sequence", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions_and_insertions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_insertions", "tests/scadnano_tests.py::TestOxviewExport::test_bp", "tests/scadnano_tests.py::TestOxviewExport::test_export", "tests/scadnano_tests.py::TestOxviewExport::test_export_file", "tests/scadnano_tests.py::TestOxdnaExport::test_basic_design", "tests/scadnano_tests.py::TestOxdnaExport::test_deletion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_file_output", "tests/scadnano_tests.py::TestOxdnaExport::test_helix_groups", "tests/scadnano_tests.py::TestOxdnaExport::test_honeycomb_design", "tests/scadnano_tests.py::TestOxdnaExport::test_insertion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_loopout_design", "tests/scadnano_tests.py::TestPlateMaps::test_plate_map_markdown", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_angle_key_contains_non_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_length_key_contains_non_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__extension_key_contains_num_bases", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__label_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__name_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_angle_key_when_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_length_key_when_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_label_key_when_default_label", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_name_key_when_default_name", "tests/scadnano_tests.py::TestBasePairs::test_base_pairs_on_forward_strand_ahead_of_reverse_strand", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions_mismatch_in_insertion", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_dna_on_some_strands_and_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_dna", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_find_overlapping_domains", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_forward_strand", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_reverse_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_2_crossovers_call_relax_twice", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover_and_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_no_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout_crossovers_method", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_6_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_0_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_20", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_45_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_10_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_1_359", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_30_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_350_0_40", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_3_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_20_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_50_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_80_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_174_179_184_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_179_181_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_181_183_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_10_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_40_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0_and_20_0_310_relative_to_10" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-08-23 18:41:06+00:00
mit
802
UC-Davis-molecular-computing__scadnano-python-package-284
diff --git a/scadnano/scadnano.py b/scadnano/scadnano.py index 8cec304..fbd93bd 100644 --- a/scadnano/scadnano.py +++ b/scadnano/scadnano.py @@ -858,7 +858,10 @@ strands_key = 'strands' scaffold_key = 'scaffold' helices_view_order_key = 'helices_view_order' is_origami_key = 'is_origami' -design_modifications_key = 'modifications_in_design' +design_modifications_key = 'modifications_in_design' # legacy key for when we stored all mods in one dict +design_modifications_5p_key = 'modifications_5p_in_design' +design_modifications_3p_key = 'modifications_3p_in_design' +design_modifications_int_key = 'modifications_int_in_design' geometry_key = 'geometry' groups_key = 'groups' @@ -966,12 +969,22 @@ class ModificationType(enum.Enum): five_prime = "5'" """5' modification type""" - three_prime = "5'" + three_prime = "3'" """3' modification type""" internal = "internal" """internal modification type""" + def key(self) -> str: + if self == ModificationType.five_prime: + return design_modifications_5p_key + elif self == ModificationType.three_prime: + return design_modifications_3p_key + elif self == ModificationType.internal: + return design_modifications_int_key + else: + raise AssertionError(f'unknown ModificationType {self}') + @dataclass(frozen=True, eq=True) class Modification(_JSONSerializable, ABC): @@ -3962,16 +3975,20 @@ class Strand(_JSONSerializable): name = f'{start_helix}[{start_offset}]{forward_str}{end_helix}[{end_offset}]' return f'SCAF{name}' if self.is_scaffold else f'ST{name}' - def set_modification_5p(self, mod: Modification5Prime = None) -> None: - """Sets 5' modification to be `mod`. `mod` cannot be non-None if :any:`Strand.circular` is True.""" - if self.circular and mod is not None: + def set_modification_5p(self, mod: Modification5Prime) -> None: + """Sets 5' modification to be `mod`. :any:`Strand.circular` must be False.""" + if self.circular: raise StrandError(self, "cannot have a 5' modification on a circular strand") + if not isinstance(mod, Modification5Prime): + raise TypeError(f'mod must be a Modification5Prime but it is type {type(mod)}: {mod}') self.modification_5p = mod - def set_modification_3p(self, mod: Modification3Prime = None) -> None: - """Sets 3' modification to be `mod`. `mod` cannot be non-None if :any:`Strand.circular` is True.""" + def set_modification_3p(self, mod: Modification3Prime) -> None: + """Sets 3' modification to be `mod`. :any:`Strand.circular` must be False.""" if self.circular and mod is not None: raise StrandError(self, "cannot have a 3' modification on a circular strand") + if not isinstance(mod, Modification3Prime): + raise TypeError(f'mod must be a Modification3Prime but it is type {type(mod)}: {mod}') self.modification_3p = mod def remove_modification_5p(self) -> None: @@ -3999,6 +4016,8 @@ class Strand(_JSONSerializable): elif warn_on_no_dna: print('WARNING: no DNA sequence has been assigned, so certain error checks on the internal ' 'modification were not done. To be safe, first assign DNA, then add the modifications.') + if not isinstance(mod, ModificationInternal): + raise TypeError(f'mod must be a ModificationInternal but it is type {type(mod)}: {mod}') self.modifications_int[idx] = mod def remove_modification_internal(self, idx: int) -> None: @@ -5763,10 +5782,27 @@ class Design(_JSONSerializable): strand = Strand.from_json(strand_json) strands.append(strand) - # modifications in whole design + mods_5p: Dict[str, Modification5Prime] = {} + mods_3p: Dict[str, Modification3Prime] = {} + mods_int: Dict[str, ModificationInternal] = {} + for all_mods_key, mods in zip([design_modifications_5p_key, + design_modifications_3p_key, + design_modifications_int_key], [mods_5p, mods_3p, mods_int]): + if all_mods_key in json_map: + all_mods_json = json_map[all_mods_key] + for mod_key, mod_json in all_mods_json.items(): + mod = Modification.from_json(mod_json) + if mod_key != mod.vendor_code: + print(f'WARNING: key {mod_key} does not match vendor_code field {mod.vendor_code}' + f'for modification {mod}\n' + f'replacing with key = {mod.vendor_code}') + mod = dataclasses.replace(mod, vendor_code=mod_key) + mods[mod_key] = mod + + # legacy code; now we stored modifications in 3 separate dicts depending on 5', 3', internal + all_mods: Dict[str, Modification] = {} if design_modifications_key in json_map: all_mods_json = json_map[design_modifications_key] - all_mods = {} for mod_key, mod_json in all_mods_json.items(): mod = Modification.from_json(mod_json) if mod_key != mod.vendor_code: @@ -5775,7 +5811,8 @@ class Design(_JSONSerializable): f'replacing with key = {mod.vendor_code}') mod = dataclasses.replace(mod, vendor_code=mod_key) all_mods[mod_key] = mod - Design.assign_modifications_to_strands(strands, strand_jsons, all_mods) + + Design.assign_modifications_to_strands(strands, strand_jsons, mods_5p, mods_3p, mods_int, all_mods) geometry = None if geometry_key in json_map: @@ -5831,19 +5868,25 @@ class Design(_JSONSerializable): self.helices_view_order) if suppress_indent else self.helices_view_order # modifications - mods = self.modifications() - if len(mods) > 0: - mods_dict = {} - for mod in mods: - if mod.vendor_code not in mods_dict: - mods_dict[mod.vendor_code] = mod.to_json_serializable(suppress_indent) - else: - if mod != mods_dict[mod.vendor_code]: - raise IllegalDesignError(f"Modifications must have unique vendor codes, but I found" - f"two different Modifications that share vendor code " - f"{mod.vendor_code}:\n{mod}\nand\n" - f"{mods_dict[mod.vendor_code]}") - dct[design_modifications_key] = mods_dict + for mod_type in [ModificationType.five_prime, + ModificationType.three_prime, + ModificationType.internal]: + mods = self.modifications(mod_type) + mod_key = mod_type.key() + if len(mods) > 0: + mods_dict = {} + for mod in mods: + if mod.vendor_code not in mods_dict: + mods_dict[mod.vendor_code] = mod.to_json_serializable(suppress_indent) + else: + if mod != mods_dict[mod.vendor_code]: + raise IllegalDesignError( + f"Modifications of type {mod_type} must have unique vendor codes, " + f"but I foundtwo different Modifications of that type " + f"that share vendor code " + f"{mod.vendor_code}:\n{mod}\nand\n" + f"{mods_dict[mod.vendor_code]}") + dct[mod_key] = mods_dict dct[strands_key] = [strand.to_json_serializable(suppress_indent) for strand in self.strands] @@ -5940,19 +5983,34 @@ class Design(_JSONSerializable): @staticmethod def assign_modifications_to_strands(strands: List[Strand], strand_jsons: List[dict], + mods_5p: Dict[str, Modification5Prime], + mods_3p: Dict[str, Modification3Prime], + mods_int: Dict[str, ModificationInternal], all_mods: Dict[str, Modification]) -> None: + if len(all_mods) > 0: # legacy code for when modifications were stored in a single dict + assert len(mods_5p) == 0 and len(mods_3p) == 0 and len(mods_int) == 0 + legacy = True + elif len(mods_5p) > 0 or len(mods_3p) > 0 or len(mods_int) > 0: + assert len(all_mods) == 0 + legacy = False + else: # no modifications + return + for strand, strand_json in zip(strands, strand_jsons): if modification_5p_key in strand_json: - mod_name = strand_json[modification_5p_key] - strand.modification_5p = cast(Modification5Prime, all_mods[mod_name]) + mod_code = strand_json[modification_5p_key] + strand.modification_5p = cast(Modification5Prime, all_mods[mod_code]) \ + if legacy else mods_5p[mod_code] if modification_3p_key in strand_json: - mod_name = strand_json[modification_3p_key] - strand.modification_3p = cast(Modification3Prime, all_mods[mod_name]) + mod_code = strand_json[modification_3p_key] + strand.modification_3p = cast(Modification3Prime, all_mods[mod_code]) \ + if legacy else mods_3p[mod_code] if modifications_int_key in strand_json: mod_names_by_offset = strand_json[modifications_int_key] - for offset_str, mod_name in mod_names_by_offset.items(): + for offset_str, mod_code in mod_names_by_offset.items(): offset = int(offset_str) - strand.modifications_int[offset] = cast(ModificationInternal, all_mods[mod_name]) + strand.modifications_int[offset] = cast(ModificationInternal, all_mods[mod_code]) \ + if legacy else mods_int[mod_code] @staticmethod def _cadnano_v2_import_find_5_end(vstrands: VStrands, strand_type: str, helix_num: int, base_id: int, @@ -6079,7 +6137,7 @@ class Design(_JSONSerializable): @staticmethod def _cadnano_v2_import_circular_strands_merge_first_last_domains(domains: List[Domain]) -> None: """ When we create domains for circular strands in the cadnano import routine, we may end up - with a fake crossover if first and last domain are on same helix, we have to merge them + with a fake crossover if first and last domain are on same helix, we have to merge them if it is the case. """ if domains[0].helix != domains[-1].helix: @@ -6210,9 +6268,9 @@ class Design(_JSONSerializable): # TS: Dave, I have thorougly checked the code of Design constructor and the order of the helices # IS lost even if the helices were give as a list. # Indeed, you very early call `_normalize_helices_as_dict` in the constructor the order is lost. - # Later in the code, if no view order was given the code will choose the identity + # Later in the code, if no view order was given the code will choose the identity # in function `_check_helices_view_order_and_return`. - # Conclusion: do not assume that your constructor code deals with the ordering, even if + # Conclusion: do not assume that your constructor code deals with the ordering, even if # input helices is a list. I am un commenting the below: design.set_helices_view_order([num for num in helices]) @@ -7641,7 +7699,7 @@ class Design(_JSONSerializable): # IDT charges extra for a plate with < 24 strands for 96-well plate # or < 96 strands for 384-well plate. - # So if we would have fewer than that many on the last plate, + # So if we would have fewer than that many on the last plate, # shift some from the penultimate plate. if not on_final_plate and \ final_plate_less_than_min_required and \ @@ -7670,7 +7728,7 @@ class Design(_JSONSerializable): have duplicate names. (default: True) :param use_strand_colors: if True (default), sets the color of each nucleotide in a strand in oxView to the color - of the strand. + of the strand. """ import datetime self._check_legal_design(warn_duplicate_strand_names) @@ -8184,7 +8242,8 @@ class Design(_JSONSerializable): strand_3p.domains.append(dom_new) strand_3p.domains.extend(strand_5p.domains[1:]) strand_3p.is_scaffold = strand_left.is_scaffold or strand_right.is_scaffold - strand_3p.set_modification_3p(strand_5p.modification_3p) + if strand_5p.modification_3p is not None: + strand_3p.set_modification_3p(strand_5p.modification_3p) for idx, mod in strand_5p.modifications_int.items(): new_idx = idx + strand_3p.dna_length() strand_3p.set_modification_internal(new_idx, mod)
UC-Davis-molecular-computing/scadnano-python-package
fc3086264e1e5857f7585b2e382d4330cee60822
diff --git a/tests/scadnano_tests.py b/tests/scadnano_tests.py index ddeb33a..62c0472 100644 --- a/tests/scadnano_tests.py +++ b/tests/scadnano_tests.py @@ -637,16 +637,17 @@ class TestModifications(unittest.TestCase): sc.Modification3Prime(display_text=name, vendor_code=name + '3')) design.to_json(True) - def test_to_json__names_not_unique_for_modifications_raises_error(self) -> None: + def test_to_json__names_not_unique_for_modifications_5p_raises_error(self) -> None: helices = [sc.Helix(max_offset=100)] design: sc.Design = sc.Design(helices=helices, strands=[], grid=sc.square) - name = 'mod_name' + code1 = 'mod_code1' + code2 = 'mod_code2' design.draw_strand(0, 0).move(5).with_modification_5p( - sc.Modification5Prime(display_text=name, vendor_code=name)) - design.draw_strand(0, 5).move(5).with_modification_3p( - sc.Modification3Prime(display_text=name, vendor_code=name)) + sc.Modification5Prime(display_text=code1, vendor_code=code1)) + design.draw_strand(0, 5).move(5).with_modification_5p( + sc.Modification5Prime(display_text=code2, vendor_code=code1)) with self.assertRaises(sc.IllegalDesignError): - design.to_json(True) + design.to_json(False) def test_mod_illegal_exceptions_raised(self) -> None: strand = sc.Strand(domains=[sc.Domain(0, True, 0, 5)], dna_sequence='AATGC') @@ -793,18 +794,22 @@ class TestModifications(unittest.TestCase): # print(design.to_json()) json_dict = design.to_json_serializable(suppress_indent=False) - self.assertTrue(sc.design_modifications_key in json_dict) - mods_dict = json_dict[sc.design_modifications_key] - self.assertTrue(r'/5Biosg/' in mods_dict) - self.assertTrue(r'/3Bio/' in mods_dict) - self.assertTrue(r'/iBiodT/' in mods_dict) - - biotin5_json = mods_dict[r'/5Biosg/'] + self.assertTrue(sc.design_modifications_5p_key in json_dict) + self.assertTrue(sc.design_modifications_3p_key in json_dict) + self.assertTrue(sc.design_modifications_int_key in json_dict) + mods_5p_dict = json_dict[sc.design_modifications_5p_key] + self.assertTrue(r'/5Biosg/' in mods_5p_dict) + mods_3p_dict = json_dict[sc.design_modifications_3p_key] + self.assertTrue(r'/3Bio/' in mods_3p_dict) + mods_int_dict = json_dict[sc.design_modifications_int_key] + self.assertTrue(r'/iBiodT/' in mods_int_dict) + + biotin5_json = mods_5p_dict[r'/5Biosg/'] self.assertEqual('/5Biosg/', biotin5_json[sc.mod_vendor_code_key]) self.assertEqual('B', biotin5_json[sc.mod_display_text_key]) self.assertEqual(6, biotin5_json[sc.mod_connector_length_key]) - biotin3_json = mods_dict[r'/3Bio/'] + biotin3_json = mods_3p_dict[r'/3Bio/'] self.assertEqual('/3Bio/', biotin3_json[sc.mod_vendor_code_key]) self.assertEqual('B', biotin3_json[sc.mod_display_text_key]) self.assertNotIn(sc.mod_connector_length_key, biotin3_json)
deal with non-unique Modification vendor codes Eurofins does not use unique vendor codes for their modifications: https://eurofinsgenomics.com/en/products/dnarna-synthesis/mods/ For example, Biotin TEG can be used on the 5' or 3' end, but both use the code `[BIOTEG]`. Deal with this somehow, now that scadnano has switched to using vendor codes as the unique ID for a modification. Perhaps we can store three separate Dicts, one for 5', 3', internal, to store modifications in the design. Alternatively, we could go back to what the web interface used to do, and prepend `"5'-"`, `"3'-"`, or `"int-"` to the front of the key. I like the first solution better, to match how we split the storage of Modifications in Strands.
0.0
fc3086264e1e5857f7585b2e382d4330cee60822
[ "tests/scadnano_tests.py::TestModifications::test_to_json_serializable" ]
[ "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5__reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__5p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_then_update_to_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_decrease_increase_reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_increase_decrease_forward", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_update_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_loopout_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_on_circular_strand_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_5p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_with_name", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__h0_off0_to_off10_cross_h1_to_off5_loopout_length3_h2_to_off15", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels_and_colors_to_json", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_other_order", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_no_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_forward_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_reverse_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_domain_sequence_on_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_relative_offset", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_5p_extension", "tests/scadnano_tests.py::TestCreateHelix::test_helix_constructor_no_max_offset_with_major_ticks", "tests/scadnano_tests.py::TestM13::test_p7249", "tests/scadnano_tests.py::TestM13::test_p7560", "tests/scadnano_tests.py::TestM13::test_p8064", "tests/scadnano_tests.py::TestModifications::test_Cy3", "tests/scadnano_tests.py::TestModifications::test_biotin", "tests/scadnano_tests.py::TestModifications::test_mod_illegal_exceptions_raised", "tests/scadnano_tests.py::TestModifications::test_to_json__names_not_unique_for_modifications_5p_raises_error", "tests/scadnano_tests.py::TestModifications::test_to_json__names_unique_for_modifications_raises_no_error", "tests/scadnano_tests.py::TestImportCadnanoV2::test_2_stape_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestImportCadnanoV2::test_32_helix_rectangle", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Nature09_monolith", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Science09_prot120_98_v3", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order2", "tests/scadnano_tests.py::TestImportCadnanoV2::test_huge_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestImportCadnanoV2::test_same_helix_crossover", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters_internal_nonbase_modifications", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters_modifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_purifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_scales", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_sequences", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_same_sequence", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_write_idt_plate_excel_file", "tests/scadnano_tests.py::TestExportCadnanoV2::test_16_helix_origami_rectangle_no_twist", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple_2", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_bundle_honeycomb", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_origami_rectangle", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples_hex", "tests/scadnano_tests.py::TestExportCadnanoV2::test_circular_strand", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group_not_same_grid", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_no_whitespace", "tests/scadnano_tests.py::TestExportCadnanoV2::test_extension", "tests/scadnano_tests.py::TestExportCadnanoV2::test_loopout", "tests/scadnano_tests.py::TestExportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestExportCadnanoV2::test_parity_issue", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__from_and_to_file_contents", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others_mixed_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices_mixed_with_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__three_strands", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__one_strand", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__three_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains_two_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_deletions", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_insertions", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_no_deletion_after_loopout", "tests/scadnano_tests.py::TestInlineInsDel::test_no_insertion_after_loopout", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal_only_one_helix_has_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__both_scaffolds_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__first_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__neither_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__second_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_0", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_15", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_8", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_no_nicks_added_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick_then_add_crossovers__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_ligate_all", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_no_ligation_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_extension_side_should_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_non_extension_side_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_nick_on_extension", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_max_offset", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_autocalculated", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_explicitly_specified", "tests/scadnano_tests.py::TestSetHelixIdx::test_set_helix_idx", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_pitch_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_roll_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_yaw_of_helix", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_no_groups_but_helices_reference_groups", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_grid", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_helices_view_order", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_fail_nonexistent", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_to_from_JSON", "tests/scadnano_tests.py::TestNames::test_strand_domain_names_json", "tests/scadnano_tests.py::TestNames::test_strand_names_can_be_nonunique", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_periodic_distances", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_start_default_min_offset", "tests/scadnano_tests.py::TestJSON::test_NoIndent_on_helix_without_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_both_helix_groups_and_helices_do_not_specify_pitch_nor_yaw", "tests/scadnano_tests.py::TestJSON::test_color_specified_with_integer", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_default_order", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_nondefault_order", "tests/scadnano_tests.py::TestJSON::test_domain_labels", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_end_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_forward_and_right_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_helix_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_start_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_grid_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_strands_missing", "tests/scadnano_tests.py::TestJSON::test_from_json_extension_design", "tests/scadnano_tests.py::TestJSON::test_grid_design_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_grid_helix_group_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_json_tristan_example_issue_32", "tests/scadnano_tests.py::TestJSON::test_lack_of_NoIndent_on_helix_if_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_legacy_dna_sequence_key", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__no_strand_name", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__strand_name_exists", "tests/scadnano_tests.py::TestJSON::test_legacy_right_key", "tests/scadnano_tests.py::TestJSON::test_legacy_substrands_key", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw_invalid", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry_some_default", "tests/scadnano_tests.py::TestJSON::test_only_helix_groups_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_only_individual_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_position_specified_with_origin_keyword", "tests/scadnano_tests.py::TestJSON::test_single_helix_group_and_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_strand_idt", "tests/scadnano_tests.py::TestJSON::test_strand_labels", "tests/scadnano_tests.py::TestJSON::test_to_json__hairpin", "tests/scadnano_tests.py::TestJSON::test_to_json__roll", "tests/scadnano_tests.py::TestJSON::test_to_json_extension_design__extension", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_directly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_indirectly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_consecutive_domains_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_domains_not_none_in_Strand_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_four_legally_leapfrogging_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_just_inside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_outside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_overlapping_caught_in_strange_counterexample", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_singleton_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_offset_beyond_maxbases", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_references_nonexistent_helix", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_and_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_illegally_overlapping_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_nonconsecutive_illegally_overlapping_strands", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_3_helix_before_design", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_append_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_insert_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_first_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_last_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_middle_domain_with_sequence", "tests/scadnano_tests.py::TestLabels::test_with_domain_label", "tests/scadnano_tests.py::TestLabels::test_with_domain_label__and__with_label", "tests/scadnano_tests.py::TestLabels::test_with_label__dict", "tests/scadnano_tests.py::TestLabels::test_with_label__str", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_3p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_5p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_can_add_internal_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_3p_mod", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_5p_mod", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_crossover_from_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_second_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_last_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_middle_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_ligate_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__illegal_overlapping_domains", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__2helix_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_insertions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_from_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_seq_with_wildcards", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_to_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_left_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_right_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix_wildcards_both_ends", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__from_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__hairpin", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_helix_with_one_bottom_strand_and_three_top_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_strand_assigned_by_complement_from_two_other_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_other_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_self_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__to_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_equal_length_strands_on_one_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_helices_with_multiple_domain_intersections", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__upper_left_edge_staple_of_16H_origami_rectangle", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__wildcards_simple", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__domain_sequence_too_long_error", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__to_individual_domains__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_method_chaining_with_domain_sequence", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions_and_insertions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_insertions", "tests/scadnano_tests.py::TestOxviewExport::test_bp", "tests/scadnano_tests.py::TestOxviewExport::test_export", "tests/scadnano_tests.py::TestOxviewExport::test_export_file", "tests/scadnano_tests.py::TestOxdnaExport::test_basic_design", "tests/scadnano_tests.py::TestOxdnaExport::test_deletion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_file_output", "tests/scadnano_tests.py::TestOxdnaExport::test_helix_groups", "tests/scadnano_tests.py::TestOxdnaExport::test_honeycomb_design", "tests/scadnano_tests.py::TestOxdnaExport::test_insertion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_loopout_design", "tests/scadnano_tests.py::TestPlateMaps::test_plate_map_markdown", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_angle_key_contains_non_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_length_key_contains_non_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__extension_key_contains_num_bases", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__label_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__name_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_angle_key_when_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_length_key_when_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_label_key_when_default_label", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_name_key_when_default_name", "tests/scadnano_tests.py::TestBasePairs::test_base_pairs_on_forward_strand_ahead_of_reverse_strand", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions_mismatch_in_insertion", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_dna_on_some_strands_and_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_dna", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_find_overlapping_domains", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_forward_strand", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_reverse_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_2_crossovers_call_relax_twice", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover_and_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_no_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout_crossovers_method", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_6_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_0_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_20", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_45_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_10_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_1_359", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_30_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_350_0_40", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_allow_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intergroup_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_3_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_20_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_50_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_80_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_174_179_184_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_179_181_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_181_183_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_10_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_40_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0_and_20_0_310_relative_to_10" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-09-03 20:55:24+00:00
mit
803
UC-Davis-molecular-computing__scadnano-python-package-288
diff --git a/scadnano/scadnano.py b/scadnano/scadnano.py index 9b4e869..e0902ee 100644 --- a/scadnano/scadnano.py +++ b/scadnano/scadnano.py @@ -54,7 +54,7 @@ so the user must take care not to set them. # needed to use forward annotations: https://docs.python.org/3/whatsnew/3.7.html#whatsnew37-pep563 from __future__ import annotations -__version__ = "0.19.0" # version line; WARNING: do not remove or change this line or comment +__version__ = "0.19.1" # version line; WARNING: do not remove or change this line or comment import collections import dataclasses @@ -2016,6 +2016,40 @@ def _is_close(x1: float, x2: float) -> bool: return abs(x1 - x2) < _floating_point_tolerance +def _vendor_dna_sequence_substrand(substrand: Union[Domain, Loopout, Extension]) -> Optional[str]: + # used to share code between Domain, Loopout Extension + # for adding modification codes to exported DNA sequence + if substrand.dna_sequence is None: + return None + + strand = substrand.strand() + len_dna_prior = 0 + for other_substrand in strand.domains: + if other_substrand is substrand: + break + len_dna_prior += other_substrand.dna_length() + + new_seq_list = [] + for pos, base in enumerate(substrand.dna_sequence): + new_seq_list.append(base) + strand_pos = pos + len_dna_prior + if strand_pos in strand.modifications_int: # if internal mod attached to base, replace base + mod = strand.modifications_int[strand_pos] + if mod.vendor_code is not None: + vendor_code_with_delim = mod.vendor_code + if mod.allowed_bases is not None: + if base not in mod.allowed_bases: + msg = (f'internal modification {mod} can only replace one of these bases: ' + f'{",".join(mod.allowed_bases)}, ' + f'but the base at position {strand_pos} is {base}') + raise IllegalDesignError(msg) + new_seq_list[-1] = vendor_code_with_delim # replace base with modified base + else: + new_seq_list.append(vendor_code_with_delim) # append modification between two bases + + return ''.join(new_seq_list) + + @dataclass class Domain(_JSONSerializable): """ @@ -2167,35 +2201,7 @@ class Domain(_JSONSerializable): The difference between this and the field :data:`Domain.dna_sequence` is that this will add internal modification codes. """ - if self.dna_sequence is None: - return None - - strand = self.strand() - len_dna_prior = 0 - for domain in strand.domains: - if domain is self: - break - len_dna_prior += domain.dna_length() - - new_seq_list = [] - for pos, base in enumerate(self.dna_sequence): - new_seq_list.append(base) - strand_pos = pos + len_dna_prior - if strand_pos in strand.modifications_int: # if internal mod attached to base, replace base - mod = strand.modifications_int[strand_pos] - if mod.vendor_code is not None: - vendor_code_with_delim = mod.vendor_code - if mod.allowed_bases is not None: - if base not in mod.allowed_bases: - msg = (f'internal modification {mod} can only replace one of these bases: ' - f'{",".join(mod.allowed_bases)}, ' - f'but the base at position {strand_pos} is {base}') - raise IllegalDesignError(msg) - new_seq_list[-1] = vendor_code_with_delim # replace base with modified base - else: - new_seq_list.append(vendor_code_with_delim) # append modification between two bases - - return ''.join(new_seq_list) + return _vendor_dna_sequence_substrand(self) def set_name(self, name: str) -> None: """Sets name of this :any:`Domain`.""" @@ -2565,6 +2571,15 @@ class Loopout(_JSONSerializable): def __str__(self) -> str: return repr(self) if self.name is None else self.name + def vendor_dna_sequence(self) -> Optional[str]: + """ + :return: + vendor DNA sequence of this :any:`Loopout`, or ``None`` if no DNA sequence has been assigned. + The difference between this and the field :data:`Loopout.dna_sequence` is that this + will add internal modification codes. + """ + return _vendor_dna_sequence_substrand(self) + def set_name(self, name: str) -> None: """Sets name of this :any:`Loopout`.""" self.name = name @@ -2617,8 +2632,8 @@ class Extension(_JSONSerializable): import scadnano as sc domain = sc.Domain(helix=0, forward=True, start=0, end=10) - left_toehold = sc.Extension(num_bases=6) - right_toehold = sc.Extension(num_bases=5) + left_toehold = sc.Extension(num_bases=3) + right_toehold = sc.Extension(num_bases=2) strand = sc.Strand([left_toehold, domain, right_toehold]) It can also be created with chained method calls @@ -2701,6 +2716,23 @@ class Extension(_JSONSerializable): """Length of this :any:`Extension`; same as field :data:`Extension.num_bases`.""" return self.num_bases + def strand(self) -> Strand: + """ + :return: The :any:`Strand` that contains this :any:`Extension`. + """ + if self._parent_strand is None: + raise ValueError('_parent_strand has not yet been set') + return self._parent_strand + + def vendor_dna_sequence(self) -> Optional[str]: + """ + :return: + vendor DNA sequence of this :any:`Extension`, or ``None`` if no DNA sequence has been assigned. + The difference between this and the field :data:`Extension.dna_sequence` is that this + will add internal modification codes. + """ + return _vendor_dna_sequence_substrand(self) + def set_label(self, label: Optional[str]) -> None: """Sets label of this :any:`Extension`.""" self.label = label @@ -3709,7 +3741,7 @@ class Strand(_JSONSerializable): def __post_init__(self) -> None: self._ensure_domains_not_none() - self.set_domains(self.domains) + self.set_domains(self.domains) # some error-checking code is in this method self._ensure_modifications_legal() self._ensure_domains_nonoverlapping() @@ -3886,15 +3918,18 @@ class Strand(_JSONSerializable): def set_domains(self, domains: Iterable[Union[Domain, Loopout]]) -> None: """ - Sets the :any:`Domain`'s/:any:`Loopout`'s of this :any:`Strand` to be `domains`, - which can contain a mix of :any:`Domain`'s and :any:`Loopout`'s, + Sets the :any:`Domain`'s/:any:`Loopout`'s/:any:`Extension`'s of this :any:`Strand` to be `domains`, + which can contain a mix of :any:`Domain`'s, :any:`Loopout`'s, and :any:`Extension`'s, just like the field :py:data:`Strand.domains`. :param domains: - The new sequence of :any:`Domain`'s/:any:`Loopout`'s to use for this :any:`Strand`. + The new sequence of :any:`Domain`'s/:any:`Loopout`'s/:any:`Extension`'s to use for this + :any:`Strand`. :raises StrandError: - if domains has two consecutive :any:`Loopout`'s, consists of just a single :any:`Loopout`'s, - or starts or ends with a :any:`Loopout` + if domains has two consecutive :any:`Loopout`'s, consists of just a single :any:`Loopout`'s + or a single :any:`Extension`, or starts or ends with a :any:`Loopout`, + or has an :any:`Extension` on a circular :any:`Strand`, + or has an :any:`Extension` not as the first or last element of `domains`. """ self.domains = domains if isinstance(domains, list) else list(domains) @@ -3912,6 +3947,10 @@ class Strand(_JSONSerializable): if len(self.domains) == 0: raise StrandError(self, 'domains cannot be empty') + for domain in self.domains[1:-1]: + if isinstance(domain, Extension): + raise StrandError(self, 'cannot have an Extension in the middle of domains') + for domain1, domain2 in _pairwise(self.domains): if isinstance(domain1, Loopout) and isinstance(domain2, Loopout): raise StrandError(self, 'cannot have two consecutive Loopouts in a strand')
UC-Davis-molecular-computing/scadnano-python-package
f415a4773feb665d556dbb709eba67058f8e6ea1
diff --git a/tests/scadnano_tests.py b/tests/scadnano_tests.py index 62c0472..61350cc 100644 --- a/tests/scadnano_tests.py +++ b/tests/scadnano_tests.py @@ -1309,6 +1309,37 @@ col major top-left domain start: ABCDEFLHJGIKMNOPQR os.remove(filename) + def test_export_dna_sequences_extension_5p(self) -> None: + design = sc.Design(helices=[sc.Helix(max_offset=100)]) + design.draw_strand(0, 0) \ + .extension_5p(3) \ + .move(5) \ + .with_sequence('TTT' + 'AAAAA') \ + .with_name('strand') + contents = design.to_idt_bulk_input_format() + self.assertEqual('strand,TTTAAAAA,25nm,STD', contents) + + def test_export_dna_sequences_extension_3p(self) -> None: + design = sc.Design(helices=[sc.Helix(max_offset=100)]) + design.draw_strand(0, 0) \ + .move(5) \ + .extension_3p(3) \ + .with_sequence('AAAAA' + 'TTT') \ + .with_name('strand') + contents = design.to_idt_bulk_input_format() + self.assertEqual('strand,AAAAATTT,25nm,STD', contents) + + def test_export_dna_sequences_loopout(self) -> None: + design = sc.Design(helices=[sc.Helix(max_offset=100), sc.Helix(max_offset=100)]) + design.draw_strand(0, 0) \ + .move(5) \ + .loopout(1, 3) \ + .move(-5) \ + .with_sequence('AAAAA' + 'TTT' + 'AAAAA') \ + .with_name('strand') + contents = design.to_idt_bulk_input_format() + self.assertEqual('strand,AAAAATTTAAAAA,25nm,STD', contents) + class TestExportCadnanoV2(unittest.TestCase): """
export DNA sequences from extensions and loopouts This code crashes: ```python design = sc.Design(helices=[sc.Helix(max_offset=100)]) design.draw_strand(0, 0).extension_5p(3).move(5).with_sequence('TTT' + 'AAAAA') contents = design.to_idt_bulk_input_format() ``` with this exception: ``` ..\scadnano\scadnano.py:7369: in to_idt_bulk_input_format [strand.vendor_export_name(), strand.vendor_dna_sequence(domain_delimiter=domain_delimiter), _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = Strand(domains=[Extension(num_bases=3, display_length=1.0, display_angle=35.0, label=None, name=None, dna_sequence='TT...ields=None, is_scaffold=False, modification_5p=None, modification_3p=None, modifications_int={}, name=None, label=None) domain_delimiter = '' def vendor_dna_sequence(self, domain_delimiter: str = '') -> str: """ :param domain_delimiter: string to put in between DNA sequences of each domain, and between 5'/3' modifications and DNA. Note that the delimiter is not put between internal modifications and the next base(s) in the same domain. :return: DNA sequence as it needs to be typed to order from a DNA synthesis vendor, with :py:data:`Modification5Prime`'s, :py:data:`Modification3Prime`'s, and :py:data:`ModificationInternal`'s represented with text codes, e.g., for IDT DNA, using "/5Biosg/ACGT" for sequence ACGT with a 5' biotin modification. """ self._ensure_modifications_legal(check_offsets_legal=True) if self.dna_sequence is None: raise ValueError('DNA sequence has not been assigned yet') ret_list: List[str] = [] if self.modification_5p is not None and self.modification_5p.vendor_code is not None: ret_list.append(self.modification_5p.vendor_code) for substrand in self.domains: > ret_list.append(substrand.vendor_dna_sequence()) E AttributeError: 'Extension' object has no attribute 'vendor_dna_sequence' ..\scadnano\scadnano.py:4362: AttributeError ``` This code also crashes: ```python design = sc.Design(helices=[sc.Helix(max_offset=100), sc.Helix(max_offset=100)]) design.draw_strand(0, 0).move(5).loopout(1, 3).move(-5).with_sequence('AAAAA' + 'TTT' + 'AAAAA') contents = design.to_idt_bulk_input_format() ``` It's not happening in the web interface, yay strongly typed languages.
0.0
f415a4773feb665d556dbb709eba67058f8e6ea1
[ "tests/scadnano_tests.py::TestExportDNASequences::test_export_dna_sequences_extension_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_export_dna_sequences_extension_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_export_dna_sequences_loopout" ]
[ "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__0_0_to_10_cross_1_to_5__reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__5p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__as_circular_with_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_then_update_to_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_decrease_increase_reverse", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_increase_decrease_forward", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__call_update_to_twice_legally", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__cross_after_5p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_after_loopout_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_on_circular_strand_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_3p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_5p_with_label", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__extension_with_name", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__h0_off0_to_off10_cross_h1_to_off5_loopout_length3_h2_to_off15", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__loopouts_with_labels_and_colors_to_json", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__move_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_other_order", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__multiple_strands_overlap_no_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_forward_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__two_reverse_paranemic_crossovers", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_3p_extension_should_raise_error", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__update_to_after_5p_extension_ok", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_domain_sequence_on_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_relative_offset", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_3p_extension", "tests/scadnano_tests.py::TestCreateStrandChainedMethods::test_strand__with_sequence_on_5p_extension", "tests/scadnano_tests.py::TestCreateHelix::test_helix_constructor_no_max_offset_with_major_ticks", "tests/scadnano_tests.py::TestM13::test_p7249", "tests/scadnano_tests.py::TestM13::test_p7560", "tests/scadnano_tests.py::TestM13::test_p8064", "tests/scadnano_tests.py::TestModifications::test_Cy3", "tests/scadnano_tests.py::TestModifications::test_biotin", "tests/scadnano_tests.py::TestModifications::test_mod_illegal_exceptions_raised", "tests/scadnano_tests.py::TestModifications::test_to_json__names_not_unique_for_modifications_5p_raises_error", "tests/scadnano_tests.py::TestModifications::test_to_json__names_unique_for_modifications_raises_no_error", "tests/scadnano_tests.py::TestModifications::test_to_json_serializable", "tests/scadnano_tests.py::TestImportCadnanoV2::test_2_stape_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestImportCadnanoV2::test_32_helix_rectangle", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Nature09_monolith", "tests/scadnano_tests.py::TestImportCadnanoV2::test_Science09_prot120_98_v3", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple", "tests/scadnano_tests.py::TestImportCadnanoV2::test_circular_auto_staple_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order", "tests/scadnano_tests.py::TestImportCadnanoV2::test_helices_order2", "tests/scadnano_tests.py::TestImportCadnanoV2::test_huge_hex", "tests/scadnano_tests.py::TestImportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestImportCadnanoV2::test_same_helix_crossover", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters_internal_nonbase_modifications", "tests/scadnano_tests.py::TestExportDNASequences::test_domain_delimiters_modifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__col_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_purifications", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_scales", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_different_sequences", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__duplicate_names_same_sequence", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_5p_or_3p", "tests/scadnano_tests.py::TestExportDNASequences::test_to_idt_bulk_input_format__row_major_top_left_domain_start", "tests/scadnano_tests.py::TestExportDNASequences::test_write_idt_plate_excel_file", "tests/scadnano_tests.py::TestExportCadnanoV2::test_16_helix_origami_rectangle_no_twist", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_deletions_insertions", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple", "tests/scadnano_tests.py::TestExportCadnanoV2::test_2_staple_2_helix_origami_extremely_simple_2", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_bundle_honeycomb", "tests/scadnano_tests.py::TestExportCadnanoV2::test_6_helix_origami_rectangle", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples", "tests/scadnano_tests.py::TestExportCadnanoV2::test_big_circular_staples_hex", "tests/scadnano_tests.py::TestExportCadnanoV2::test_circular_strand", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_design_with_helix_group_not_same_grid", "tests/scadnano_tests.py::TestExportCadnanoV2::test_export_no_whitespace", "tests/scadnano_tests.py::TestExportCadnanoV2::test_extension", "tests/scadnano_tests.py::TestExportCadnanoV2::test_loopout", "tests/scadnano_tests.py::TestExportCadnanoV2::test_paranemic_crossover", "tests/scadnano_tests.py::TestExportCadnanoV2::test_parity_issue", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__from_and_to_file_contents", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_error_if_some_have_idx_not_others_mixed_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__helices_non_default_indices_mixed_with_default", "tests/scadnano_tests.py::TestDesignFromJson::test_from_json__three_strands", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__one_strand", "tests/scadnano_tests.py::TestStrandReversePolarity::test_reverse_all__three_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_deletion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__deletions_insertions_in_multiple_domains_two_strands", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_deletion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_left_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_on_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__one_insertion_right_of_major_tick", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_deletions", "tests/scadnano_tests.py::TestInlineInsDel::test_inline_deletions_insertions__two_insertions", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_above_range", "tests/scadnano_tests.py::TestInlineInsDel::test_insertion_below_range", "tests/scadnano_tests.py::TestInlineInsDel::test_no_deletion_after_loopout", "tests/scadnano_tests.py::TestInlineInsDel::test_no_insertion_after_loopout", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__small_design_illegal_only_one_helix_has_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_full_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__both_scaffolds_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__bottom_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__first_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__horizontal_crossovers_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__neither_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__second_scaffold_preserved", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_0", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_15", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_H0_reverse_8", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__small_design_illegal", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover__top_horizontal_crossover_already_there", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_existing_crossover_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_half_crossover_on_extension_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H0_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_forward", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_H1_reverse", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__small_design_no_nicks_added_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_add_nick_then_add_crossovers__6_helix_rectangle", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_ligate_all", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__small_nicked_design_no_ligation_yet", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate__twice_on_same_domain", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_extension_side_should_error", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_3p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_middle_domain_should_error_5p_case", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_ligate_on_non_extension_side_ok", "tests/scadnano_tests.py::TestNickLigateAndCrossover::test_nick_on_extension", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_max_offset", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_autocalculated", "tests/scadnano_tests.py::TestAutocalculatedData::test_helix_min_max_offsets_illegal_explicitly_specified", "tests/scadnano_tests.py::TestSetHelixIdx::test_set_helix_idx", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_pitch_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_roll_of_helix", "tests/scadnano_tests.py::TestDesignPitchYawRollOfHelix::test_design_yaw_of_helix", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_no_groups_but_helices_reference_groups", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_grid", "tests/scadnano_tests.py::TestHelixGroups::test_JSON_bad_uses_groups_and_top_level_helices_view_order", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_fail_nonexistent", "tests/scadnano_tests.py::TestHelixGroups::test_helix_groups_to_from_JSON", "tests/scadnano_tests.py::TestNames::test_strand_domain_names_json", "tests/scadnano_tests.py::TestNames::test_strand_names_can_be_nonunique", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_periodic_distances", "tests/scadnano_tests.py::TestJSON::test_Helix_major_tick_start_default_min_offset", "tests/scadnano_tests.py::TestJSON::test_NoIndent_on_helix_without_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_both_helix_groups_and_helices_do_not_specify_pitch_nor_yaw", "tests/scadnano_tests.py::TestJSON::test_color_specified_with_integer", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_default_order", "tests/scadnano_tests.py::TestJSON::test_default_helices_view_order_with_nondefault_helix_idxs_in_nondefault_order", "tests/scadnano_tests.py::TestJSON::test_domain_labels", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_end_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_forward_and_right_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_helix_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_domain_start_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_grid_missing", "tests/scadnano_tests.py::TestJSON::test_error_when_strands_missing", "tests/scadnano_tests.py::TestJSON::test_from_json_extension_design", "tests/scadnano_tests.py::TestJSON::test_grid_design_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_grid_helix_group_level_converted_to_enum_from_string", "tests/scadnano_tests.py::TestJSON::test_json_tristan_example_issue_32", "tests/scadnano_tests.py::TestJSON::test_lack_of_NoIndent_on_helix_if_position_or_major_ticks_present", "tests/scadnano_tests.py::TestJSON::test_legacy_dna_sequence_key", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__no_strand_name", "tests/scadnano_tests.py::TestJSON::test_legacy_idt_name_import__strand_name_exists", "tests/scadnano_tests.py::TestJSON::test_legacy_right_key", "tests/scadnano_tests.py::TestJSON::test_legacy_substrands_key", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_multiple_helix_groups_helices_specify_pitch_and_yaw_invalid", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry", "tests/scadnano_tests.py::TestJSON::test_nondefault_geometry_some_default", "tests/scadnano_tests.py::TestJSON::test_only_helix_groups_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_only_individual_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_position_specified_with_origin_keyword", "tests/scadnano_tests.py::TestJSON::test_single_helix_group_and_helices_specify_pitch_and_yaw", "tests/scadnano_tests.py::TestJSON::test_strand_idt", "tests/scadnano_tests.py::TestJSON::test_strand_labels", "tests/scadnano_tests.py::TestJSON::test_to_json__hairpin", "tests/scadnano_tests.py::TestJSON::test_to_json__roll", "tests/scadnano_tests.py::TestJSON::test_to_json_extension_design__extension", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_directly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_assign_dna__conflicting_sequences_indirectly_assigned", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_consecutive_domains_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_domains_not_none_in_Strand_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_four_legally_leapfrogging_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_just_inside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_major_tick_outside_range", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_overlapping_caught_in_strange_counterexample", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_singleton_loopout", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_offset_beyond_maxbases", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strand_references_nonexistent_helix", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_and_helices_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_strands_not_specified_in_Design_constructor", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_illegally_overlapping_strands", "tests/scadnano_tests.py::TestIllegalStructuresPrevented::test_two_nonconsecutive_illegally_overlapping_strands", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_3_helix_before_design", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_append_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_insert_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_first_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_last_domain_with_sequence", "tests/scadnano_tests.py::TestInsertRemoveDomains::test_remove_middle_domain_with_sequence", "tests/scadnano_tests.py::TestLabels::test_with_domain_label", "tests/scadnano_tests.py::TestLabels::test_with_domain_label__and__with_label", "tests/scadnano_tests.py::TestLabels::test_with_label__dict", "tests/scadnano_tests.py::TestLabels::test_with_label__str", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_3p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_add_5p_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_can_add_internal_mod_to_circular_strand", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_3p_mod", "tests/scadnano_tests.py::TestCircularStrandsLegalMods::test_cannot_make_strand_circular_if_5p_mod", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_crossover_from_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_2_domain_circular_strand_makes_it_linear_nick_second_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_first_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_last_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_add_nick_to_3_domain_circular_strand_makes_it_linear_nick_middle_domain", "tests/scadnano_tests.py::TestCircularStrandEdits::test_ligate_linear_strand_to_itself_makes_it_circular", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__illegal_overlapping_domains", "tests/scadnano_tests.py::TestAddStrand::test_add_strand__with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__2helix_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_deletions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__adapter_assigned_from_scaffold_and_tiles_with_insertions", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_from_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_seq_with_wildcards", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__assign_to_strand_multi_other_single", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_left_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_shorter_than_complementary_strand_right_strand_longer", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__dna_sequence_with_uncomplemented_domain_on_different_helix_wildcards_both_ends", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__from_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__hairpin", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_bound_strand__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_helix_with_one_bottom_strand_and_three_top_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__one_strand_assigned_by_complement_from_two_other_strands", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_other_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__other_strand_fully_defined_already_and_self_extends_beyond", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__to_strand_with_loopout", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_deletions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_bound_strands__with_insertions__complement_true", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_equal_length_strands_on_one_helix", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__two_helices_with_multiple_domain_intersections", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__upper_left_edge_staple_of_16H_origami_rectangle", "tests/scadnano_tests.py::TestAssignDNA::test_assign_dna__wildcards_simple", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__domain_sequence_too_long_error", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__to_individual_domains__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_assign_dna__wildcards_multiple_overlaps", "tests/scadnano_tests.py::TestAssignDNAToDomains::test_method_chaining_with_domain_sequence", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_deletions_and_insertions", "tests/scadnano_tests.py::TestSubstrandDNASequenceIn::test_dna_sequence_in__right_then_left_insertions", "tests/scadnano_tests.py::TestOxviewExport::test_bp", "tests/scadnano_tests.py::TestOxviewExport::test_export", "tests/scadnano_tests.py::TestOxviewExport::test_export_file", "tests/scadnano_tests.py::TestOxdnaExport::test_basic_design", "tests/scadnano_tests.py::TestOxdnaExport::test_deletion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_file_output", "tests/scadnano_tests.py::TestOxdnaExport::test_helix_groups", "tests/scadnano_tests.py::TestOxdnaExport::test_honeycomb_design", "tests/scadnano_tests.py::TestOxdnaExport::test_insertion_design", "tests/scadnano_tests.py::TestOxdnaExport::test_loopout_design", "tests/scadnano_tests.py::TestPlateMaps::test_plate_map_markdown", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_angle_key_contains_non_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__display_length_key_contains_non_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__extension_key_contains_num_bases", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__label_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__name_key_contains_non_default_name", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_angle_key_when_default_display_angle", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_display_length_key_when_default_display_length", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_label_key_when_default_label", "tests/scadnano_tests.py::TestExtension::test_to_json_serializable__no_name_key_when_default_name", "tests/scadnano_tests.py::TestBasePairs::test_base_pairs_on_forward_strand_ahead_of_reverse_strand", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_deletions_insertions_mismatch_in_insertion", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_dna_on_some_strands_and_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_dna", "tests/scadnano_tests.py::TestBasePairs::test_design_base_pairs_no_mismatches", "tests/scadnano_tests.py::TestBasePairs::test_find_overlapping_domains", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_forward_strand", "tests/scadnano_tests.py::TestBasePairs::test_no_base_pairs_only_reverse_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_2_crossovers_call_relax_twice", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_3_crossover_and_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_2_helix_no_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_2_crossovers_1_loopout_crossovers_method", "tests/scadnano_tests.py::TestHelixRollRelax::test_3_helix_6_crossover", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_0_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_20", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_10_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_0_45_90", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_10_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_1_359", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_30_350", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_50", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_330_40_80", "tests/scadnano_tests.py::TestHelixRollRelax::test_average_angle_350_0_40", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_allow_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intergroup_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_2_helix_disallow_intrahelix_crossovers", "tests/scadnano_tests.py::TestHelixRollRelax::test_helix_crossover_addresses_3_helix_3_strand", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_20_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_50_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_0_10_80_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_174_179_184_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_179_181_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_181_183_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_10_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_0_40_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0", "tests/scadnano_tests.py::TestHelixRollRelax::test_minimum_strain_angle_350_10_60_relative_to_0_and_20_0_310_relative_to_10" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-20 01:24:41+00:00
mit
804
UCL__cathpy-17
diff --git a/.vscode/settings.json b/.vscode/settings.json index 6bc562d..65a02e9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,4 @@ { - "python.pythonPath": "${workspaceFolder}/venv/bin/python", + "python.pythonPath": "${workspaceFolder}/venv/bin/python3", "editor.formatOnSave": true } \ No newline at end of file diff --git a/cathpy/core/align.py b/cathpy/core/align.py index 3131c26..08fd3c7 100644 --- a/cathpy/core/align.py +++ b/cathpy/core/align.py @@ -93,24 +93,24 @@ class Sequence(object): LOG.warning("Explicitly changed the segment start/stop from strings to numbers " "when retrieving residues. Consider specifying the option 'parse_segments_as_numbers'") else: - segs=[NumericSegment(1, len(self.seq_no_gaps))] + segs = [NumericSegment(1, len(self.seq_no_gaps))] - current_seg_offset=0 + current_seg_offset = 0 def next_seg(): nonlocal current_seg_offset if current_seg_offset < len(segs): - seg=segs[current_seg_offset] + seg = segs[current_seg_offset] current_seg_offset += 1 return seg else: return None # theoretical length according to segment info vs length according to sequence - seg_length=0 + seg_length = 0 for seg in segs: seg_length += seg.stop - seg.start + 1 - actual_length=len(self.seq_no_gaps) + actual_length = len(self.seq_no_gaps) if seg_length != actual_length: # should this be a warning? (with 1-n numbering as fallback?) @@ -177,7 +177,7 @@ class Sequence(object): """Returns sequence position (ignoring gaps) of the given residue (may include gaps).""" seq_to_offset = self.seq[:offset+1] - if re.match(seq_to_offset[-1], Sequence.re_gap_chars): + if re.match(Sequence.re_gap_chars, seq_to_offset[-1]): raise err.GapError( "Cannot get sequence position at offset {} since this corresponds to a gap".format( offset)) @@ -327,12 +327,12 @@ class Sequence(object): # features if meta_str: meta_parts = meta_str.split() - for f in meta_parts.split('=', maxsplit=1): - if len(f) == 2: - meta[f[0]] = f[1] + for key_index, kv in enumerate(meta_parts): + if '=' in kv: + _key, _value = kv.split('=', maxsplit=1) + meta[_key] = _value else: - LOG.warning( - "failed to parse meta feature from string %s", meta_str) + meta[key_index] = kv return({'accession': accession, 'id': id_with_segs_str, @@ -438,7 +438,7 @@ class Sequence(object): def seginfo(self): """Returns the segment info for this Sequence.""" segs_str = '_'.join(['-'.join([str(s.start), str(s.stop)]) - for s in self.segs]) + for s in self.segs]) return segs_str def apply_segments(self, segs): @@ -460,7 +460,7 @@ class Sequence(object): acc = self.accession startstops = [(seg[0], seg[1]) for seg in segs] seq_range = '_'.join(['{}-{}'.format(ss[0], ss[1]) - for ss in startstops]) + for ss in startstops]) seq_parts = [seq[ss[0]-1:ss[1]] for ss in startstops] subseq = Sequence(hdr="{}/{}".format(acc, seq_range),
UCL/cathpy
74820f35bf9c41c256ce9b6ab838e24d3300ca99
diff --git a/tests/align_test.py b/tests/align_test.py index 4edd457..fea0551 100644 --- a/tests/align_test.py +++ b/tests/align_test.py @@ -6,6 +6,8 @@ import unittest from cathpy.core.align import ( Align, Correspondence, Residue, SegmentBase, NumericSegment, StringSegment, Sequence,) +from cathpy.core.error import GapError, OutOfBoundsError, SeqIOError + from . import testutils LOG = logging.getLogger(__name__) @@ -401,6 +403,50 @@ ghCHC-fsAK-HP-PK-A----AHG--P--GPa self.assertEqual(meta_info.dops_score, 61.529) self.assertEqual(meta_info.organism_newick, "((((((((((((((Homo,(Gorilla_gorilla)'Gorilla Gorilla gorilla (1)',Pan)'Homininae Homo (5)',(Pongo)'Ponginae Pongo (1)')'Hominidae Homininae (6)')'Hominoidea Hominidae (6)',(((Chlorocebus,Macaca,Papio)'Cercopithecinae Chlorocebus (3)')'Cercopithecidae Cercopithecinae (3)')'Cercopithecoidea Cercopithecidae (3)')'Catarrhini Hominoidea (9)')'Simiiformes Catarrhini (9)')'Haplorrhini Simiiformes (9)')'Primates Haplorrhini (9)',(((((Mus)'Mus Mus (1)',Rattus)'Murinae Mus (2)')'Muridae Murinae (2)')'Myomorpha Muridae (2)',((Heterocephalus,Fukomys)'Bathyergidae Heterocephalus (2)')'Hystricomorpha Bathyergidae (2)')'Rodentia Myomorpha (4)',((Oryctolagus)'Leporidae Oryctolagus (1)')'Lagomorpha Leporidae (1)')'Euarchontoglires Primates (14)',(((((Bos)'Bovinae Bos (1)')'Bovidae Bovinae (1)')'Pecora Bovidae (1)')'Ruminantia Pecora (1)',((Camelus)'Camelidae Camelus (1)')'Tylopoda Camelidae (1)',((((Pteropus)'Pteropodinae Pteropus (1)')'Pteropodidae Pteropodinae (1)')'Megachiroptera Pteropodidae (1)',((Myotis)'Vespertilionidae Myotis (1)')'Microchiroptera Vespertilionidae (1)')'Chiroptera Megachiroptera (2)',((((Felis)'Felinae Felis (1)')'Felidae Felinae (1)')'Feliformia Felidae (1)',(((Canis_lupus)'Canis Canis lupus (1)')'Canidae Canis (1)',(((Mustela_putorius)'Mustela Mustela putorius (1)')'Mustelinae Mustela (1)')'Mustelidae Mustelinae (1)')'Caniformia Canidae (2)')'Carnivora Feliformia (3)',(((Equus)'Equus Equus (2)')'Equidae Equus (2)')'Perissodactyla Equidae (2)')'Laurasiatheria Ruminantia (9)',(((Loxodonta)'Elephantidae Loxodonta (1)')'Proboscidea Elephantidae (1)')'Afrotheria Proboscidea (1)')'Mammalia Euarchontoglires (24)',(((((((Silurana)'Xenopus Silurana (4)')'Xenopodinae Xenopus (4)',(Hymenochirus)'Pipinae Hymenochirus (1)')'Pipidae Xenopodinae (5)')'Pipoidea Pipidae (5)')'Anura Pipoidea (5)')'Batrachia Anura (5)')'Amphibia Batrachia (5)',((((((Ophiophagus)'Elapinae Ophiophagus (1)')'Elapidae Elapinae (1)')'Colubroidea Elapidae (1)')'Serpentes Colubroidea (1)')'Squamata Serpentes (1)')'Lepidosauria Squamata (1)',(((((((((Poeciliopsis,Xiphophorus,Poecilia)'Poeciliinae Poeciliopsis (4)')'Poeciliidae Poeciliinae (4)',(Fundulus)'Fundulidae Fundulus (1)')'Cyprinodontoidei Poeciliidae (5)')'Cyprinodontiformes Cyprinodontoidei (5)',((((Oryzias)'Oryziinae Oryzias (1)')'Adrianichthyidae Oryziinae (1)')'Adrianichthyoidei Adrianichthyidae (1)')'Beloniformes Adrianichthyoidei (1)')'Atherinomorphae Cyprinodontiformes (6)',((((Astyanax)'Characidae Astyanax (1)')'Characoidei Characidae (1)')'Characiformes Characoidei (1)')'Characiphysae Characiformes (1)',((((Gasterosteus)'Gasterosteidae Gasterosteus (1)')'Gasterosteales Gasterosteidae (1)')'Cottioidei Gasterosteales (1)')'Perciformes Cottioidei (1)',((((Takifugu)'Tetraodontidae Takifugu (1)')'Tetradontoidea Tetraodontidae (1)')'Tetraodontoidei Tetradontoidea (1)')'Tetraodontiformes Tetraodontoidei (1)',((((Danio)'Cyprinidae Danio (2)')'Cyprinoidea Cyprinidae (2)')'Cypriniformes Cyprinoidea (2)')'Cypriniphysae Cypriniformes (2)',(((((Oreochromis)'Oreochromini Oreochromis (1)')'Pseudocrenilabrinae Oreochromini (1)')'Cichlidae Pseudocrenilabrinae (1)')'Cichliformes Cichlidae (1)')'Cichlomorphae Cichliformes (1)',(((Oncorhynchus)'Salmoninae Oncorhynchus (1)')'Salmonidae Salmoninae (1)')'Salmoniformes Salmonidae (1)')'Teleostei Atherinomorphae (13)',(((Lepisosteus)'Lepisosteidae Lepisosteus (1)')'Semionotiformes Lepisosteidae (1)')'Holostei Semionotiformes (1)')'Neopterygii Teleostei (14)')'Actinopteri Neopterygii (14)')'Actinopterygii Actinopteri (14)',(((((Gallus)'Phasianinae Gallus (1)')'Phasianidae Phasianinae (1)')'Galliformes Phasianidae (1)',((Picoides)'Picidae Picoides (1)')'Piciformes Picidae (1)',((((Taeniopygia)'Estrildinae Taeniopygia (1)')'Estrildidae Estrildinae (1)')'Passeroidea Estrildidae (1)',(Ficedula)'Muscicapidae Ficedula (1)')'Passeriformes Passeroidea (2)')'Neognathae Galliformes (4)')'Aves Neognathae (4)',((((Callorhinchus)'Callorhinchidae Callorhinchus (1)')'Chimaeriformes Callorhinchidae (1)')'Holocephali Chimaeriformes (1)')'Chondrichthyes Holocephali (1)',((Latimeria)'Coelacanthidae Latimeria (1)')'Coelacanthiformes Coelacanthidae (1)',(((Alligator)'Alligatorinae Alligator (1)')'Alligatoridae Alligatorinae (1)')'Crocodylia Alligatoridae (1)')'Craniata Mammalia (51)')'Chordata Craniata (51)')'Metazoa Chordata (51)')'Eukaryota Metazoa (51)')'ROOT (51)';") + def test_fasta_with_meta(self): + fasta_str = """ +>seq1 bla1 bla2 +TTTTLLASAMLSASVFALTDPPVDPVDPVDPTDPPSSD +>seq2 key1=value1 key2=value2 +TTTTLLASAMLSASVFALTDPPVDPVDPVDPTDPPSSD +""".strip() + + aln = Align.from_fasta(fasta_str) + seq1 = aln.get_seq_at_offset(0) + seq2 = aln.get_seq_at_offset(1) + self.assertEqual(seq1.accession, 'seq1') + self.assertEqual(seq2.accession, 'seq2') + + self.assertEqual(seq1.meta, {0: 'bla1', 1: 'bla2'}) + self.assertEqual(seq2.meta, {'key1': 'value1', 'key2': 'value2'}) + + def test_incorrect_fasta_headers(self): + fasta_str = """ +>seq1/100-200 +TTTTL-LASAM +""".strip() + aln = Align.from_fasta(fasta_str) + seq = aln.get_seq_at_offset(0) + with self.assertRaises(OutOfBoundsError): + residues = seq.get_residues() + + def test_sequence_errors(self): + seq = Sequence('seq1', '-TTTTL-LASAM') + self.assertEqual(seq.get_res_at_offset(0), '-') + self.assertEqual(seq.get_res_at_offset(1), 'T') + self.assertEqual(seq.get_res_at_offset(11), 'M') + self.assertEqual(seq.get_res_at_offset(-3), 'S') + + with self.assertRaises(SeqIOError): + seq.get_res_at_offset(12) + + with self.assertRaises(SeqIOError): + seq.get_res_at_seq_position(11) + + self.assertEqual(seq.get_seq_position_at_offset(2), 2) + with self.assertRaises(GapError): + seq.get_seq_position_at_offset(6) + if __name__ == '__main__': unittest.main()
Header parsing problems when whitespace in Fasta header cath-align-scorecons crashes when there is a space in the header line. The fasta file ``` >seq1 bla TTTTLLASAMLSASVFALTDPPVDPVDPVDPTDPPSSD >seq2 bla TTTTLLASAMLSASVFALTDPPVDPVDPVDPTDPPSSD ``` produces the following output (when I remove the space in the headers it works normally) ``` Traceback (most recent call last): File "/home/clemens/miniconda3/lib/python3.7/site-packages/cathpy/core/align.py", line 32, in __init__ hdr_info = Sequence.split_hdr(hdr) File "/home/clemens/miniconda3/lib/python3.7/site-packages/cathpy/core/align.py", line 283, in split_hdr for f in meta_parts.split('=', maxsplit=1): AttributeError: 'list' object has no attribute 'split' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/clemens/miniconda3/bin/cath-align-scorecons", line 45, in <module> aln = Align.from_fasta(args.in_file) File "/home/clemens/miniconda3/lib/python3.7/site-packages/cathpy/core/align.py", line 889, in from_fasta aln.read_sequences_from_fasta(fasta_io) File "/home/clemens/miniconda3/lib/python3.7/site-packages/cathpy/core/align.py", line 1062, in read_sequences_from_fasta seq = Sequence(current_hdr, current_seq) File "/home/clemens/miniconda3/lib/python3.7/site-packages/cathpy/core/align.py", line 34, in __init__ raise err.GeneralError('caught error while parsing sequence header: '+hdr) ```
0.0
74820f35bf9c41c256ce9b6ab838e24d3300ca99
[ "tests/align_test.py::TestAlign::test_fasta_with_meta", "tests/align_test.py::TestAlign::test_sequence_errors" ]
[ "tests/align_test.py::TestSequence::test_apply_segments", "tests/align_test.py::TestSequence::test_create_segment", "tests/align_test.py::TestSequence::test_create_sequence", "tests/align_test.py::TestSequence::test_pdb_coords_hdr", "tests/align_test.py::TestSequence::test_pdb_numeric_coords_hdr", "tests/align_test.py::TestSequence::test_pdb_numeric_coords_hdr_fails", "tests/align_test.py::TestSequence::test_sequence_lower_case", "tests/align_test.py::TestSequence::test_sequence_methods", "tests/align_test.py::TestSequence::test_split_hdr", "tests/align_test.py::TestCorrespondence::test_synopsis", "tests/align_test.py::TestAlign::test_aln_add_gap", "tests/align_test.py::TestAlign::test_copy_aln", "tests/align_test.py::TestAlign::test_incorrect_fasta_headers", "tests/align_test.py::TestAlign::test_meta_summary", "tests/align_test.py::TestAlign::test_parse_pfam_stockholm", "tests/align_test.py::TestAlign::test_pir", "tests/align_test.py::TestAlign::test_read_fasta_fileio", "tests/align_test.py::TestAlign::test_read_fasta_filename", "tests/align_test.py::TestAlign::test_read_fasta_str", "tests/align_test.py::TestAlign::test_read_stockholm_file", "tests/align_test.py::TestAlign::test_read_stockholm_gzip_file", "tests/align_test.py::TestAlign::test_remove_gaps", "tests/align_test.py::TestAlign::test_write_sto" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-06-08 21:44:05+00:00
mit
805
UCREL__pymusas-22
diff --git a/CHANGELOG.md b/CHANGELOG.md index 58fd475..e1587d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- A mapping from the [Penn Chinese Treebank POS tagset](https://verbs.colorado.edu/chinese/posguide.3rd.ch.pdf) to USAS core POS tagset. +- In the documentation it clarifies that we used the [Universal Dependencies Treebank](https://universaldependencies.org/u/pos/) version of the UPOS tagset rather than the original version from the [paper by Petrov et al. 2012](http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf). +- The usage documentation, for the "How-to Tag Text", has been updated so that the Chinese example includes using POS information. - A `CHANGELOG` file has been added. The format of the `CHANGELOG` file will now be used for the formats of all current and future GitHub release notes. For more information on the `CHANGELOG` file format see [Keep a Changelog.](https://keepachangelog.com/en/1.0.0/) ## [v0.1.0](https://github.com/UCREL/pymusas/releases/tag/v0.1.0) - 2021-12-07 diff --git a/docs/docs/api/pos_mapper.md b/docs/docs/api/pos_mapper.md index aba9877..bc75852 100644 --- a/docs/docs/api/pos_mapper.md +++ b/docs/docs/api/pos_mapper.md @@ -10,9 +10,18 @@ - __UPOS\_TO\_USAS\_CORE__ : `Dict[str, List[str]]` <br/> - A mapping from the [Universal Part Of Speech (UPOS) tagset](http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf) - to the USAS core tagset. UPOS is used by the - [Universal Dependencies Tree Bank.](https://universaldependencies.org/u/pos/) + A mapping from the Universal Part Of Speech (UPOS) tagset to the USAS core tagset. The UPOS tagset used + here is the same as that used by the [Universal Dependencies Treebank project](https://universaldependencies.org/u/pos/). + This is slightly different to the original presented in the + [paper by Petrov et al. 2012](http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf), + for this original tagset see the following [GitHub repository](https://github.com/slavpetrov/universal-pos-tags). + +- __PENN\_CHINESE\_TREEBANK\_TO\_USAS\_CORE__ : `Dict[str, List[str]]` <br/> + A mapping from the [Penn Chinese Treebank tagset](https://verbs.colorado.edu/chinese/posguide.3rd.ch.pdf) + to the USAS core tagset. The Penn Chinese Treebank tagset here is slightly different to the original + as it contains three extra tags, `X`, `URL`, and `INF`, that appear to be unique to + the [spaCy Chinese models](https://spacy.io/models/zh). For more information on how this mapping was + created, see the following [GitHub issue](https://github.com/UCREL/pymusas/issues/19). <a id="pymusas.pos_mapper.UPOS_TO_USAS_CORE"></a> @@ -27,6 +36,19 @@ UPOS_TO_USAS_CORE: Dict[str, List[str]] = { 'CCONJ': ['c ... ``` +<a id="pymusas.pos_mapper.PENN_CHINESE_TREEBANK_TO_USAS_CORE"></a> + +#### PENN\_CHINESE\_TREEBANK\_TO\_USAS\_CORE + +```python +PENN_CHINESE_TREEBANK_TO_USAS_CORE: Dict[str, List[str]] = { + 'AS': ['part'], + 'DEC': ['part'], + 'DEG': ['part'], + 'DER': ['part'], + 'DEV': ['pa ... +``` + <a id="pymusas.pos_mapper.upos_to_usas_core"></a> ### upos\_to\_usas\_core diff --git a/docs/docs/usage/how_to/tag_text.md b/docs/docs/usage/how_to/tag_text.md index 56e26fc..3ea9d71 100644 --- a/docs/docs/usage/how_to/tag_text.md +++ b/docs/docs/usage/how_to/tag_text.md @@ -18,7 +18,7 @@ python -m spacy download zh_core_web_sm Then create the tagger, in a Python script: :::note -Currently there is not lemmatisation component in the spaCy pipeline for Chinese. +Currently there is no lemmatisation component in the spaCy pipeline for Chinese. ::: ``` python diff --git a/pymusas/pos_mapper.py b/pymusas/pos_mapper.py index 686a019..e52ad60 100644 --- a/pymusas/pos_mapper.py +++ b/pymusas/pos_mapper.py @@ -2,10 +2,18 @@ # Attributes UPOS_TO_USAS_CORE: `Dict[str, List[str]]` - A mapping from the [Universal Part Of Speech (UPOS) tagset](http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf) - to the USAS core tagset. UPOS is used by the - [Universal Dependencies Tree Bank.](https://universaldependencies.org/u/pos/) + A mapping from the Universal Part Of Speech (UPOS) tagset to the USAS core tagset. The UPOS tagset used + here is the same as that used by the [Universal Dependencies Treebank project](https://universaldependencies.org/u/pos/). + This is slightly different to the original presented in the + [paper by Petrov et al. 2012](http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf), + for this original tagset see the following [GitHub repository](https://github.com/slavpetrov/universal-pos-tags). +PENN_CHINESE_TREEBANK_TO_USAS_CORE: `Dict[str, List[str]]` + A mapping from the [Penn Chinese Treebank tagset](https://verbs.colorado.edu/chinese/posguide.3rd.ch.pdf) + to the USAS core tagset. The Penn Chinese Treebank tagset here is slightly different to the original + as it contains three extra tags, `X`, `URL`, and `INF`, that appear to be unique to + the [spaCy Chinese models](https://spacy.io/models/zh). For more information on how this mapping was + created, see the following [GitHub issue](https://github.com/UCREL/pymusas/issues/19). ''' from typing import Dict, List @@ -30,6 +38,45 @@ UPOS_TO_USAS_CORE: Dict[str, List[str]] = { 'X': ['fw', 'xx'] } +PENN_CHINESE_TREEBANK_TO_USAS_CORE: Dict[str, List[str]] = { + 'AS': ['part'], + 'DEC': ['part'], + 'DEG': ['part'], + 'DER': ['part'], + 'DEV': ['part'], + 'ETC': ['part'], + 'LC': ['part'], + 'MSP': ['part'], + 'SP': ['part'], + 'BA': ['fw', 'xx'], + 'FW': ['fw', 'xx'], + 'IJ': ['intj'], + 'LB': ['fw', 'xx'], + 'ON': ['fw', 'xx'], + 'SB': ['fw', 'xx'], + 'X': ['fw', 'xx'], + 'URL': ['fw', 'xx'], + 'INF': ['fw', 'xx'], + 'NN': ['noun'], + 'NR': ['pnoun'], + 'NT': ['noun'], + 'VA': ['verb'], + 'VC': ['verb'], + 'VE': ['verb'], + 'VV': ['verb'], + 'CD': ['num'], + 'M': ['num'], + 'OD': ['num'], + 'DT': ['det', 'art'], + 'CC': ['conj'], + 'CS': ['conj'], + 'AD': ['adv'], + 'JJ': ['adj'], + 'P': ['prep'], + 'PN': ['pron'], + 'PU': ['punc'] +} + def upos_to_usas_core(upos_tag: str) -> List[str]: '''
UCREL/pymusas
834473086bb588498ab03870eb497a03caa868d5
diff --git a/tests/test_pos_mapper.py b/tests/test_pos_mapper.py index c7a6e5a..9110a53 100644 --- a/tests/test_pos_mapper.py +++ b/tests/test_pos_mapper.py @@ -1,4 +1,4 @@ -from pymusas.pos_mapper import upos_to_usas_core +from pymusas.pos_mapper import PENN_CHINESE_TREEBANK_TO_USAS_CORE, upos_to_usas_core def test_upos_to_usas_core() -> None: @@ -14,3 +14,47 @@ def test_upos_to_usas_core() -> None: assert usas_tags != [] for usas_tag in usas_tags: assert usas_tag.lower() == usas_tag + + +def test_penn_chinese_to_usas_core() -> None: + assert len(PENN_CHINESE_TREEBANK_TO_USAS_CORE) == 36 + penn_chinese_treebank_mapping = {'VA': ['verb'], + 'VC': ['verb'], + 'VE': ['verb'], + 'VV': ['verb'], + 'NR': ['pnoun'], + 'NT': ['noun'], + 'NN': ['noun'], + 'LC': ['part'], + 'PN': ['pron'], + 'DT': ['det', 'art'], + 'CD': ['num'], + 'OD': ['num'], + 'M': ['num'], + 'AD': ['adv'], + 'P': ['prep'], + 'CC': ['conj'], + 'CS': ['conj'], + 'DEC': ['part'], + 'DEG': ['part'], + 'DER': ['part'], + 'DEV': ['part'], + 'SP': ['part'], + 'AS': ['part'], + 'ETC': ['part'], + 'MSP': ['part'], + 'IJ': ['intj'], + 'ON': ['fw', 'xx'], + 'PU': ['punc'], + 'JJ': ['adj'], + 'FW': ['fw', 'xx'], + 'LB': ['fw', 'xx'], + 'SB': ['fw', 'xx'], + 'BA': ['fw', 'xx'], + 'INF': ['fw', 'xx'], + 'URL': ['fw', 'xx'], + 'X': ['fw', 'xx']} + assert 36 == len(penn_chinese_treebank_mapping) + + for chinese_penn_tag, usas_core_tag in PENN_CHINESE_TREEBANK_TO_USAS_CORE.items(): + assert penn_chinese_treebank_mapping[chinese_penn_tag] == usas_core_tag
Chinese Penn Treebank POS tagset mapping The [Chinese spaCy model](https://spacy.io/models/zh) outputs POS tags that come from the Chinese treebank tagset rather than the Universal POS tagset. This therefore requires a mapping from the Chinese treebank tagset to the USAS core tagset to be able to use the POS tagger within the Chinese spaCy model for the [USASRuleBasedTagger](https://ucrel.github.io/pymusas/api/spacy_api/taggers/rule_based) if we would like to make the most of the POS information within the [Chinese USAS lexicon.](https://raw.githubusercontent.com/UCREL/Multilingual-USAS/master/Chinese/semantic_lexicon_chi.tsv) A solution to this is to take the mapping from the Universal POS (UPOS) tagset for mapping between the Chinese treebank tagset to the UPOS tagset, of which the mapping can be found [here](https://github.com/slavpetrov/universal-pos-tags/blob/master/zh-ctb6.map) and swap the UPOS tags in that mapping to USAS core tagsets using the mapping we have current for [UPOS to USAS core](https://github.com/UCREL/pymusas/blob/main/pymusas/pos_mapper.py#L13).
0.0
834473086bb588498ab03870eb497a03caa868d5
[ "tests/test_pos_mapper.py::test_upos_to_usas_core", "tests/test_pos_mapper.py::test_penn_chinese_to_usas_core" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-08 11:34:22+00:00
apache-2.0
806
UCSBarchlab__PyRTL-365
diff --git a/pyrtl/visualization.py b/pyrtl/visualization.py index 3514091..ab9bc33 100644 --- a/pyrtl/visualization.py +++ b/pyrtl/visualization.py @@ -6,8 +6,9 @@ The functions provided write the block as a given visual format to the file. """ from __future__ import print_function, unicode_literals +import collections -from .pyrtlexceptions import PyrtlError +from .pyrtlexceptions import PyrtlError, PyrtlInternalError from .core import working_block, LogicNet from .wire import WireVector, Input, Output, Const, Register @@ -298,7 +299,8 @@ def graphviz_detailed_namer( return namer -def output_to_graphviz(file, block=None, namer=_graphviz_default_namer, split_state=True): +def output_to_graphviz(file, block=None, namer=_graphviz_default_namer, + split_state=True, maintain_arg_order=False): """ Walk the block and output it in Graphviz format to the open file. :param file: Open file to write to @@ -306,11 +308,15 @@ def output_to_graphviz(file, block=None, namer=_graphviz_default_namer, split_st :param namer: Function used to label each edge and node; see 'block_to_graphviz_string' for more information. :param split_state: If True, visually split the connections to/from a register update net. + :param maintain_arg_order: If True, will add ordering constraints so that that incoming edges + are ordered left-to-right for nets where argument order matters (e.g. '<'). Keeping this + as False results in a cleaner, though less visually precise, graphical output. """ - print(block_to_graphviz_string(block, namer, split_state), file=file) + print(block_to_graphviz_string(block, namer, split_state, maintain_arg_order), file=file) -def block_to_graphviz_string(block=None, namer=_graphviz_default_namer, split_state=True): +def block_to_graphviz_string(block=None, namer=_graphviz_default_namer, + split_state=True, maintain_arg_order=False): """ Return a Graphviz string for the block. :param namer: A function mapping graph objects (wires/logic nets) to labels. @@ -320,6 +326,9 @@ def block_to_graphviz_string(block=None, namer=_graphviz_default_namer, split_st means that registers will be appear as source nodes of the network, and 'r' nets (i.e. the logic for setting a register's next value) will be treated as sink nodes of the network. + :param maintain_arg_order: If True, will add ordering constraints so that that incoming edges + are ordered left-to-right for nets where argument order matters (e.g. '<'). Keeping this + as False results in a cleaner, though less visually precise, graphical output. The normal namer function will label user-named wires with their names and label the nodes (logic nets or Input/Output/Const terminals) with their operator symbol or name/value, @@ -371,6 +380,7 @@ digraph g { node_index_map[node] = index # print the list of edges + srcs = collections.defaultdict(list) for _from in sorted(graph.keys(), key=_node_sort_key): for _to in sorted(graph[_from].keys(), key=_node_sort_key): from_index = node_index_map[_from] @@ -379,6 +389,33 @@ digraph g { is_to_splitmerge = True if hasattr(_to, 'op') and _to.op in 'cs' else False label = namer(edge, True, is_to_splitmerge, False) rstring += ' n%d -> n%d %s;\n' % (from_index, to_index, label) + srcs[_to].append((_from, edge)) + + # Maintain left-to-right order of incoming wires for nets where order matters. + # This won't be visually perfect sometimes (especially for a wire used twice + # in a net's argument list), but for the majority of cases this will improve + # the visualization. + def index_of(w, args): + # Special helper so we compare id rather than using builtin operators + ix = 0 + for arg in args: + if w is arg: + return ix + ix += 1 + raise PyrtlInternalError('Expected to find wire in set of args') + + if maintain_arg_order: + block = working_block(block) + for net in sorted(block.logic_subset(op='c-<>x@'), key=_node_sort_key): + args = [(node_index_map[n], wire) for (n, wire) in srcs[net]] + args.sort(key=lambda t: index_of(t[1], net.args)) + s = ' -> '.join(['n%d' % n for n, _ in args]) + rstring += ' {\n' + rstring += ' rank=same;\n' + rstring += ' edge[style=invis];\n' + rstring += ' ' + s + ';\n' + rstring += ' rankdir=LR;\n' + rstring += ' }\n' rstring += '}\n' return rstring @@ -399,16 +436,20 @@ def output_to_svg(file, block=None, split_state=True): print(block_to_svg(block, split_state), file=file) -def block_to_svg(block=None, split_state=True): +def block_to_svg(block=None, split_state=True, maintain_arg_order=False): """ Return an SVG for the block. :param block: Block to use (defaults to current working block) :param split_state: If True, visually split the connections to/from a register update net. + :param maintain_arg_order: If True, will add ordering constraints so that that incoming edges + are ordered left-to-right for nets where argument order matters (e.g. '<'). Keeping this + as False results in a cleaner, though less visually precise, graphical output. :return: The SVG representation of the block """ try: from graphviz import Source - return Source(block_to_graphviz_string(block, split_state=split_state))._repr_svg_() + return Source(block_to_graphviz_string(block, split_state=split_state, + maintain_arg_order=maintain_arg_order))._repr_svg_() except ImportError: raise PyrtlError('need graphviz installed (try "pip install graphviz")')
UCSBarchlab/PyRTL
79099f53f44ce56a3864d31ce002bc2a60e0b441
diff --git a/tests/test_visualization.py b/tests/test_visualization.py index cabe977..fea473b 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -5,7 +5,7 @@ import pyrtl from .test_importexport import full_adder_blif -graphviz_string = """\ +graphviz_string_detailed = """\ digraph g { graph [splines="spline", outputorder="edgesfirst"]; node [shape=circle, style=filled, fillcolor=lightblue1, @@ -35,6 +35,138 @@ digraph g { n9 -> n11 [label="tmp3/6 (Delay: 706.50)", penwidth="6", arrowhead="none"]; n10 -> n11 [label="tmp4/4 (Delay: 0.00)", penwidth="6", arrowhead="none"]; n11 -> n4 [label="tmp5/10 (Delay: 706.50)", penwidth="6", arrowhead="normal"]; + { + rank=same; + edge[style=invis]; + n6 -> n0; + rankdir=LR; + } + { + rank=same; + edge[style=invis]; + n10 -> n9; + rankdir=LR; + } +} + +""" + +graphviz_string_arg_ordered = """\ +digraph g { + graph [splines="spline", outputorder="edgesfirst"]; + node [shape=circle, style=filled, fillcolor=lightblue1, + fontcolor=black, fontname=helvetica, penwidth=0, + fixedsize=shape]; + edge [labelfloat=false, penwidth=2, color=deepskyblue, arrowsize=.5]; + n0 [label="0", shape=circle, fillcolor=lightgrey]; + n1 [label="0", shape=circle, fillcolor=lightgrey]; + n2 [label="0", shape=circle, fillcolor=lightgrey]; + n3 [label="i", shape=invhouse, fillcolor=coral]; + n4 [label="j", shape=invhouse, fillcolor=coral]; + n5 [label="", height=.1, width=.1]; + n6 [label="o", shape=house, fillcolor=lawngreen]; + n7 [label="", height=.1, width=.1]; + n8 [label="q", shape=house, fillcolor=lawngreen]; + n9 [label="[0]*4", fillcolor=azure1, height=.25, width=.25]; + n10 [label="concat", height=.1, width=.1]; + n11 [label="<"]; + n12 [label="[0]*7", fillcolor=azure1, height=.25, width=.25]; + n13 [label="concat", height=.1, width=.1]; + n14 [label="[0]*4", fillcolor=azure1, height=.25, width=.25]; + n15 [label="concat", height=.1, width=.1]; + n16 [label=">"]; + n0 -> n9 [label="", penwidth="2", arrowhead="none"]; + n1 -> n12 [label="", penwidth="2", arrowhead="none"]; + n2 -> n14 [label="", penwidth="2", arrowhead="none"]; + n3 -> n11 [label="", penwidth="6", arrowhead="normal"]; + n3 -> n16 [label="", penwidth="6", arrowhead="normal"]; + n4 -> n10 [label="", penwidth="6", arrowhead="none"]; + n4 -> n15 [label="", penwidth="6", arrowhead="none"]; + n5 -> n6 [label="", penwidth="6", arrowhead="normal"]; + n7 -> n8 [label="", penwidth="2", arrowhead="normal"]; + n9 -> n10 [label="", penwidth="6", arrowhead="none"]; + n10 -> n11 [label="", penwidth="6", arrowhead="normal"]; + n11 -> n13 [label="", penwidth="2", arrowhead="none"]; + n12 -> n13 [label="", penwidth="6", arrowhead="none"]; + n13 -> n5 [label="", penwidth="6", arrowhead="normal"]; + n14 -> n15 [label="", penwidth="6", arrowhead="none"]; + n15 -> n16 [label="", penwidth="6", arrowhead="normal"]; + n16 -> n7 [label="", penwidth="2", arrowhead="normal"]; + { + rank=same; + edge[style=invis]; + n9 -> n4; + rankdir=LR; + } + { + rank=same; + edge[style=invis]; + n3 -> n10; + rankdir=LR; + } + { + rank=same; + edge[style=invis]; + n12 -> n11; + rankdir=LR; + } + { + rank=same; + edge[style=invis]; + n14 -> n4; + rankdir=LR; + } + { + rank=same; + edge[style=invis]; + n15 -> n3; + rankdir=LR; + } +} + +""" + +graphviz_string_arg_unordered = """\ +digraph g { + graph [splines="spline", outputorder="edgesfirst"]; + node [shape=circle, style=filled, fillcolor=lightblue1, + fontcolor=black, fontname=helvetica, penwidth=0, + fixedsize=shape]; + edge [labelfloat=false, penwidth=2, color=deepskyblue, arrowsize=.5]; + n0 [label="0", shape=circle, fillcolor=lightgrey]; + n1 [label="0", shape=circle, fillcolor=lightgrey]; + n2 [label="0", shape=circle, fillcolor=lightgrey]; + n3 [label="i", shape=invhouse, fillcolor=coral]; + n4 [label="j", shape=invhouse, fillcolor=coral]; + n5 [label="", height=.1, width=.1]; + n6 [label="o", shape=house, fillcolor=lawngreen]; + n7 [label="", height=.1, width=.1]; + n8 [label="q", shape=house, fillcolor=lawngreen]; + n9 [label="[0]*4", fillcolor=azure1, height=.25, width=.25]; + n10 [label="concat", height=.1, width=.1]; + n11 [label="<"]; + n12 [label="[0]*7", fillcolor=azure1, height=.25, width=.25]; + n13 [label="concat", height=.1, width=.1]; + n14 [label="[0]*4", fillcolor=azure1, height=.25, width=.25]; + n15 [label="concat", height=.1, width=.1]; + n16 [label=">"]; + n0 -> n9 [label="", penwidth="2", arrowhead="none"]; + n1 -> n12 [label="", penwidth="2", arrowhead="none"]; + n2 -> n14 [label="", penwidth="2", arrowhead="none"]; + n3 -> n11 [label="", penwidth="6", arrowhead="normal"]; + n3 -> n16 [label="", penwidth="6", arrowhead="normal"]; + n4 -> n10 [label="", penwidth="6", arrowhead="none"]; + n4 -> n15 [label="", penwidth="6", arrowhead="none"]; + n5 -> n6 [label="", penwidth="6", arrowhead="normal"]; + n7 -> n8 [label="", penwidth="2", arrowhead="normal"]; + n9 -> n10 [label="", penwidth="6", arrowhead="none"]; + n10 -> n11 [label="", penwidth="6", arrowhead="normal"]; + n11 -> n13 [label="", penwidth="2", arrowhead="none"]; + n12 -> n13 [label="", penwidth="6", arrowhead="none"]; + n13 -> n5 [label="", penwidth="6", arrowhead="normal"]; + n14 -> n15 [label="", penwidth="6", arrowhead="none"]; + n15 -> n16 [label="", penwidth="6", arrowhead="normal"]; + n16 -> n7 [label="", penwidth="2", arrowhead="normal"]; } """ @@ -98,9 +230,34 @@ class TestOutputGraphs(unittest.TestCase): with io.StringIO() as vfile: pyrtl.output_to_graphviz( file=vfile, - namer=pyrtl.graphviz_detailed_namer(node_fanout, wire_delay) + namer=pyrtl.graphviz_detailed_namer(node_fanout, wire_delay), + maintain_arg_order=True ) - self.assertEqual(vfile.getvalue(), graphviz_string) + self.assertEqual(vfile.getvalue(), graphviz_string_detailed) + + def test_output_to_graphviz_correct_output_with_arg_ordering(self): + i = pyrtl.Input(8, 'i') + j = pyrtl.Input(4, 'j') + o = pyrtl.Output(8, 'o') + q = pyrtl.Output(1, 'q') + o <<= i < j + q <<= j > i + + with io.StringIO() as vfile: + pyrtl.output_to_graphviz(file=vfile, maintain_arg_order=True) + self.assertEqual(vfile.getvalue(), graphviz_string_arg_ordered) + + def test_output_to_graphviz_correct_output_without_arg_ordering(self): + i = pyrtl.Input(8, 'i') + j = pyrtl.Input(4, 'j') + o = pyrtl.Output(8, 'o') + q = pyrtl.Output(1, 'q') + o <<= i < j + q <<= j > i + + with io.StringIO() as vfile: + pyrtl.output_to_graphviz(file=vfile) + self.assertEqual(vfile.getvalue(), graphviz_string_arg_unordered) class TestNetGraph(unittest.TestCase):
Improve visualization of nets where order of incoming edges matters For nets where the order of incoming edges matters (e.g. `c`, `-`, `<`, `>`, `x`, and `@`), it would be nice to improve the way visualizations present them. For example, given the following netlist: ``` tmp6/1W <-- s -- i/8I ((4,)) tmp4/1W <-- s -- i/8I ((2,)) tmp2/1W <-- s -- i/8I ((0,)) tmp5/1W <-- s -- i/8I ((3,)) tmp7/1W <-- s -- i/8I ((5,)) o/8O <-- w -- tmp10/8W tmp10/8W <-- c -- tmp7/1W, tmp6/1W, tmp5/1W, tmp4/1W, tmp3/1W, tmp2/1W, const_0_0_synth_1/1C, const_0_0_synth_0/1C tmp3/1W <-- s -- i/8I ((1,)) ``` outputting to SVG produces the following: ![shift_test_sll_new_synth_opt](https://user-images.githubusercontent.com/2482771/117214298-79403600-adb1-11eb-96bb-21f92762c4c6.png) It would be greatly improved if `[5]` was furthest left, followed by `[4]` to the right, etc., like the actual netlist is. This is probably an issue specifically related to using graphviz, so if that library doesn't have the capability, it might be nice to consider adding support for an output format that respects left-to-right ordering.
0.0
79099f53f44ce56a3864d31ce002bc2a60e0b441
[ "tests/test_visualization.py::TestOutputGraphs::test_output_to_graphviz_correct_detailed_output", "tests/test_visualization.py::TestOutputGraphs::test_output_to_graphviz_correct_output_with_arg_ordering" ]
[ "tests/test_visualization.py::TestOutputGraphs::test_output_to_graphviz_correct_output_without_arg_ordering", "tests/test_visualization.py::TestOutputGraphs::test_output_to_graphviz_does_not_throw_error", "tests/test_visualization.py::TestOutputGraphs::test_output_to_graphviz_with_custom_namer_does_not_throw_error", "tests/test_visualization.py::TestOutputGraphs::test_output_to_tgf_does_not_throw_error", "tests/test_visualization.py::TestNetGraph::test_as_graph", "tests/test_visualization.py::TestNetGraph::test_netgraph_same_wire_multiple_edges_to_same_net", "tests/test_visualization.py::TestNetGraph::test_netgraph_unused_wires", "tests/test_visualization.py::TestOutputIPynb::test_one_bit_adder_matches_expected" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-06 01:28:15+00:00
bsd-3-clause
807
UFRN-URNAI__urnai-tools-78
diff --git a/urnai/states/__init__.py b/urnai/states/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/urnai/states/state_base.py b/urnai/states/state_base.py new file mode 100644 index 0000000..8e0a903 --- /dev/null +++ b/urnai/states/state_base.py @@ -0,0 +1,38 @@ +from abc import ABC, abstractmethod +from typing import Any, List + + +class StateBase(ABC): + """ + Every Agent needs to own an instance of this base class + in order to define its State. + So every time we want to create a new agent, + we should either use an existing State implementation or create a new one. + """ + + @abstractmethod + def update(self, obs) -> List[Any]: + """ + This method receives as a parameter an Observation and returns a State, which + is usually a list of features extracted from the Observation. The Agent uses + this State during training to receive a new action from its model and also to + make it learn, that's why this method should always return a list. + """ + pass + + @property + @abstractmethod + def state(self): + """Returns the State currently saved.""" + pass + + @property + @abstractmethod + def dimension(self): + """Returns the dimensions of the States returned by the update method.""" + pass + + @abstractmethod + def reset(self): + """Resets the State currently saved.""" + pass \ No newline at end of file
UFRN-URNAI/urnai-tools
0dfb6fe8c8ddb791bf109cd4b00b25ae07659ae7
diff --git a/tests/units/states/__init__.py b/tests/units/states/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/units/states/test_state_base.py b/tests/units/states/test_state_base.py new file mode 100644 index 0000000..c42b803 --- /dev/null +++ b/tests/units/states/test_state_base.py @@ -0,0 +1,25 @@ +import unittest +from abc import ABCMeta + +from urnai.states.state_base import StateBase + + +class TestStateBase(unittest.TestCase): + + def test_abstract_methods(self): + StateBase.__abstractmethods__ = set() + + class FakeState(StateBase): + def __init__(self): + super().__init__() + + fake_state = FakeState() + update_return = fake_state.update("observation") + state = fake_state.state + dimension = fake_state.dimension + reset_return = fake_state.reset() + assert isinstance(StateBase, ABCMeta) + assert update_return is None + assert state is None + assert dimension is None + assert reset_return is None
Base class for the state representation We need a class that lets us know the agent's current state. It needs to have the `update` method, which will update the agent's state according to the script developed. Suggestions: - Class name: `StateBase`. - Class path: `urnai.states`.
0.0
0dfb6fe8c8ddb791bf109cd4b00b25ae07659ae7
[ "tests/units/states/test_state_base.py::TestStateBase::test_abstract_methods" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2024-02-27 19:06:35+00:00
apache-2.0
808
Uberi__speech_recognition-619
diff --git a/speech_recognition/__init__.py b/speech_recognition/__init__.py index 39d042a..ed86b75 100644 --- a/speech_recognition/__init__.py +++ b/speech_recognition/__init__.py @@ -855,7 +855,7 @@ class Recognizer(AudioSource): if hypothesis is not None: return hypothesis.hypstr raise UnknownValueError() # no transcriptions available - def recognize_google(self, audio_data, key=None, language="en-US", pfilter=0, show_all=False): + def recognize_google(self, audio_data, key=None, language="en-US", pfilter=0, show_all=False, with_confidence=False): """ Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Speech Recognition API. @@ -927,7 +927,9 @@ class Recognizer(AudioSource): # https://cloud.google.com/speech-to-text/docs/basics#confidence-values # "Your code should not require the confidence field as it is not guaranteed to be accurate, or even set, in any of the results." confidence = best_hypothesis.get("confidence", 0.5) - return best_hypothesis["transcript"], confidence + if with_confidence: + return best_hypothesis["transcript"], confidence + return best_hypothesis["transcript"] def recognize_google_cloud(self, audio_data, credentials_json=None, language="en-US", preferred_phrases=None, show_all=False): """
Uberi/speech_recognition
45c0a25d48561a1deccc0632fb949d8533bbd34e
diff --git a/.github/workflows/unittests.yml b/.github/workflows/unittests.yml new file mode 100644 index 0000000..68ce9d5 --- /dev/null +++ b/.github/workflows/unittests.yml @@ -0,0 +1,36 @@ +name: Unit tests + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + fail-fast: true + matrix: + python-version: ["3.9"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install --no-install-recommends -y libpulse-dev libasound2-dev + - name: Install Python dependencies + run: | + python -m pip install pocketsphinx + python -m pip install . + - name: Test with unittest + run: | + python -m unittest discover --verbose diff --git a/tests/test_recognition.py b/tests/test_recognition.py index ef83ce4..34934c2 100644 --- a/tests/test_recognition.py +++ b/tests/test_recognition.py @@ -21,7 +21,7 @@ class TestRecognition(unittest.TestCase): def test_google_english(self): r = sr.Recognizer() with sr.AudioFile(self.AUDIO_FILE_EN) as source: audio = r.record(source) - self.assertIn(r.recognize_google(audio), ["1 2 3", "one two three"]) + self.assertIn(r.recognize_google(audio), ["123", "1 2 3", "one two three"]) def test_google_french(self): r = sr.Recognizer()
unittest is failing due to change for recognize_google method to return tuples with confidence Steps to reproduce ------------------ 1. `git clone` this repository 2. `python3.9 -m venv venv --upgrade-deps`, then `source venv/bin/activate` 3. `pip install -e .` 4. `pip install pocketsphinx` 5. `python -m unittest discover --verbose` Expected behaviour ------------------ All test passes. Actual behaviour ---------------- Tests of `recognize_google` fails. ``` ====================================================================== FAIL: test_google_chinese (tests.test_recognition.TestRecognition) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/.../speech_recognition/tests/test_recognition.py", line 34, in test_google_chinese self.assertEqual(r.recognize_google(audio, language="zh-CN"), u"砸自己的脚") AssertionError: ('砸自己的脚', 0.96296197) != '砸自己的脚' ====================================================================== FAIL: test_google_english (tests.test_recognition.TestRecognition) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/.../speech_recognition/tests/test_recognition.py", line 24, in test_google_english self.assertIn(r.recognize_google(audio), ["1 2 3", "one two three"]) AssertionError: ('123', 0.77418035) not found in ['1 2 3', 'one two three'] ====================================================================== FAIL: test_google_french (tests.test_recognition.TestRecognition) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/.../speech_recognition/tests/test_recognition.py", line 29, in test_google_french self.assertEqual(r.recognize_google(audio, language="fr-FR"), u"et c'est la dictée numéro 1") AssertionError: ("et c'est la dictée numéro 1", 0.93855578) != "et c'est la dictée numéro 1" ---------------------------------------------------------------------- Ran 28 tests in 4.440s FAILED (failures=3, skipped=8) ``` Output is here: ``` test_google_chinese (tests.test_recognition.TestRecognition) ... result2: { 'alternative': [ {'confidence': 0.96296197, 'transcript': '砸自己的脚'}, {'transcript': '咱自己的脚'}, {'transcript': '打自己的脚'}, {'transcript': '咱自己的角'}, {'transcript': '砸自己的角'}], 'final': True} FAIL test_google_english (tests.test_recognition.TestRecognition) ... result2: { 'alternative': [ {'confidence': 0.77418035, 'transcript': '123'}, {'transcript': '1 2 3'}, {'transcript': 'one two three'}, {'transcript': '1-2-3'}, {'transcript': 'one-two-three'}], 'final': True} FAIL test_google_french (tests.test_recognition.TestRecognition) ... result2: { 'alternative': [ { 'confidence': 0.93855578, 'transcript': "et c'est la dictée numéro 1"}, {'transcript': "eh c'est la dictée numéro 1"}, {'transcript': "hé c'est la dictée numéro 1"}, {'transcript': "hey c'est la dictée numéro 1"}, {'transcript': "c'est la dictée numéro 1"}], 'final': True} FAIL ``` `recognize_google` was changed to return tuple (text, confidence) at https://github.com/Uberi/speech_recognition/commit/68627691f852b8af6da05aa647199079c346cba1 (pull request #434 ) `test_google_english` needs to be added `'123'` as expected value. System information ------------------ (Delete all the statements that don't apply.) My **system** is macOS Mojave. My **Python version** is 3.9.4. My **Pip version** is 22.2. My **SpeechRecognition library version** is 3.8.1. I **installed PocketSphinx from** https://pypi.org/project/pocketsphinx/ .
0.0
45c0a25d48561a1deccc0632fb949d8533bbd34e
[ "tests/test_recognition.py::TestRecognition::test_google_english", "tests/test_recognition.py::TestRecognition::test_google_french" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-07-26 12:04:03+00:00
bsd-3-clause
809
Unidata__MetPy-2580
diff --git a/docs/_templates/overrides/metpy.calc.rst b/docs/_templates/overrides/metpy.calc.rst index f6eeeaf372..88a9d5cdad 100644 --- a/docs/_templates/overrides/metpy.calc.rst +++ b/docs/_templates/overrides/metpy.calc.rst @@ -90,6 +90,7 @@ Soundings storm_relative_helicity supercell_composite surface_based_cape_cin + sweat_index total_totals_index vertical_totals diff --git a/setup.cfg b/setup.cfg index cd334e3677..6eed3787a4 100644 --- a/setup.cfg +++ b/setup.cfg @@ -45,7 +45,7 @@ install_requires = matplotlib>=3.3.0 numpy>=1.18.0 pandas>=1.0.0 - pint>=0.10.1 + pint>=0.13 pooch>=1.2.0 pyproj>=2.5.0 scipy>=1.4.0 diff --git a/src/metpy/calc/thermo.py b/src/metpy/calc/thermo.py index 1eb1424bb7..44bb3aa5d8 100644 --- a/src/metpy/calc/thermo.py +++ b/src/metpy/calc/thermo.py @@ -4352,3 +4352,87 @@ def cross_totals(pressure, temperature, dewpoint): # Calculate vertical totals. return td850 - t500 + + [email protected] +@preprocess_and_wrap() +@check_units('[pressure]', '[temperature]', '[temperature]', '[speed]') +def sweat_index(pressure, temperature, dewpoint, speed, direction): + """Calculate SWEAT Index. + + SWEAT Index derived from [Miller1972]_: + + .. math:: SWEAT = 12Td_{850} + 20(TT - 49) + 2f_{850} + f_{500} + 125(S + 0.2) + + where: + + * :math:`Td_{850}` is the dewpoint at 850 hPa; the first term is set to zero + if :math:`Td_{850}` is negative. + * :math:`TT` is the total totals index; the second term is set to zero + if :math:`TT` is less than 49 + * :math:`f_{850}` is the wind speed at 850 hPa + * :math:`f_{500}` is the wind speed at 500 hPa + * :math:`S` is the shear term: :math:`sin{(dd_{850} - dd_{500})}`, where + :math:`dd_{850}` and :math:`dd_{500}` are the wind directions at 850 hPa and 500 hPa, + respectively. It is set to zero if any of the following conditions are not met: + + 1. :math:`dd_{850}` is between 130 - 250 degrees + 2. :math:`dd_{500}` is between 210 - 310 degrees + 3. :math:`dd_{500} - dd_{850} > 0` + 4. both the wind speeds are greater than or equal to 15 kts + + Calculation of the SWEAT Index consists of a low-level moisture, instability, + and the vertical wind shear (both speed and direction). This index aim to + determine the likeliness of severe weather and tornadoes. + + Parameters + ---------- + pressure : `pint.Quantity` + Pressure level(s), in order from highest to lowest pressure + + temperature : `pint.Quantity` + Temperature corresponding to pressure + + dewpoint : `pint.Quantity` + Dewpoint temperature corresponding to pressure + + speed : `pint.Quantity` + Wind speed corresponding to pressure + + direction : `pint.Quantity` + Wind direction corresponding to pressure + + Returns + ------- + `pint.Quantity` + SWEAT Index + + """ + # Find dewpoint at 850 hPa. + td850 = interpolate_1d(units.Quantity(850, 'hPa'), pressure, dewpoint) + + # Find total totals index. + tt = total_totals_index(pressure, temperature, dewpoint) + + # Find wind speed and direction at 850 and 500 hPa + (f850, f500), (dd850, dd500) = interpolate_1d(units.Quantity([850, 500], + 'hPa'), pressure, speed, + direction) + + # First term is set to zero if Td850 is negative + first_term = 12 * np.clip(td850.m_as('degC'), 0, None) + + # Second term is set to zero if TT is less than 49 + second_term = 20 * np.clip(tt.m_as('degC') - 49, 0, None) + + # Shear term is set to zero if any of four conditions are not met + required = ((units.Quantity(130, 'deg') <= dd850) & (dd850 <= units.Quantity(250, 'deg')) + & (units.Quantity(210, 'deg') <= dd500) & (dd500 <= units.Quantity(310, 'deg')) + & (dd500 - dd850 > 0) + & (f850 >= units.Quantity(15, 'knots')) + & (f500 >= units.Quantity(15, 'knots'))) + shear_term = np.atleast_1d(125 * (np.sin(dd500 - dd850) + 0.2)) + shear_term[~required] = 0 + + # Calculate sweat index. + return first_term + second_term + (2 * f850.m) + f500.m + shear_term
Unidata/MetPy
f6aac4c44218164089e0e0d3b3767feebc70b84c
diff --git a/tests/calc/test_thermo.py b/tests/calc/test_thermo.py index cc8e5827bf..1766b91bb2 100644 --- a/tests/calc/test_thermo.py +++ b/tests/calc/test_thermo.py @@ -27,7 +27,7 @@ from metpy.calc import (brunt_vaisala_frequency, brunt_vaisala_frequency_squared saturation_equivalent_potential_temperature, saturation_mixing_ratio, saturation_vapor_pressure, showalter_index, specific_humidity_from_dewpoint, specific_humidity_from_mixing_ratio, - static_stability, surface_based_cape_cin, + static_stability, surface_based_cape_cin, sweat_index, temperature_from_potential_temperature, thickness_hydrostatic, thickness_hydrostatic_from_relative_humidity, total_totals_index, vapor_pressure, vertical_totals, vertical_velocity, @@ -2157,3 +2157,40 @@ def test_parcel_profile_with_lcl_as_dataset_duplicates(): profile = parcel_profile_with_lcl_as_dataset(pressure, temperature, dewpoint) xr.testing.assert_allclose(profile, truth, atol=1e-5) + + +def test_sweat_index(): + """Test the SWEAT Index calculation.""" + pressure = np.array([1008., 1000., 947., 925., 921., 896., 891., 889., 866., + 858., 850., 835., 820., 803., 733., 730., 700., 645., + 579., 500., 494., 466., 455., 441., 433., 410., 409., + 402., 400., 390., 388., 384., 381., 349., 330., 320., + 306., 300., 278., 273., 250., 243., 208., 200., 196., + 190., 179., 159., 151., 150., 139.]) * units.hPa + temperature = np.array([27.4, 26.4, 22.9, 21.4, 21.2, 20.7, 20.6, 21.2, 19.4, + 19.1, 18.8, 17.8, 17.4, 16.3, 11.4, 11.2, 10.2, 6.1, + 0.6, -4.9, -5.5, -8.5, -9.9, -11.7, -12.3, -13.7, -13.8, + -14.9, -14.9, -16.1, -16.1, -16.9, -17.3, -21.7, -24.5, -26.1, + -28.3, -29.5, -33.1, -34.2, -39.3, -41., -50.2, -52.5, -53.5, + -55.2, -58.6, -65.2, -68.1, -68.5, -72.5]) * units.degC + dewpoint = np.array([24.9, 24.6, 22., 20.9, 20.7, 14.8, 13.6, 12.2, 16.8, + 16.6, 16.5, 15.9, 13.6, 13.2, 11.3, 11.2, 8.6, 4.5, + -0.8, -8.1, -9.5, -12.7, -12.7, -12.8, -13.1, -24.7, -24.4, + -21.9, -24.9, -36.1, -31.1, -26.9, -27.4, -33., -36.5, -47.1, + -31.4, -33.5, -40.1, -40.8, -44.1, -45.6, -54., -56.1, -56.9, + -58.6, -61.9, -68.4, -71.2, -71.6, -77.2]) * units.degC + speed = np.array([0., 3., 10., 12., 12., 14., 14., 14., 12., + 12., 12., 12., 11., 11., 12., 12., 10., 10., + 8., 5., 4., 1., 0., 3., 5., 10., 10., + 11., 11., 13., 14., 14., 15., 23., 23., 24., + 24., 24., 26., 27., 28., 30., 25., 24., 26., + 28., 33., 29., 32., 26., 26.]) * units.knot + direction = np.array([0., 170., 200., 205., 204., 200., 197., 195., 180., + 175., 175., 178., 181., 185., 160., 160., 165., 165., + 203., 255., 268., 333., 0., 25., 40., 83., 85., + 89., 90., 100., 103., 107., 110., 90., 88., 87., + 86., 85., 85., 85., 60., 55., 60., 50., 46., + 40., 45., 35., 50., 50., 50.]) * units.degree + + sweat = sweat_index(pressure, temperature, dewpoint, speed, direction) + assert_almost_equal(sweat, 227., 2)
SWEAT Index Another severe weather index. From COD: http://weather.cod.edu/sirvatka/si.html ## SWEAT Index SWEAT = 12Td850 + 20(TT - 49) + 2f850 + f500 + 125(s + 0.2); where the first term is set to zero if the 850 mb Td (°C) is negative; TT is the Total Totals Index (if TT < 49, the term is set to zero); f is the wind speed in knots; and s = sin (500 mb wind direction - 850 mb wind direction). The last term is set to zero if any of the following is not met: 1) the 850 mb wind is between 130°-250°; 2) the 500 mb wind is between 210°-310°; 3) (the 500 mb wind direction - the 850 mb wind direction) is greater than zero; or 4) both the wind speeds are greater than or equal to 15 kts. SWEAT values +250 indicate a potential for strong convection. SWEAT values +300 indicate the threshold for severe thunderstorms. SWEAT values +400 indicate the threshold for tornadoes.
0.0
f6aac4c44218164089e0e0d3b3767feebc70b84c
[ "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint", "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint_with_f", "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint_xarray", "tests/calc/test_thermo.py::test_exner_function", "tests/calc/test_thermo.py::test_potential_temperature", "tests/calc/test_thermo.py::test_temperature_from_potential_temperature", "tests/calc/test_thermo.py::test_pot_temp_scalar", "tests/calc/test_thermo.py::test_pot_temp_fahrenheit", "tests/calc/test_thermo.py::test_pot_temp_inhg", "tests/calc/test_thermo.py::test_dry_lapse", "tests/calc/test_thermo.py::test_dry_lapse_2_levels", "tests/calc/test_thermo.py::test_moist_lapse[degF]", "tests/calc/test_thermo.py::test_moist_lapse[degC]", "tests/calc/test_thermo.py::test_moist_lapse[K]", "tests/calc/test_thermo.py::test_moist_lapse_ref_pressure", "tests/calc/test_thermo.py::test_moist_lapse_scalar", "tests/calc/test_thermo.py::test_moist_lapse_close_start", "tests/calc/test_thermo.py::test_moist_lapse_uniform", "tests/calc/test_thermo.py::test_moist_lapse_nan_temp", "tests/calc/test_thermo.py::test_moist_lapse_nan_ref_press", "tests/calc/test_thermo.py::test_moist_lapse_downwards", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[0-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[0--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[1-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[1--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[2-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[2--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[3-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[3--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[4-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[4--1]", "tests/calc/test_thermo.py::test_parcel_profile", "tests/calc/test_thermo.py::test_parcel_profile_lcl", "tests/calc/test_thermo.py::test_parcel_profile_lcl_not_monotonic", "tests/calc/test_thermo.py::test_parcel_profile_with_lcl_as_dataset", "tests/calc/test_thermo.py::test_parcel_profile_saturated", "tests/calc/test_thermo.py::test_sat_vapor_pressure", "tests/calc/test_thermo.py::test_sat_vapor_pressure_scalar", "tests/calc/test_thermo.py::test_sat_vapor_pressure_fahrenheit", "tests/calc/test_thermo.py::test_basic_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_scalar_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_percent_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_warning_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_dewpoint", "tests/calc/test_thermo.py::test_dewpoint_weird_units", "tests/calc/test_thermo.py::test_mixing_ratio", "tests/calc/test_thermo.py::test_vapor_pressure", "tests/calc/test_thermo.py::test_lcl", "tests/calc/test_thermo.py::test_lcl_kelvin", "tests/calc/test_thermo.py::test_lcl_convergence", "tests/calc/test_thermo.py::test_lcl_nans", "tests/calc/test_thermo.py::test_lfc_basic", "tests/calc/test_thermo.py::test_lfc_kelvin", "tests/calc/test_thermo.py::test_lfc_ml", "tests/calc/test_thermo.py::test_lfc_ml2", "tests/calc/test_thermo.py::test_lfc_intersection", "tests/calc/test_thermo.py::test_no_lfc", "tests/calc/test_thermo.py::test_lfc_inversion", "tests/calc/test_thermo.py::test_lfc_equals_lcl", "tests/calc/test_thermo.py::test_sensitive_sounding", "tests/calc/test_thermo.py::test_lfc_sfc_precision", "tests/calc/test_thermo.py::test_lfc_pos_area_below_lcl", "tests/calc/test_thermo.py::test_saturation_mixing_ratio", "tests/calc/test_thermo.py::test_saturation_mixing_ratio_with_xarray", "tests/calc/test_thermo.py::test_equivalent_potential_temperature", "tests/calc/test_thermo.py::test_equivalent_potential_temperature_masked", "tests/calc/test_thermo.py::test_saturation_equivalent_potential_temperature", "tests/calc/test_thermo.py::test_saturation_equivalent_potential_temperature_masked", "tests/calc/test_thermo.py::test_virtual_temperature", "tests/calc/test_thermo.py::test_virtual_potential_temperature", "tests/calc/test_thermo.py::test_density", "tests/calc/test_thermo.py::test_el", "tests/calc/test_thermo.py::test_el_kelvin", "tests/calc/test_thermo.py::test_el_ml", "tests/calc/test_thermo.py::test_no_el", "tests/calc/test_thermo.py::test_no_el_multi_crossing", "tests/calc/test_thermo.py::test_lfc_and_el_below_lcl", "tests/calc/test_thermo.py::test_el_lfc_equals_lcl", "tests/calc/test_thermo.py::test_el_small_surface_instability", "tests/calc/test_thermo.py::test_no_el_parcel_colder", "tests/calc/test_thermo.py::test_el_below_lcl", "tests/calc/test_thermo.py::test_wet_psychrometric_vapor_pressure", "tests/calc/test_thermo.py::test_wet_psychrometric_rh", "tests/calc/test_thermo.py::test_wet_psychrometric_rh_kwargs", "tests/calc/test_thermo.py::test_mixing_ratio_from_relative_humidity", "tests/calc/test_thermo.py::test_rh_mixing_ratio", "tests/calc/test_thermo.py::test_mixing_ratio_from_specific_humidity", "tests/calc/test_thermo.py::test_mixing_ratio_from_specific_humidity_no_units", "tests/calc/test_thermo.py::test_specific_humidity_from_mixing_ratio", "tests/calc/test_thermo.py::test_specific_humidity_from_mixing_ratio_no_units", "tests/calc/test_thermo.py::test_rh_specific_humidity", "tests/calc/test_thermo.py::test_cape_cin", "tests/calc/test_thermo.py::test_cape_cin_no_el", "tests/calc/test_thermo.py::test_cape_cin_no_lfc", "tests/calc/test_thermo.py::test_find_append_zero_crossings", "tests/calc/test_thermo.py::test_most_unstable_parcel", "tests/calc/test_thermo.py::test_isentropic_pressure", "tests/calc/test_thermo.py::test_isentropic_pressure_masked_column", "tests/calc/test_thermo.py::test_isentropic_pressure_p_increase", "tests/calc/test_thermo.py::test_isentropic_pressure_additional_args", "tests/calc/test_thermo.py::test_isentropic_pressure_tmp_out", "tests/calc/test_thermo.py::test_isentropic_pressure_p_increase_rh_out", "tests/calc/test_thermo.py::test_isentropic_pressure_interp", "tests/calc/test_thermo.py::test_isentropic_pressure_addition_args_interp", "tests/calc/test_thermo.py::test_isentropic_pressure_tmp_out_interp", "tests/calc/test_thermo.py::test_isentropic_pressure_data_bounds_error", "tests/calc/test_thermo.py::test_isentropic_pressure_4d", "tests/calc/test_thermo.py::test_isentropic_interpolation_dataarray", "tests/calc/test_thermo.py::test_isentropic_interpolation_as_dataset", "tests/calc/test_thermo.py::test_surface_based_cape_cin[Quantity]", "tests/calc/test_thermo.py::test_surface_based_cape_cin[masked_array]", "tests/calc/test_thermo.py::test_surface_based_cape_cin_with_xarray", "tests/calc/test_thermo.py::test_profile_with_nans", "tests/calc/test_thermo.py::test_most_unstable_cape_cin_surface", "tests/calc/test_thermo.py::test_most_unstable_cape_cin", "tests/calc/test_thermo.py::test_mixed_parcel", "tests/calc/test_thermo.py::test_mixed_layer_cape_cin", "tests/calc/test_thermo.py::test_mixed_layer", "tests/calc/test_thermo.py::test_dry_static_energy", "tests/calc/test_thermo.py::test_moist_static_energy", "tests/calc/test_thermo.py::test_thickness_hydrostatic", "tests/calc/test_thermo.py::test_thickness_hydrostatic_subset", "tests/calc/test_thermo.py::test_thickness_hydrostatic_isothermal", "tests/calc/test_thermo.py::test_thickness_hydrostatic_isothermal_subset", "tests/calc/test_thermo.py::test_thickness_hydrostatic_from_relative_humidity", "tests/calc/test_thermo.py::test_mixing_ratio_dimensions", "tests/calc/test_thermo.py::test_saturation_mixing_ratio_dimensions", "tests/calc/test_thermo.py::test_mixing_ratio_from_rh_dimensions", "tests/calc/test_thermo.py::test_brunt_vaisala_frequency_squared", "tests/calc/test_thermo.py::test_brunt_vaisala_frequency", "tests/calc/test_thermo.py::test_brunt_vaisala_period", "tests/calc/test_thermo.py::test_wet_bulb_temperature[degF]", "tests/calc/test_thermo.py::test_wet_bulb_temperature[degC]", "tests/calc/test_thermo.py::test_wet_bulb_temperature[K]", "tests/calc/test_thermo.py::test_wet_bulb_temperature_saturated", "tests/calc/test_thermo.py::test_wet_bulb_temperature_numpy_scalars", "tests/calc/test_thermo.py::test_wet_bulb_temperature_1d", "tests/calc/test_thermo.py::test_wet_bulb_temperature_2d", "tests/calc/test_thermo.py::test_wet_bulb_nan[degF]", "tests/calc/test_thermo.py::test_wet_bulb_nan[degC]", "tests/calc/test_thermo.py::test_wet_bulb_nan[K]", "tests/calc/test_thermo.py::test_static_stability_adiabatic", "tests/calc/test_thermo.py::test_static_stability_cross_section", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_old_signature", "tests/calc/test_thermo.py::test_lfc_not_below_lcl", "tests/calc/test_thermo.py::test_multiple_lfcs_simple", "tests/calc/test_thermo.py::test_multiple_lfs_wide", "tests/calc/test_thermo.py::test_invalid_which", "tests/calc/test_thermo.py::test_multiple_els_simple", "tests/calc/test_thermo.py::test_multiple_el_wide", "tests/calc/test_thermo.py::test_muliple_el_most_cape", "tests/calc/test_thermo.py::test_muliple_lfc_most_cape", "tests/calc/test_thermo.py::test_el_lfc_most_cape_bottom", "tests/calc/test_thermo.py::test_cape_cin_top_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_bottom_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_wide_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_custom_profile", "tests/calc/test_thermo.py::test_parcel_profile_below_lcl", "tests/calc/test_thermo.py::test_vertical_velocity_pressure_dry_air", "tests/calc/test_thermo.py::test_vertical_velocity_dry_air", "tests/calc/test_thermo.py::test_vertical_velocity_pressure_moist_air", "tests/calc/test_thermo.py::test_vertical_velocity_moist_air", "tests/calc/test_thermo.py::test_specific_humidity_from_dewpoint", "tests/calc/test_thermo.py::test_lcl_convergence_issue", "tests/calc/test_thermo.py::test_cape_cin_value_error", "tests/calc/test_thermo.py::test_lcl_grid_surface_lcls", "tests/calc/test_thermo.py::test_lifted_index", "tests/calc/test_thermo.py::test_lifted_index_500hpa_missing", "tests/calc/test_thermo.py::test_k_index", "tests/calc/test_thermo.py::test_gradient_richardson_number", "tests/calc/test_thermo.py::test_gradient_richardson_number_with_xarray", "tests/calc/test_thermo.py::test_showalter_index", "tests/calc/test_thermo.py::test_total_totals_index", "tests/calc/test_thermo.py::test_vertical_totals", "tests/calc/test_thermo.py::test_cross_totals", "tests/calc/test_thermo.py::test_parcel_profile_drop_duplicates", "tests/calc/test_thermo.py::test_parcel_profile_with_lcl_as_dataset_duplicates" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-07-12 07:46:47+00:00
bsd-3-clause
810
Unidata__MetPy-2691
diff --git a/ci/doc_requirements.txt b/ci/doc_requirements.txt index 9a7099ca6d..e4e7c0c43e 100644 --- a/ci/doc_requirements.txt +++ b/ci/doc_requirements.txt @@ -1,7 +1,7 @@ sphinx==4.5.0 pydata-sphinx-theme==0.8.1 sphinx-gallery==0.11.1 -myst-parser==0.18.0 +myst-parser==0.18.1 netCDF4==1.6.1 geopandas==0.11.1 rtree==1.0.0 diff --git a/ci/linting_requirements.txt b/ci/linting_requirements.txt index dee85eb267..7e1b9024d1 100644 --- a/ci/linting_requirements.txt +++ b/ci/linting_requirements.txt @@ -2,7 +2,7 @@ flake8==5.0.4 pycodestyle==2.9.1 pyflakes==2.5.0 -flake8-bugbear==22.9.11 +flake8-bugbear==22.9.23 flake8-builtins==1.5.3 flake8-comprehensions==3.10.0 flake8-continuation==1.0.5 diff --git a/src/metpy/io/gempak.py b/src/metpy/io/gempak.py index bff5f9d292..15c5b0226f 100644 --- a/src/metpy/io/gempak.py +++ b/src/metpy/io/gempak.py @@ -1362,6 +1362,9 @@ class GempakGrid(GempakFile): 'gempak_grid_type': ftype, } ) + xrda = xrda.metpy.assign_latitude_longitude() + xrda['x'].attrs['units'] = 'meters' + xrda['y'].attrs['units'] = 'meters' grids.append(xrda) else:
Unidata/MetPy
acf42bc17ec954333b8a993823eab5193872c538
diff --git a/tests/io/test_gempak.py b/tests/io/test_gempak.py index 1883b71033..3cb09a20d6 100644 --- a/tests/io/test_gempak.py +++ b/tests/io/test_gempak.py @@ -249,9 +249,14 @@ def test_coordinates_creation(proj_type): def test_metpy_crs_creation(proj_type, proj_attrs): """Test grid mapping metadata.""" grid = GempakGrid(get_test_data(f'gem_{proj_type}.grd')) - metpy_crs = grid.gdxarray()[0].metpy.crs + arr = grid.gdxarray()[0] + metpy_crs = arr.metpy.crs for k, v in proj_attrs.items(): assert metpy_crs[k] == v + x_unit = arr['x'].units + y_unit = arr['y'].units + assert x_unit == 'meters' + assert y_unit == 'meters' def test_date_parsing():
gdxarray() should assign units to x and y coordinates Is there a way to construct the proper `Dataset` with the current MetPy functionality so my attempt to plot wind barbs works? Here's my attempt: ```python from datetime import datetime import xarray as xr import metpy from metpy.units import units from metpy.io import GempakGrid from metpy.plots.declarative import ContourPlot, FilledContourPlot, BarbPlot, MapPanel, PanelContainer print(metpy.__version__) MODEL = '/ldmdata/gempak/model/' gem_file_name = MODEL + 'nam/21092012_nam211.gem' gem_file = GempakGrid(gem_file_name) plot_time = datetime(2021, 9, 20, 12) u500 = gem_file.gdxarray(parameter='UREL', date_time=plot_time, level=500)[0] v500 = gem_file.gdxarray(parameter='VREL', date_time=plot_time, level=500)[0] u500 = u500 * units('m/s') v500 = v500 * units('m/s') wind = xr.merge([u500, v500]) barbs = BarbPlot() barbs.data = wind barbs.time = plot_time barbs.field = ['urel', 'vrel'] barbs.earth_relative = False # I get a plot w/o this line, but obviously the winds aren't rotated correctly barbs.skip = (3, 3) barbs.plot_units = 'knot' panel = MapPanel() panel.area = [-120, -74, 22, 55] panel.projection = 'lcc' panel.layers = ['states', 'coastline', 'borders'] panel.title = f'500-mb Winds at {plot_time}' panel.plots = [barbs] pc = PanelContainer() pc.size = (15, 15) pc.panels = [panel] pc.show() ``` The result: ``` 1.1.0.post39+gd43d5eb02.d20210825 Traceback (most recent call last): File "/home/decker/classes/met433/new_labs/barb_issue.py", line 42, in <module> pc.show() File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 589, in show self.draw() File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 576, in draw panel.draw() File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 846, in draw p.draw() File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 1480, in draw self._build() File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 1504, in _build x_like, y_like, u, v = self.plotdata File "/home/decker/src/git_repos/metpy/src/metpy/plots/declarative.py", line 1465, in plotdata if 'degree' in x.units: File "/home/decker/local/miniconda3/envs/devel21/lib/python3.9/site-packages/xarray/core/common.py", line 239, in __getattr__ raise AttributeError( AttributeError: 'DataArray' object has no attribute 'units' ```
0.0
acf42bc17ec954333b8a993823eab5193872c538
[ "tests/io/test_gempak.py::test_metpy_crs_creation[conical-proj_attrs0]", "tests/io/test_gempak.py::test_metpy_crs_creation[azimuthal-proj_attrs1]" ]
[ "tests/io/test_gempak.py::test_grid_loading[none]", "tests/io/test_gempak.py::test_grid_loading[diff]", "tests/io/test_gempak.py::test_grid_loading[dec]", "tests/io/test_gempak.py::test_grid_loading[grib]", "tests/io/test_gempak.py::test_merged_sounding", "tests/io/test_gempak.py::test_unmerged_sounding[gem_sigw_hght_unmrg.csv-gem_sigw_hght_unmrg.snd-TOP]", "tests/io/test_gempak.py::test_unmerged_sounding[gem_sigw_pres_unmrg.csv-gem_sigw_pres_unmrg.snd-WAML]", "tests/io/test_gempak.py::test_unmerged_sigw_pressure_sounding", "tests/io/test_gempak.py::test_standard_surface", "tests/io/test_gempak.py::test_ship_surface", "tests/io/test_gempak.py::test_coordinates_creation[conical]", "tests/io/test_gempak.py::test_coordinates_creation[cylindrical]", "tests/io/test_gempak.py::test_coordinates_creation[azimuthal]", "tests/io/test_gempak.py::test_date_parsing", "tests/io/test_gempak.py::test_surface_text[text-202109070000]", "tests/io/test_gempak.py::test_surface_text[spcl-202109071600]", "tests/io/test_gempak.py::test_sounding_text[txta]", "tests/io/test_gempak.py::test_sounding_text[txtb]", "tests/io/test_gempak.py::test_sounding_text[txtc]", "tests/io/test_gempak.py::test_sounding_text[txpb]", "tests/io/test_gempak.py::test_special_surface_observation" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-22 17:25:13+00:00
bsd-3-clause
811
Unidata__MetPy-3121
diff --git a/docs/_templates/overrides/metpy.calc.rst b/docs/_templates/overrides/metpy.calc.rst index 57a438210f..e5e7a4f787 100644 --- a/docs/_templates/overrides/metpy.calc.rst +++ b/docs/_templates/overrides/metpy.calc.rst @@ -79,6 +79,7 @@ Soundings cross_totals downdraft_cape el + galvez_davison_index k_index lcl lfc diff --git a/docs/api/references.rst b/docs/api/references.rst index 787cc6581d..dacd418954 100644 --- a/docs/api/references.rst +++ b/docs/api/references.rst @@ -86,6 +86,10 @@ References Services and Supporting Research, 2003. `FCM-R19-2003 <../_static/FCM-R19-2003-WindchillReport.pdf>`_, 75 pp. +.. [Galvez2015] Galvez, J. M. and Michel Davison, 2015. “The Gálvez-Davison Index for Tropical + Convection.” `GDI_Manuscript_V20161021 + <https://www.wpc.ncep.noaa.gov/international/gdi/GDI_Manuscript_V20161021.pdf>`_. + .. [Galway1956] Galway, J. G., 1956: The Lifted Index as a Predictor of Latent Instability. *American Meteorology Society*, doi:`10.1175/1520-0477-37.10.528 diff --git a/examples/calculations/Sounding_Calculations.py b/examples/calculations/Sounding_Calculations.py index fad5281800..0791a382ab 100644 --- a/examples/calculations/Sounding_Calculations.py +++ b/examples/calculations/Sounding_Calculations.py @@ -88,6 +88,11 @@ wdir = df['direction'].values * units.degree sped = df['speed'].values * units.knot height = df['height'].values * units.meter +########################################### +# Compute needed variables from our data file and attach units +relhum = mpcalc.relative_humidity_from_dewpoint(T, Td) +mixrat = mpcalc.mixing_ratio_from_relative_humidity(p, T, relhum) + ########################################### # Compute the wind components u, v = mpcalc.wind_components(sped, wdir) @@ -96,6 +101,7 @@ u, v = mpcalc.wind_components(sped, wdir) # Compute common sounding index parameters ctotals = mpcalc.cross_totals(p, T, Td) kindex = mpcalc.k_index(p, T, Td) +gdi = mpcalc.galvez_davison_index(p, T, mixrat, p[0]) showalter = mpcalc.showalter_index(p, T, Td) total_totals = mpcalc.total_totals_index(p, T, Td) vert_totals = mpcalc.vertical_totals(p, T) diff --git a/src/metpy/calc/thermo.py b/src/metpy/calc/thermo.py index 2a166f874e..4e7382daab 100644 --- a/src/metpy/calc/thermo.py +++ b/src/metpy/calc/thermo.py @@ -4497,6 +4497,181 @@ def k_index(pressure, temperature, dewpoint, vertical_dim=0): return ((t850 - t500) + td850 - (t700 - td700)).to(units.degC) [email protected] +@add_vertical_dim_from_xarray +@preprocess_and_wrap(broadcast=('pressure', 'temperature', 'mixing_ratio')) +@check_units('[pressure]', '[temperature]', '[dimensionless]', '[pressure]') +def galvez_davison_index(pressure, temperature, mixing_ratio, surface_pressure, + vertical_dim=0): + """ + Calculate GDI from the pressure, temperature, mixing ratio, and surface pressure. + + Calculation of the GDI relies on temperatures and mixing ratios at 950, + 850, 700, and 500 hPa. These four levels define three layers: A) Boundary, + B) Trade Wind Inversion (TWI), C) Mid-Troposphere. + + GDI formula derived from [Galvez2015]_: + + .. math:: GDI = CBI + MWI + II + TC + + where: + + * :math:`CBI` is the Column Buoyancy Index + * :math:`MWI` is the Mid-tropospheric Warming Index + * :math:`II` is the Inversion Index + * :math:`TC` is the Terrain Correction [optional] + + .. list-table:: GDI Values & Corresponding Convective Regimes + :widths: 15 75 + :header-rows: 1 + + * - GDI Value + - Expected Convective Regime + * - >=45 + - Scattered to widespread thunderstorms likely. + * - 35 to 45 + - Scattered thunderstorms and/or scattered to widespread rain showers. + * - 25 to 35 + - Isolated to scattered thunderstorms and/or scattered showers. + * - 15 to 25 + - Isolated thunderstorms and/or isolated to scattered showers. + * - 5 to 10 + - Isolated to scattered showers. + * - <5 + - Strong TWI likely, light rain possible. + + Parameters + ---------- + pressure : `pint.Quantity` + Pressure level(s) + + temperature : `pint.Quantity` + Temperature corresponding to pressure + + mixing_ratio : `pint.Quantity` + Mixing ratio values corresponding to pressure + + surface_pressure : `pint.Quantity` + Pressure of the surface. + + vertical_dim : int, optional + The axis corresponding to vertical, defaults to 0. Automatically determined from + xarray DataArray arguments. + + Returns + ------- + `pint.Quantity` + GDI Index + + Examples + -------- + >>> from metpy.calc import mixing_ratio_from_relative_humidity + >>> from metpy.units import units + >>> # pressure + >>> p = [1008., 1000., 950., 900., 850., 800., 750., 700., 650., 600., + ... 550., 500., 450., 400., 350., 300., 250., 200., + ... 175., 150., 125., 100., 80., 70., 60., 50., + ... 40., 30., 25., 20.] * units.hPa + >>> # temperature + >>> T = [29.3, 28.1, 23.5, 20.9, 18.4, 15.9, 13.1, 10.1, 6.7, 3.1, + ... -0.5, -4.5, -9.0, -14.8, -21.5, -29.7, -40.0, -52.4, + ... -59.2, -66.5, -74.1, -78.5, -76.0, -71.6, -66.7, -61.3, + ... -56.3, -51.7, -50.7, -47.5] * units.degC + >>> # relative humidity + >>> rh = [.85, .65, .36, .39, .82, .72, .75, .86, .65, .22, .52, + ... .66, .64, .20, .05, .75, .76, .45, .25, .48, .76, .88, + ... .56, .88, .39, .67, .15, .04, .94, .35] * units.dimensionless + >>> # calculate mixing ratio + >>> mixrat = mixing_ratio_from_relative_humidity(p, T, rh) + >>> galvez_davison_index(p, T, mixrat, p[0]) + <Quantity(-8.78797532, 'dimensionless')> + """ + if np.any(np.max(pressure, axis=vertical_dim) < 950 * units.hectopascal): + indices_without_950 = np.where( + np.max(pressure, axis=vertical_dim) < 950 * units.hectopascal + ) + raise ValueError( + f'Data not provided for 950hPa or higher pressure. ' + f'GDI requires 950hPa temperature and dewpoint data, ' + f'see referenced paper section 3.d. in docstring for discussion of' + f' extrapolating sounding data below terrain surface in high-' + f'elevation regions.\nIndices without a 950hPa or higher datapoint' + f':\n{indices_without_950}' + f'\nMax provided pressures:' + f'\n{np.max(pressure, axis=0)[indices_without_950]}' + ) + + potential_temp = potential_temperature(pressure, temperature) + + # Interpolate to appropriate level with appropriate units + ( + (t950, t850, t700, t500), + (r950, r850, r700, r500), + (th950, th850, th700, th500) + ) = interpolate_1d( + units.Quantity([950, 850, 700, 500], 'hPa'), + pressure, temperature.to('K'), mixing_ratio, potential_temp.to('K'), + axis=vertical_dim, + ) + + # L_v definition preserved from referenced paper + # Value differs heavily from metpy.constants.Lv in tropical context + # and using MetPy value affects resulting GDI + l_0 = units.Quantity(2.69e6, 'J/kg') + + # Calculate adjusted equivalent potential temperatures + alpha = units.Quantity(-10, 'K') + eptp_a = th950 * np.exp(l_0 * r950 / (mpconsts.Cp_d * t850)) + eptp_b = ((th850 + th700) / 2 + * np.exp(l_0 * (r850 + r700) / 2 / (mpconsts.Cp_d * t850)) + alpha) + eptp_c = th500 * np.exp(l_0 * r500 / (mpconsts.Cp_d * t850)) + alpha + + # Calculate Column Buoyanci Index (CBI) + # Apply threshold to low and mid levels + beta = units.Quantity(303, 'K') + l_e = eptp_a - beta + m_e = eptp_c - beta + + # Gamma unit - likely a typo from the paper, should be units of K^(-2) to + # result in dimensionless CBI + gamma = units.Quantity(6.5e-2, '1/K^2') + + column_buoyancy_index = np.atleast_1d(gamma * l_e * m_e) + column_buoyancy_index[l_e <= 0] = 0 + + # Calculate Mid-tropospheric Warming Index (MWI) + # Apply threshold to 500-hPa temperature + tau = units.Quantity(263.15, 'K') + t_diff = t500 - tau + + mu = units.Quantity(-7, '1/K') # Empirical adjustment + mid_tropospheric_warming_index = np.atleast_1d(mu * t_diff) + mid_tropospheric_warming_index[t_diff <= 0] = 0 + + # Calculate Inversion Index (II) + s = t950 - t700 + d = eptp_b - eptp_a + inv_sum = s + d + + sigma = units.Quantity(1.5, '1/K') # Empirical scaling constant + inversion_index = np.atleast_1d(sigma * inv_sum) + inversion_index[inv_sum >= 0] = 0 + + # Calculate Terrain Correction + terrain_correction = 18 - 9000 / (surface_pressure.m_as('hPa') - 500) + + # Calculate G.D.I. + gdi = (column_buoyancy_index + + mid_tropospheric_warming_index + + inversion_index + + terrain_correction) + + if gdi.size == 1: + return gdi[0] + else: + return gdi + + @exporter.export @add_vertical_dim_from_xarray @preprocess_and_wrap(
Unidata/MetPy
e0e24d51702787943fc3c0481fa9a6632abe9d20
diff --git a/tests/calc/test_thermo.py b/tests/calc/test_thermo.py index ea97646d49..4cd9c60749 100644 --- a/tests/calc/test_thermo.py +++ b/tests/calc/test_thermo.py @@ -37,7 +37,7 @@ from metpy.calc import (brunt_vaisala_frequency, brunt_vaisala_frequency_squared vertical_velocity_pressure, virtual_potential_temperature, virtual_temperature, virtual_temperature_from_dewpoint, wet_bulb_potential_temperature, wet_bulb_temperature) -from metpy.calc.thermo import _find_append_zero_crossings +from metpy.calc.thermo import _find_append_zero_crossings, galvez_davison_index from metpy.testing import (assert_almost_equal, assert_array_almost_equal, assert_nan, version_check) from metpy.units import is_quantity, masked_array, units @@ -2309,6 +2309,50 @@ def index_xarray_data(): coords={'isobaric': pressure, 'time': ['2020-01-01T00:00Z']}) [email protected]() +def index_xarray_data_expanded(): + """Create expanded data for testing that index calculations work with xarray data. + + Specifically for Galvez Davison Index calculation, which requires 950hPa pressure + """ + pressure = xr.DataArray( + [950., 850., 700., 500.], dims=('isobaric',), attrs={'units': 'hPa'} + ) + temp = xr.DataArray([[[[306., 305., 304.], [303., 302., 301.]], + [[296., 295., 294.], [293., 292., 291.]], + [[286., 285., 284.], [283., 282., 281.]], + [[276., 275., 274.], [273., 272., 271.]]]] * units.K, + dims=('time', 'isobaric', 'y', 'x')) + + profile = xr.DataArray([[[[299., 298., 297.], [296., 295., 294.]], + [[289., 288., 287.], [286., 285., 284.]], + [[279., 278., 277.], [276., 275., 274.]], + [[269., 268., 267.], [266., 265., 264.]]]] * units.K, + dims=('time', 'isobaric', 'y', 'x')) + + dewp = xr.DataArray([[[[304., 303., 302.], [301., 300., 299.]], + [[294., 293., 292.], [291., 290., 289.]], + [[284., 283., 282.], [281., 280., 279.]], + [[274., 273., 272.], [271., 270., 269.]]]] * units.K, + dims=('time', 'isobaric', 'y', 'x')) + + dirw = xr.DataArray([[[[135., 135., 135.], [135., 135., 135.]], + [[180., 180., 180.], [180., 180., 180.]], + [[225., 225., 225.], [225., 225., 225.]], + [[270., 270., 270.], [270., 270., 270.]]]] * units.degree, + dims=('time', 'isobaric', 'y', 'x')) + + speed = xr.DataArray([[[[15., 15., 15.], [15., 15., 15.]], + [[20., 20., 20.], [20., 20., 20.]], + [[25., 25., 25.], [25., 25., 25.]], + [[50., 50., 50.], [50., 50., 50.]]]] * units.knots, + dims=('time', 'isobaric', 'y', 'x')) + + return xr.Dataset({'temperature': temp, 'profile': profile, 'dewpoint': dewp, + 'wind_direction': dirw, 'wind_speed': speed}, + coords={'isobaric': pressure, 'time': ['2023-01-01T00:00Z']}) + + def test_lifted_index(): """Test the Lifted Index calculation.""" pressure = np.array([1014., 1000., 997., 981.2, 947.4, 925., 914.9, 911., @@ -2398,6 +2442,109 @@ def test_k_index_xarray(index_xarray_data): np.array([[[312., 311., 310.], [309., 308., 307.]]]) * units.K) +def test_gdi(): + """Test the Galvez Davison Index calculation.""" + pressure = np.array([1014., 1000., 997., 981.2, 947.4, 925., 914.9, 911., + 902., 883., 850., 822.3, 816., 807., 793.2, 770., + 765.1, 753., 737.5, 737., 713., 700., 688., 685., + 680., 666., 659.8, 653., 643., 634., 615., 611.8, + 566.2, 516., 500., 487., 484.2, 481., 475., 460., + 400.]) * units.hPa + temperature = np.array([24.2, 24.2, 24., 23.1, 21., 19.6, 18.7, 18.4, + 19.2, 19.4, 17.2, 15.3, 14.8, 14.4, 13.4, 11.6, + 11.1, 10., 8.8, 8.8, 8.2, 7., 5.6, 5.6, + 5.6, 4.4, 3.8, 3.2, 3., 3.2, 1.8, 1.5, + -3.4, -9.3, -11.3, -13.1, -13.1, -13.1, -13.7, -15.1, + -23.5]) * units.degC + dewpoint = np.array([23.2, 23.1, 22.8, 22., 20.2, 19., 17.6, 17., + 16.8, 15.5, 14., 11.7, 11.2, 8.4, 7., 4.6, + 5., 6., 4.2, 4.1, -1.8, -2., -1.4, -0.4, + -3.4, -5.6, -4.3, -2.8, -7., -25.8, -31.2, -31.4, + -34.1, -37.3, -32.3, -34.1, -37.3, -41.1, -37.7, -58.1, + -57.5]) * units.degC + + relative_humidity = relative_humidity_from_dewpoint(temperature, dewpoint) + mixrat = mixing_ratio_from_relative_humidity(pressure, temperature, relative_humidity) + gdi = galvez_davison_index(pressure, temperature, mixrat, pressure[0]) + + # Compare with value from hand calculation + assert_almost_equal(gdi, 6.635, decimal=1) + + +def test_gdi_xarray(index_xarray_data_expanded): + """Test the GDI calculation with a grid of xarray data.""" + pressure = index_xarray_data_expanded.isobaric + temperature = index_xarray_data_expanded.temperature + dewpoint = index_xarray_data_expanded.dewpoint + mixing_ratio = mixing_ratio_from_relative_humidity( + pressure, temperature, relative_humidity_from_dewpoint(temperature, dewpoint)) + + result = galvez_davison_index( + pressure, + temperature, + mixing_ratio, + pressure[0] + ) + + assert_array_almost_equal( + result, + np.array([[[189.5890429, 157.4307982, 129.9739099], + [106.6763526, 87.0637477, 70.7202505]]]) + ) + + +def test_gdi_arrays(index_xarray_data_expanded): + """Test GDI on 3-D Quantity arrays with an array of surface pressure.""" + ds = index_xarray_data_expanded.isel(time=0).squeeze() + pressure = ds.isobaric.metpy.unit_array[:, None, None] + temperature = ds.temperature.metpy.unit_array + dewpoint = ds.dewpoint.metpy.unit_array + mixing_ratio = mixing_ratio_from_relative_humidity( + pressure, temperature, relative_humidity_from_dewpoint(temperature, dewpoint)) + surface_pressure = units.Quantity( + np.broadcast_to(pressure.m, temperature.shape), pressure.units)[0] + + result = galvez_davison_index(pressure, temperature, mixing_ratio, surface_pressure) + + assert_array_almost_equal( + result, + np.array([[189.5890429, 157.4307982, 129.9739099], + [106.6763526, 87.0637477, 70.7202505]]) + ) + + +def test_gdi_profile(index_xarray_data_expanded): + """Test GDI calculation on an individual profile.""" + ds = index_xarray_data_expanded.isel(time=0, y=0, x=0) + pressure = ds.isobaric.metpy.unit_array + temperature = ds.temperature.metpy.unit_array + dewpoint = ds.dewpoint.metpy.unit_array + mixing_ratio = mixing_ratio_from_relative_humidity( + pressure, temperature, relative_humidity_from_dewpoint(temperature, dewpoint)) + + assert_almost_equal(galvez_davison_index(pressure, temperature, mixing_ratio, pressure[0]), + 189.5890429, 4) + + +def test_gdi_no_950_raises_valueerror(index_xarray_data): + """GDI requires a 950hPa or higher measurement. + + Ensure error is raised if this data is not provided. + """ + with pytest.raises(ValueError): + pressure = index_xarray_data.isobaric + temperature = index_xarray_data.temperature + dewpoint = index_xarray_data.dewpoint + relative_humidity = relative_humidity_from_dewpoint(temperature, dewpoint) + mixrat = mixing_ratio_from_relative_humidity(pressure, temperature, relative_humidity) + galvez_davison_index( + pressure, + temperature, + mixrat, + pressure[0] + ) + + def test_gradient_richardson_number(): """Test gradient Richardson number calculation.""" theta = units('K') * np.asarray([254.5, 258.3, 262.2])
Please add GDI (Galvez Davison Index) for tropical convection ### What should we add? Hi, the[ GDI](https://www.wpc.ncep.noaa.gov/international/gdi/) is a relative new index what calculate the convective potential and is widely used ritgh now in América, Galvez and Davision are from NOAA International Desks, please add it to metpy. More info abut the index calculation are here: https://www.wpc.ncep.noaa.gov/international/gdi/GDI_Manuscript_V20161021.pdf Here is my code to calculate GDI in GrADS lenguage from my repository: https://github.com/joseamidesfigueroa/GDI ### Reference _No response_
0.0
e0e24d51702787943fc3c0481fa9a6632abe9d20
[ "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint", "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint_with_f", "tests/calc/test_thermo.py::test_relative_humidity_from_dewpoint_xarray", "tests/calc/test_thermo.py::test_exner_function", "tests/calc/test_thermo.py::test_potential_temperature", "tests/calc/test_thermo.py::test_temperature_from_potential_temperature", "tests/calc/test_thermo.py::test_pot_temp_scalar", "tests/calc/test_thermo.py::test_pot_temp_fahrenheit", "tests/calc/test_thermo.py::test_pot_temp_inhg", "tests/calc/test_thermo.py::test_dry_lapse", "tests/calc/test_thermo.py::test_dry_lapse_2_levels", "tests/calc/test_thermo.py::test_moist_lapse[degF]", "tests/calc/test_thermo.py::test_moist_lapse[degC]", "tests/calc/test_thermo.py::test_moist_lapse[K]", "tests/calc/test_thermo.py::test_moist_lapse_ref_pressure", "tests/calc/test_thermo.py::test_moist_lapse_multiple_temps", "tests/calc/test_thermo.py::test_moist_lapse_scalar", "tests/calc/test_thermo.py::test_moist_lapse_close_start", "tests/calc/test_thermo.py::test_moist_lapse_uniform", "tests/calc/test_thermo.py::test_moist_lapse_nan_temp", "tests/calc/test_thermo.py::test_moist_lapse_nan_ref_press", "tests/calc/test_thermo.py::test_moist_lapse_downwards", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[0-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[0--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[1-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[1--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[2-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[2--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[3-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[3--1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[4-1]", "tests/calc/test_thermo.py::test_moist_lapse_starting_points[4--1]", "tests/calc/test_thermo.py::test_moist_lapse_failure", "tests/calc/test_thermo.py::test_parcel_profile", "tests/calc/test_thermo.py::test_parcel_profile_lcl", "tests/calc/test_thermo.py::test_parcel_profile_lcl_not_monotonic", "tests/calc/test_thermo.py::test_parcel_profile_with_lcl_as_dataset", "tests/calc/test_thermo.py::test_parcel_profile_saturated", "tests/calc/test_thermo.py::test_sat_vapor_pressure", "tests/calc/test_thermo.py::test_sat_vapor_pressure_scalar", "tests/calc/test_thermo.py::test_sat_vapor_pressure_fahrenheit", "tests/calc/test_thermo.py::test_basic_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_scalar_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_percent_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_warning_dewpoint_from_relative_humidity", "tests/calc/test_thermo.py::test_dewpoint", "tests/calc/test_thermo.py::test_dewpoint_weird_units", "tests/calc/test_thermo.py::test_mixing_ratio", "tests/calc/test_thermo.py::test_vapor_pressure", "tests/calc/test_thermo.py::test_lcl", "tests/calc/test_thermo.py::test_lcl_kelvin", "tests/calc/test_thermo.py::test_lcl_convergence", "tests/calc/test_thermo.py::test_lcl_nans", "tests/calc/test_thermo.py::test_ccl_basic", "tests/calc/test_thermo.py::test_ccl_nans", "tests/calc/test_thermo.py::test_ccl_unit", "tests/calc/test_thermo.py::test_multiple_ccl", "tests/calc/test_thermo.py::test_ccl_with_ml", "tests/calc/test_thermo.py::test_lfc_basic", "tests/calc/test_thermo.py::test_lfc_kelvin", "tests/calc/test_thermo.py::test_lfc_ml", "tests/calc/test_thermo.py::test_lfc_ml2", "tests/calc/test_thermo.py::test_lfc_intersection", "tests/calc/test_thermo.py::test_no_lfc", "tests/calc/test_thermo.py::test_lfc_inversion", "tests/calc/test_thermo.py::test_lfc_equals_lcl", "tests/calc/test_thermo.py::test_lfc_profile_nan", "tests/calc/test_thermo.py::test_lfc_profile_nan_with_parcel_profile", "tests/calc/test_thermo.py::test_sensitive_sounding", "tests/calc/test_thermo.py::test_lfc_sfc_precision", "tests/calc/test_thermo.py::test_lfc_pos_area_below_lcl", "tests/calc/test_thermo.py::test_saturation_mixing_ratio", "tests/calc/test_thermo.py::test_saturation_mixing_ratio_with_xarray", "tests/calc/test_thermo.py::test_equivalent_potential_temperature", "tests/calc/test_thermo.py::test_equivalent_potential_temperature_masked", "tests/calc/test_thermo.py::test_wet_bulb_potential_temperature", "tests/calc/test_thermo.py::test_saturation_equivalent_potential_temperature", "tests/calc/test_thermo.py::test_saturation_equivalent_potential_temperature_masked", "tests/calc/test_thermo.py::test_virtual_temperature", "tests/calc/test_thermo.py::test_virtual_temperature_from_dewpoint", "tests/calc/test_thermo.py::test_virtual_potential_temperature", "tests/calc/test_thermo.py::test_density", "tests/calc/test_thermo.py::test_el", "tests/calc/test_thermo.py::test_el_kelvin", "tests/calc/test_thermo.py::test_el_ml", "tests/calc/test_thermo.py::test_no_el", "tests/calc/test_thermo.py::test_no_el_multi_crossing", "tests/calc/test_thermo.py::test_lfc_and_el_below_lcl", "tests/calc/test_thermo.py::test_el_lfc_equals_lcl", "tests/calc/test_thermo.py::test_el_small_surface_instability", "tests/calc/test_thermo.py::test_no_el_parcel_colder", "tests/calc/test_thermo.py::test_el_below_lcl", "tests/calc/test_thermo.py::test_el_profile_nan", "tests/calc/test_thermo.py::test_el_profile_nan_with_parcel_profile", "tests/calc/test_thermo.py::test_wet_psychrometric_vapor_pressure", "tests/calc/test_thermo.py::test_wet_psychrometric_rh", "tests/calc/test_thermo.py::test_wet_psychrometric_rh_kwargs", "tests/calc/test_thermo.py::test_mixing_ratio_from_relative_humidity", "tests/calc/test_thermo.py::test_rh_mixing_ratio", "tests/calc/test_thermo.py::test_mixing_ratio_from_specific_humidity", "tests/calc/test_thermo.py::test_mixing_ratio_from_specific_humidity_no_units", "tests/calc/test_thermo.py::test_specific_humidity_from_mixing_ratio", "tests/calc/test_thermo.py::test_specific_humidity_from_mixing_ratio_no_units", "tests/calc/test_thermo.py::test_rh_specific_humidity", "tests/calc/test_thermo.py::test_cape_cin", "tests/calc/test_thermo.py::test_cape_cin_no_el", "tests/calc/test_thermo.py::test_cape_cin_no_lfc", "tests/calc/test_thermo.py::test_find_append_zero_crossings", "tests/calc/test_thermo.py::test_most_unstable_parcel", "tests/calc/test_thermo.py::test_isentropic_pressure", "tests/calc/test_thermo.py::test_isentropic_pressure_masked_column", "tests/calc/test_thermo.py::test_isentropic_pressure_p_increase", "tests/calc/test_thermo.py::test_isentropic_pressure_additional_args", "tests/calc/test_thermo.py::test_isentropic_pressure_tmp_out", "tests/calc/test_thermo.py::test_isentropic_pressure_p_increase_rh_out", "tests/calc/test_thermo.py::test_isentropic_pressure_interp[False]", "tests/calc/test_thermo.py::test_isentropic_pressure_addition_args_interp", "tests/calc/test_thermo.py::test_isentropic_pressure_tmp_out_interp", "tests/calc/test_thermo.py::test_isentropic_pressure_data_bounds_error", "tests/calc/test_thermo.py::test_isentropic_pressure_4d", "tests/calc/test_thermo.py::test_isentropic_interpolation_dataarray", "tests/calc/test_thermo.py::test_isentropic_interpolation_as_dataset", "tests/calc/test_thermo.py::test_isentropic_interpolation_as_dataset_duplicate", "tests/calc/test_thermo.py::test_isen_interpolation_as_dataset_non_pressure_default", "tests/calc/test_thermo.py::test_isen_interpolation_as_dataset_passing_pressre", "tests/calc/test_thermo.py::test_surface_based_cape_cin[Quantity]", "tests/calc/test_thermo.py::test_surface_based_cape_cin[masked_array]", "tests/calc/test_thermo.py::test_surface_based_cape_cin_with_xarray", "tests/calc/test_thermo.py::test_profile_with_nans", "tests/calc/test_thermo.py::test_most_unstable_cape_cin_surface", "tests/calc/test_thermo.py::test_most_unstable_cape_cin", "tests/calc/test_thermo.py::test_mixed_parcel", "tests/calc/test_thermo.py::test_mixed_layer_cape_cin", "tests/calc/test_thermo.py::test_mixed_layer_cape_cin_bottom_pressure", "tests/calc/test_thermo.py::test_dcape", "tests/calc/test_thermo.py::test_mixed_layer", "tests/calc/test_thermo.py::test_dry_static_energy", "tests/calc/test_thermo.py::test_moist_static_energy", "tests/calc/test_thermo.py::test_thickness_hydrostatic", "tests/calc/test_thermo.py::test_thickness_hydrostatic_subset", "tests/calc/test_thermo.py::test_thickness_hydrostatic_isothermal", "tests/calc/test_thermo.py::test_thickness_hydrostatic_isothermal_subset", "tests/calc/test_thermo.py::test_thickness_hydrostatic_from_relative_humidity", "tests/calc/test_thermo.py::test_mixing_ratio_dimensions", "tests/calc/test_thermo.py::test_saturation_mixing_ratio_dimensions", "tests/calc/test_thermo.py::test_mixing_ratio_from_rh_dimensions", "tests/calc/test_thermo.py::test_brunt_vaisala_frequency_squared", "tests/calc/test_thermo.py::test_brunt_vaisala_frequency", "tests/calc/test_thermo.py::test_brunt_vaisala_period", "tests/calc/test_thermo.py::test_wet_bulb_temperature[degF]", "tests/calc/test_thermo.py::test_wet_bulb_temperature[degC]", "tests/calc/test_thermo.py::test_wet_bulb_temperature[K]", "tests/calc/test_thermo.py::test_wet_bulb_temperature_saturated", "tests/calc/test_thermo.py::test_wet_bulb_temperature_numpy_scalars", "tests/calc/test_thermo.py::test_wet_bulb_temperature_1d", "tests/calc/test_thermo.py::test_wet_bulb_temperature_2d", "tests/calc/test_thermo.py::test_wet_bulb_nan[degF]", "tests/calc/test_thermo.py::test_wet_bulb_nan[degC]", "tests/calc/test_thermo.py::test_wet_bulb_nan[K]", "tests/calc/test_thermo.py::test_static_stability_adiabatic", "tests/calc/test_thermo.py::test_static_stability_cross_section", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_old_signature", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_kwargs", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_three_mixed_args_kwargs", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_two_mixed_args_kwargs", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_two_args", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_arrays", "tests/calc/test_thermo.py::test_dewpoint_specific_humidity_xarray", "tests/calc/test_thermo.py::test_lfc_not_below_lcl", "tests/calc/test_thermo.py::test_multiple_lfcs_simple", "tests/calc/test_thermo.py::test_multiple_lfs_wide", "tests/calc/test_thermo.py::test_invalid_which", "tests/calc/test_thermo.py::test_multiple_els_simple", "tests/calc/test_thermo.py::test_multiple_el_wide", "tests/calc/test_thermo.py::test_muliple_el_most_cape", "tests/calc/test_thermo.py::test_muliple_lfc_most_cape", "tests/calc/test_thermo.py::test_el_lfc_most_cape_bottom", "tests/calc/test_thermo.py::test_cape_cin_top_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_bottom_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_wide_el_lfc", "tests/calc/test_thermo.py::test_cape_cin_custom_profile", "tests/calc/test_thermo.py::test_parcel_profile_below_lcl", "tests/calc/test_thermo.py::test_vertical_velocity_pressure_dry_air", "tests/calc/test_thermo.py::test_vertical_velocity_dry_air", "tests/calc/test_thermo.py::test_vertical_velocity_pressure_moist_air", "tests/calc/test_thermo.py::test_vertical_velocity_moist_air", "tests/calc/test_thermo.py::test_specific_humidity_from_dewpoint", "tests/calc/test_thermo.py::test_specific_humidity_from_dewpoint_versionchanged", "tests/calc/test_thermo.py::test_lcl_convergence_issue", "tests/calc/test_thermo.py::test_cape_cin_value_error", "tests/calc/test_thermo.py::test_lcl_grid_surface_lcls", "tests/calc/test_thermo.py::test_lifted_index", "tests/calc/test_thermo.py::test_lifted_index_500hpa_missing", "tests/calc/test_thermo.py::test_lifted_index_xarray", "tests/calc/test_thermo.py::test_k_index", "tests/calc/test_thermo.py::test_k_index_xarray", "tests/calc/test_thermo.py::test_gdi", "tests/calc/test_thermo.py::test_gdi_xarray", "tests/calc/test_thermo.py::test_gdi_arrays", "tests/calc/test_thermo.py::test_gdi_profile", "tests/calc/test_thermo.py::test_gdi_no_950_raises_valueerror", "tests/calc/test_thermo.py::test_gradient_richardson_number", "tests/calc/test_thermo.py::test_gradient_richardson_number_with_xarray", "tests/calc/test_thermo.py::test_showalter_index", "tests/calc/test_thermo.py::test_total_totals_index", "tests/calc/test_thermo.py::test_total_totals_index_xarray", "tests/calc/test_thermo.py::test_vertical_totals", "tests/calc/test_thermo.py::test_vertical_totals_index_xarray", "tests/calc/test_thermo.py::test_cross_totals", "tests/calc/test_thermo.py::test_cross_totals_index_xarray", "tests/calc/test_thermo.py::test_parcel_profile_drop_duplicates", "tests/calc/test_thermo.py::test_parcel_profile_with_lcl_as_dataset_duplicates", "tests/calc/test_thermo.py::test_sweat_index_xarray" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-16 20:47:36+00:00
bsd-3-clause
812
Unidata__MetPy-3188
diff --git a/src/metpy/io/station_data.py b/src/metpy/io/station_data.py index 4db0f2ec5e..df7e153b5b 100644 --- a/src/metpy/io/station_data.py +++ b/src/metpy/io/station_data.py @@ -191,8 +191,9 @@ def add_station_lat_lon(df, stn_var=None): raise KeyError('Second argument not provided to add_station_lat_lon, but none of ' f'{names_to_try} were found.') - df['latitude'] = None - df['longitude'] = None + df['latitude'] = np.nan + df['longitude'] = np.nan + if stn_var is None: stn_var = key_finder(df) for stn in df[stn_var].unique():
Unidata/MetPy
1a53dd232914227555ccc0e4a98a1d90a287f006
diff --git a/tests/io/test_station_data.py b/tests/io/test_station_data.py index 7e0e9b0d70..a281ad830d 100644 --- a/tests/io/test_station_data.py +++ b/tests/io/test_station_data.py @@ -23,6 +23,7 @@ def test_add_lat_lon_station_data(): assert_almost_equal(df.loc[df.station == 'KDEN'].longitude.values[0], -104.65) assert_almost_equal(df.loc[df.station == 'PAAA'].latitude.values[0], np.nan) assert_almost_equal(df.loc[df.station == 'PAAA'].longitude.values[0], np.nan) + assert df['longitude'].dtype == np.float64 def test_add_lat_lon_station_data_optional():
add_station_lat_lon yields columns with object dtype ```python df = pd.DataFrame({'station': ['KOUN', 'KVPZ', 'KDEN', 'PAAA']}) df = add_station_lat_lon(df, 'station') df.info() ``` gives ``` <class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 station 4 non-null object 1 latitude 3 non-null object 2 longitude 3 non-null object dtypes: object(3) memory usage: 224.0+ bytes ``` Apparently it's good enough to pass e.g. `assert_almost_equal(df.loc[df.station == 'KOUN'].latitude.values[0], 35.25)`, but it's painful to pass to e.g. `tricontour()`.
0.0
1a53dd232914227555ccc0e4a98a1d90a287f006
[ "tests/io/test_station_data.py::test_add_lat_lon_station_data" ]
[ "tests/io/test_station_data.py::test_add_lat_lon_station_data_optional", "tests/io/test_station_data.py::test_add_lat_lon_station_data_not_found", "tests/io/test_station_data.py::test_station_lookup_get_station", "tests/io/test_station_data.py::test_station_lookup_len", "tests/io/test_station_data.py::test_station_lookup_iter" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-09-12 22:20:24+00:00
bsd-3-clause
813
Unidata__MetPy-3437
diff --git a/ci/extra_requirements.txt b/ci/extra_requirements.txt index 70a45f6230..590f2f0b2f 100644 --- a/ci/extra_requirements.txt +++ b/ci/extra_requirements.txt @@ -1,3 +1,3 @@ cartopy==0.22.0 -dask==2024.3.0 +dask==2024.3.1 shapely==2.0.3 diff --git a/ci/linting_requirements.txt b/ci/linting_requirements.txt index a67d1f70f0..1d739578d5 100644 --- a/ci/linting_requirements.txt +++ b/ci/linting_requirements.txt @@ -1,4 +1,4 @@ -ruff==0.3.2 +ruff==0.3.3 flake8==7.0.0 pycodestyle==2.11.1 diff --git a/src/metpy/calc/basic.py b/src/metpy/calc/basic.py index 0e164e1b04..a290e3df12 100644 --- a/src/metpy/calc/basic.py +++ b/src/metpy/calc/basic.py @@ -52,6 +52,13 @@ def wind_speed(u, v): -------- wind_components + Examples + -------- + >>> from metpy.calc import wind_speed + >>> from metpy.units import units + >>> wind_speed(10. * units('m/s'), 10. * units('m/s')) + <Quantity(14.1421356, 'meter / second')> + """ return np.hypot(u, v) @@ -88,6 +95,13 @@ def wind_direction(u, v, convention='from'): In the case of calm winds (where `u` and `v` are zero), this function returns a direction of 0. + Examples + -------- + >>> from metpy.calc import wind_direction + >>> from metpy.units import units + >>> wind_direction(10. * units('m/s'), 10. * units('m/s')) + <Quantity(225.0, 'degree')> + """ wdir = units.Quantity(90., 'deg') - np.arctan2(-v, -u) origshape = wdir.shape @@ -141,7 +155,7 @@ def wind_components(speed, wind_direction): >>> from metpy.calc import wind_components >>> from metpy.units import units >>> wind_components(10. * units('m/s'), 225. * units.deg) - (<Quantity(7.07106781, 'meter / second')>, <Quantity(7.07106781, 'meter / second')>) + (<Quantity(7.07106781, 'meter / second')>, <Quantity(7.07106781, 'meter / second')>) .. versionchanged:: 1.0 Renamed ``wdir`` parameter to ``wind_direction`` diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index c34453c8f3..12640a6561 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1825,6 +1825,13 @@ def angle_to_direction(input_angle, full=False, level=3): direction The directional text + Examples + -------- + >>> from metpy.calc import angle_to_direction + >>> from metpy.units import units + >>> angle_to_direction(225. * units.deg) + 'SW' + """ try: # strip units temporarily origin_units = input_angle.units diff --git a/src/metpy/xarray.py b/src/metpy/xarray.py index 2ccb36ce0a..ab16f76802 100644 --- a/src/metpy/xarray.py +++ b/src/metpy/xarray.py @@ -338,15 +338,16 @@ class MetPyDataArrayAccessor: def _generate_coordinate_map(self): """Generate a coordinate map via CF conventions and other methods.""" coords = self._data_array.coords.values() - # Parse all the coordinates, attempting to identify x, longitude, y, latitude, - # vertical, time - coord_lists = {'time': [], 'vertical': [], 'y': [], 'latitude': [], 'x': [], - 'longitude': []} + # Parse all the coordinates, attempting to identify longitude, latitude, x, y, + # time, vertical, in that order. + coord_lists = {'longitude': [], 'latitude': [], 'x': [], 'y': [], 'time': [], + 'vertical': []} for coord_var in coords: # Identify the coordinate type using check_axis helper for axis in coord_lists: if check_axis(coord_var, axis): coord_lists[axis].append(coord_var) + break # Ensure a coordinate variable only goes to one axis # Fill in x/y with longitude/latitude if x/y not otherwise present for geometric, graticule in (('y', 'latitude'), ('x', 'longitude')):
Unidata/MetPy
8f510ae51fe0478ba208711bb7468efca0296ade
diff --git a/ci/test_requirements.txt b/ci/test_requirements.txt index 4302ff9e96..61b6ff44b9 100644 --- a/ci/test_requirements.txt +++ b/ci/test_requirements.txt @@ -2,4 +2,4 @@ packaging==24.0 pytest==8.1.1 pytest-mpl==0.17.0 netCDF4==1.6.5 -coverage==7.4.3 +coverage==7.4.4 diff --git a/tests/test_xarray.py b/tests/test_xarray.py index a5364f327b..2571944f80 100644 --- a/tests/test_xarray.py +++ b/tests/test_xarray.py @@ -273,6 +273,14 @@ def test_missing_grid_mapping_invalid(test_var_multidim_no_xy): assert 'metpy_crs' not in data_var.coords +def test_xy_not_vertical(test_ds): + """Test not detecting x/y as a vertical coordinate based on metadata.""" + test_ds.x.attrs['positive'] = 'up' + test_ds.y.attrs['positive'] = 'up' + data_var = test_ds.metpy.parse_cf('Temperature') + assert data_var.metpy.vertical.identical(data_var.coords['isobaric']) + + def test_missing_grid_mapping_var(caplog): """Test behavior when we can't find the variable pointed to by grid_mapping.""" x = xr.DataArray(np.arange(3),
mpcalc.isentropic_interpolation_as_dataset "vertical attribute is not available." I get an error "vertical attribute is not available." when interpolating bitwise vortices to isentropic surfaces using the mpcalc.isentropic_interpolation_as_dataset function.Here's the code and the specifics of the error reported: ```python f=xr.open_dataset(r'H:\data\dust\daily_atmosphere_data\daily_mean_era5_pv0.5_198604.nc') f_1=xr.open_dataset(r'H:\data\dust\daily_atmosphere_data\daily_mean_era5_t0.5_198604.nc') pv=f.pv.loc['1986-04-01',100000:20000,20:60,30:150] # (level,lat,lon) t=f_1.t.loc['1986-04-01',100000:20000,20:60,30:150]# (level,lat,lon) print(t,pv) isentlevs = [345.] * units.kelvin print(isen_lev) isent_data = mpcalc.isentropic_interpolation_as_dataset(isentlevs, t, pv) ``` ``` C:\Users\Administrator\AppData\Local\Temp\ipykernel_8224\906077059.py:12: UserWarning: More than one vertical coordinate present for variable "t". isent_data = mpcalc.isentropic_interpolation_as_dataset(isentlevs, t, pv) ``` ```pytb --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [20], in <cell line: 12>() 10 print(isen_lev) 11 # 调用 isentropic_interpolation_as_dataset 函数 ---> 12 isent_data = mpcalc.isentropic_interpolation_as_dataset(isentlevs, t, pv) File G:\Anaconda\lib\site-packages\metpy\calc\thermo.py:2761, in isentropic_interpolation_as_dataset(levels, temperature, max_iters, eps, bottom_up_search, *args) 2756 all_args = xr.broadcast(temperature, *args) 2758 # Obtain result as list of Quantities 2759 ret = isentropic_interpolation( 2760 levels, -> 2761 all_args[0].metpy.vertical, 2762 all_args[0].metpy.unit_array, 2763 *(arg.metpy.unit_array for arg in all_args[1:]), 2764 vertical_dim=all_args[0].metpy.find_axis_number('vertical'), 2765 temperature_out=True, 2766 max_iters=max_iters, 2767 eps=eps, 2768 bottom_up_search=bottom_up_search 2769 ) 2771 # Reconstruct coordinates and dims (add isentropic levels, remove isobaric levels) 2772 vertical_dim = all_args[0].metpy.find_axis_name('vertical') File G:\Anaconda\lib\site-packages\metpy\xarray.py:486, in MetPyDataArrayAccessor.vertical(self) 483 @property 484 def vertical(self): 485 """Return the vertical coordinate.""" --> 486 return self._axis('vertical') File G:\Anaconda\lib\site-packages\metpy\xarray.py:418, in MetPyDataArrayAccessor._axis(self, axis) 416 coord_var = self._metpy_axis_search(axis) 417 if coord_var is None: --> 418 raise AttributeError(axis + ' attribute is not available.') 419 else: 420 return coord_var AttributeError: vertical attribute is not available. ```
0.0
8f510ae51fe0478ba208711bb7468efca0296ade
[ "tests/test_xarray.py::test_xy_not_vertical" ]
[ "tests/test_xarray.py::test_pyproj_projection", "tests/test_xarray.py::test_no_projection", "tests/test_xarray.py::test_unit_array", "tests/test_xarray.py::test_units", "tests/test_xarray.py::test_units_data", "tests/test_xarray.py::test_units_percent", "tests/test_xarray.py::test_magnitude_with_quantity", "tests/test_xarray.py::test_magnitude_without_quantity", "tests/test_xarray.py::test_convert_units", "tests/test_xarray.py::test_convert_to_base_units", "tests/test_xarray.py::test_convert_coordinate_units", "tests/test_xarray.py::test_latlon_default_units", "tests/test_xarray.py::test_quantify", "tests/test_xarray.py::test_dequantify", "tests/test_xarray.py::test_dataset_quantify", "tests/test_xarray.py::test_dataset_dequantify", "tests/test_xarray.py::test_radian_projection_coords", "tests/test_xarray.py::test_missing_grid_mapping_valid", "tests/test_xarray.py::test_missing_grid_mapping_invalid", "tests/test_xarray.py::test_missing_grid_mapping_var", "tests/test_xarray.py::test_parsecf_crs", "tests/test_xarray.py::test_parsecf_existing_scalar_crs", "tests/test_xarray.py::test_parsecf_existing_vector_crs", "tests/test_xarray.py::test_preprocess_and_wrap_only_preprocessing", "tests/test_xarray.py::test_coordinates_basic_by_method", "tests/test_xarray.py::test_coordinates_basic_by_property", "tests/test_xarray.py::test_coordinates_specified_by_name_with_dataset", "tests/test_xarray.py::test_coordinates_specified_by_dataarray_with_dataset", "tests/test_xarray.py::test_missing_coordinate_type", "tests/test_xarray.py::test_assign_coordinates_not_overwrite", "tests/test_xarray.py::test_resolve_axis_conflict_lonlat_and_xy", "tests/test_xarray.py::test_resolve_axis_conflict_double_lonlat", "tests/test_xarray.py::test_resolve_axis_conflict_double_xy", "tests/test_xarray.py::test_resolve_axis_conflict_double_x_with_single_dim", "tests/test_xarray.py::test_resolve_axis_conflict_double_vertical", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple0]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple1]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple2]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple3]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple4]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple5]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple6]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple7]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple8]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple9]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple10]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple11]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple12]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple13]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple14]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple15]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple16]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple17]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple18]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple19]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple20]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple21]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple22]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple23]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple24]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple25]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple26]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple27]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple28]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple29]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple30]", "tests/test_xarray.py::test_check_axis_criterion_match[test_tuple31]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple0]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple1]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple2]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple3]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple4]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple5]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple6]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple7]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple8]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple9]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple10]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple11]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple12]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple13]", "tests/test_xarray.py::test_check_axis_unit_match[test_tuple14]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple0]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple1]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple2]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple3]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple4]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple5]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple6]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple7]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple8]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple9]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple10]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple11]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple12]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple13]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple14]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple15]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple16]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple17]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple18]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple19]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple20]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple21]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple22]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple23]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple24]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple25]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple26]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple27]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple28]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple29]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple30]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple31]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple32]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple33]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple34]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple35]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple36]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple37]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple38]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple39]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple40]", "tests/test_xarray.py::test_check_axis_regular_expression_match[test_tuple41]", "tests/test_xarray.py::test_narr_example_variable_without_grid_mapping", "tests/test_xarray.py::test_coordinates_identical_true", "tests/test_xarray.py::test_coordinates_identical_false_number_of_coords", "tests/test_xarray.py::test_coordinates_identical_false_coords_mismatch", "tests/test_xarray.py::test_check_matching_coordinates", "tests/test_xarray.py::test_time_deltas", "tests/test_xarray.py::test_find_axis_name_integer", "tests/test_xarray.py::test_find_axis_name_axis_type", "tests/test_xarray.py::test_find_axis_name_dim_coord_name", "tests/test_xarray.py::test_find_axis_name_bad_identifier", "tests/test_xarray.py::test_find_axis_number_integer", "tests/test_xarray.py::test_find_axis_number_axis_type", "tests/test_xarray.py::test_find_axis_number_dim_coord_number", "tests/test_xarray.py::test_find_axis_number_bad_identifier", "tests/test_xarray.py::test_cf_parse_with_grid_mapping", "tests/test_xarray.py::test_data_array_loc_get_with_units", "tests/test_xarray.py::test_data_array_loc_set_with_units", "tests/test_xarray.py::test_data_array_loc_with_ellipsis", "tests/test_xarray.py::test_data_array_loc_non_tuple", "tests/test_xarray.py::test_data_array_loc_too_many_indices", "tests/test_xarray.py::test_data_array_sel_dict_with_units", "tests/test_xarray.py::test_data_array_sel_kwargs_with_units", "tests/test_xarray.py::test_dataset_loc_with_units", "tests/test_xarray.py::test_dataset_sel_kwargs_with_units", "tests/test_xarray.py::test_dataset_sel_non_dict_pos_arg", "tests/test_xarray.py::test_dataset_sel_mixed_dict_and_kwarg", "tests/test_xarray.py::test_dataset_loc_without_dict", "tests/test_xarray.py::test_dataset_parse_cf_keep_attrs", "tests/test_xarray.py::test_check_axis_with_bad_unit", "tests/test_xarray.py::test_dataset_parse_cf_varname_list", "tests/test_xarray.py::test_coordinate_identification_shared_but_not_equal_coords", "tests/test_xarray.py::test_one_dimensional_lat_lon", "tests/test_xarray.py::test_auxilary_lat_lon_with_xy", "tests/test_xarray.py::test_auxilary_lat_lon_without_xy", "tests/test_xarray.py::test_auxilary_lat_lon_without_xy_as_xy", "tests/test_xarray.py::test_assign_crs_error_with_both_attrs", "tests/test_xarray.py::test_assign_crs_error_with_neither_attrs", "tests/test_xarray.py::test_assign_latitude_longitude_no_horizontal", "tests/test_xarray.py::test_assign_y_x_no_horizontal", "tests/test_xarray.py::test_assign_latitude_longitude_basic_dataarray", "tests/test_xarray.py::test_assign_latitude_longitude_error_existing_dataarray", "tests/test_xarray.py::test_assign_latitude_longitude_force_existing_dataarray", "tests/test_xarray.py::test_assign_latitude_longitude_basic_dataset", "tests/test_xarray.py::test_assign_y_x_basic_dataarray", "tests/test_xarray.py::test_assign_y_x_error_existing_dataarray", "tests/test_xarray.py::test_assign_y_x_force_existing_dataarray", "tests/test_xarray.py::test_assign_y_x_dataarray_outside_tolerance", "tests/test_xarray.py::test_assign_y_x_dataarray_transposed", "tests/test_xarray.py::test_assign_y_x_dataset_assumed_order", "tests/test_xarray.py::test_assign_y_x_error_existing_dataset", "tests/test_xarray.py::test_update_attribute_dictionary", "tests/test_xarray.py::test_update_attribute_callable", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test0-other0-False-expected0]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test1-other1-True-expected1]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test2-other2-False-expected2]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test3-other3-True-expected3]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test4-other4-False-expected4]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test5-other5-True-expected5]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test6-other6-False-expected6]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test7-other7-True-expected7]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test8-other8-False-expected8]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test9-other9-True-expected9]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test10-other10-False-expected10]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test11-other11-False-expected11]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test12-other12-True-expected12]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test13-other13-False-expected13]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg[test14-other14-True-expected14]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg_raising_dimensionality_error[test0-other0]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg_raising_dimensionality_error[test1-other1]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg_raising_dimensionality_error[test2-other2]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg_raising_dimensionality_error[test3-other3]", "tests/test_xarray.py::test_wrap_with_wrap_like_kwarg_raising_dimensionality_error[test4-other4]", "tests/test_xarray.py::test_wrap_with_argument_kwarg", "tests/test_xarray.py::test_preprocess_and_wrap_with_broadcasting", "tests/test_xarray.py::test_preprocess_and_wrap_broadcasting_error", "tests/test_xarray.py::test_preprocess_and_wrap_with_to_magnitude", "tests/test_xarray.py::test_preprocess_and_wrap_with_variable", "tests/test_xarray.py::test_grid_deltas_from_dataarray_lonlat", "tests/test_xarray.py::test_grid_deltas_from_dataarray_xy", "tests/test_xarray.py::test_grid_deltas_from_dataarray_nominal_lonlat", "tests/test_xarray.py::test_grid_deltas_from_dataarray_lonlat_assumed_order", "tests/test_xarray.py::test_grid_deltas_from_dataarray_invalid_kind", "tests/test_xarray.py::test_add_vertical_dim_from_xarray" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-03-14 23:52:49+00:00
bsd-3-clause
814
ValvePython__steam-309
diff --git a/steam/core/crypto.py b/steam/core/crypto.py index 6fb2867..583bbde 100644 --- a/steam/core/crypto.py +++ b/steam/core/crypto.py @@ -6,7 +6,7 @@ from os import urandom as random_bytes from struct import pack from base64 import b64decode -from Cryptodome.Hash import SHA1, HMAC +from Cryptodome.Hash import MD5, SHA1, HMAC from Cryptodome.PublicKey.RSA import import_key as rsa_import_key, construct as rsa_construct from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5 from Cryptodome.Cipher import AES as AES @@ -96,6 +96,9 @@ def hmac_sha1(secret, data): def sha1_hash(data): return SHA1.new(data).digest() +def md5_hash(data): + return MD5.new(data).digest() + def rsa_publickey(mod, exp): return rsa_construct((mod, exp)) diff --git a/steam/steamid.py b/steam/steamid.py index 183c767..319d877 100644 --- a/steam/steamid.py +++ b/steam/steamid.py @@ -1,9 +1,11 @@ +import struct import json import sys import re import requests from steam.enums.base import SteamIntEnum from steam.enums import EType, EUniverse, EInstanceFlag +from steam.core.crypto import md5_hash from steam.utils.web import make_requests_session if sys.version_info < (3,): @@ -35,6 +37,7 @@ _icode_custom = "bcdfghjkmnpqrtvw" _icode_all_valid = _icode_hex + _icode_custom _icode_map = dict(zip(_icode_hex, _icode_custom)) _icode_map_inv = dict(zip(_icode_custom, _icode_hex )) +_csgofrcode_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' class SteamID(intBase): @@ -83,6 +86,14 @@ class SteamID(intBase): """ return int(self) & 0xFFffFFff + @property + def account_id(self): + """ + :return: account id + :rtype: :class:`int` + """ + return int(self) & 0xFFffFFff + @property def instance(self): """ @@ -197,6 +208,40 @@ class SteamID(intBase): return invite_code + @property + def as_csgo_friend_code(self): + """ + :return: CS:GO Friend code (e.g. ``AEBJA-ABDC``) + :rtype: :class:`str` + """ + if self.type != EType.Individual or not self.is_valid(): + return + + h = b'CSGO' + struct.pack('>L', self.account_id) + h, = struct.unpack('<L', md5_hash(h[::-1])[:4]) + steamid = self.as_64 + result = 0 + + for i in range(8): + id_nib = (steamid >> (i * 4)) & 0xF + hash_nib = (h >> i) & 0x1 + a = (result << 4) | id_nib + + result = ((result >> 28) << 32) | a + result = ((result >> 31) << 32) | ((a << 1) | hash_nib) + + result, = struct.unpack('<Q', struct.pack('>Q', result)) + code = '' + + for i in range(13): + if i in (4, 9): + code += '-' + + code += _csgofrcode_chars[result & 31] + result = result >> 5 + + return code[5:] + @property def invite_url(self): """ @@ -413,7 +458,7 @@ def steam3_to_tuple(value): return (steam32, etype, universe, instance) -def invite_code_to_tuple(code, universe=EUniverse.Public): +def from_invite_code(code, universe=EUniverse.Public): """ Invites urls can be generated at https://steamcommunity.com/my/friends/add @@ -441,7 +486,45 @@ def invite_code_to_tuple(code, universe=EUniverse.Public): accountid = int(re.sub("["+_icode_custom+"]", repl_mapper, code), 16) if 0 < accountid < 2**32: - return (accountid, EType(1), EUniverse(universe), 1) + return SteamID(accountid, EType.Individual, EUniverse(universe), 1) + +SteamID.from_invite_code = staticmethod(from_invite_code) + +def from_csgo_friend_code(code, universe=EUniverse.Public): + """ + Takes CS:GO friend code and returns SteamID + + :param code: CS:GO friend code (e.g. ``AEBJA-ABDC``) + :type code: :class:`str` + :param universe: Steam universe (default: ``Public``) + :type universe: :class:`EType` + :return: SteamID instance + :rtype: :class:`.SteamID` or :class:`None` + """ + if not re.match(r'^['+_csgofrcode_chars+'\-]{10}$', code): + return None + + code = ('AAAA-' + code).replace('-', '') + result = 0 + + for i in range(13): + index = _csgofrcode_chars.find(code[i]) + if index == -1: + return None + result = result | (index << 5 * i) + + result, = struct.unpack('<Q', struct.pack('>Q', result)) + accountid = 0 + + for i in range(8): + result = result >> 1 + id_nib = result & 0xF + result = result >> 4 + accountid = (accountid << 4) | id_nib + + return SteamID(accountid, EType.Individual, EUniverse(universe), 1) + +SteamID.from_csgo_friend_code = staticmethod(from_csgo_friend_code) def steam64_from_url(url, http_timeout=30): """
ValvePython/steam
caa7072cf0148d21593383e52ebd00a1ae8cf9ff
diff --git a/tests/test_steamid.py b/tests/test_steamid.py index b8e59a3..269a2cf 100644 --- a/tests/test_steamid.py +++ b/tests/test_steamid.py @@ -289,11 +289,22 @@ class SteamID_properties(unittest.TestCase): ) def test_as_invite_code(self): - self.assertEqual(SteamID(0 , EType.Individual, EUniverse.Public, instance=1).as_invite_code, None) - self.assertEqual(SteamID(123456, EType.Individual, EUniverse.Public, instance=1).as_invite_code, 'cv-dgb') - self.assertEqual(SteamID(123456, EType.Individual, EUniverse.Beta , instance=1).as_invite_code, 'cv-dgb') - self.assertEqual(SteamID(123456, EType.Invalid , EUniverse.Public, instance=1).as_invite_code, None) - self.assertEqual(SteamID(123456, EType.Clan , EUniverse.Public, instance=1).as_invite_code, None) + self.assertEqual(SteamID(0 , EType.Individual, EUniverse.Public, instance=1).as_invite_code, None) + self.assertEqual(SteamID(1 , EType.Invalid , EUniverse.Public, instance=1).as_invite_code, None) + self.assertEqual(SteamID(1 , EType.Clan , EUniverse.Public, instance=1).as_invite_code, None) + self.assertEqual(SteamID(1 , EType.Individual, EUniverse.Beta , instance=1).as_invite_code, 'c') + self.assertEqual(SteamID(1 , EType.Individual, EUniverse.Public, instance=1).as_invite_code, 'c') + self.assertEqual(SteamID(123456 , EType.Individual, EUniverse.Public, instance=1).as_invite_code, 'cv-dgb') + self.assertEqual(SteamID(4294967295, EType.Individual, EUniverse.Public, instance=1).as_invite_code, 'wwww-wwww') + + def test_as_csgo_friend_code(self): + self.assertEqual(SteamID(0 , EType.Individual, EUniverse.Public, instance=1).as_csgo_friend_code, None) + self.assertEqual(SteamID(1 , EType.Invalid , EUniverse.Public, instance=1).as_csgo_friend_code, None) + self.assertEqual(SteamID(1 , EType.Clan , EUniverse.Public, instance=1).as_csgo_friend_code, None) + self.assertEqual(SteamID(1 , EType.Individual, EUniverse.Beta , instance=1).as_csgo_friend_code, 'AJJJS-ABAA') + self.assertEqual(SteamID(1 , EType.Individual, EUniverse.Public, instance=1).as_csgo_friend_code, 'AJJJS-ABAA') + self.assertEqual(SteamID(123456 , EType.Individual, EUniverse.Public, instance=1).as_csgo_friend_code, 'ABNBT-GBDC') + self.assertEqual(SteamID(4294967295, EType.Individual, EUniverse.Public, instance=1).as_csgo_friend_code, 'S9ZZR-999P') def test_as_invite_url(self): self.assertEqual(SteamID(0 , EType.Individual, EUniverse.Public, instance=1).invite_url, None) @@ -435,17 +446,37 @@ class steamid_functions(unittest.TestCase): (1234, EType.Chat, EUniverse.Public, EInstanceFlag.Clan) ) - def test_arg_invite_code(self): - self.assertIsNone(steamid.invite_code_to_tuple('invalid_format')) - self.assertIsNone(steamid.invite_code_to_tuple('https://steamcommunity.com/p/cv-dgb')) - self.assertIsNone(steamid.invite_code_to_tuple('b')) - self.assertIsNone(steamid.invite_code_to_tuple('aaaaaaaaaaaaaaaaaaaaaaaaa')) - - self.assertEqual(steamid.invite_code_to_tuple('cv-dgb'), - (123456, EType.Individual, EUniverse.Public, 1)) - self.assertEqual(steamid.invite_code_to_tuple('http://s.team/p/cv-dgb'), - (123456, EType.Individual, EUniverse.Public, 1)) - self.assertEqual(steamid.invite_code_to_tuple('https://s.team/p/cv-dgb'), - (123456, EType.Individual, EUniverse.Public, 1)) - self.assertEqual(steamid.invite_code_to_tuple('https://s.team/p/cv-dgb/ABCDE12354'), - (123456, EType.Individual, EUniverse.Public, 1)) + def test_from_invite_code(self): + self.assertIsNone(steamid.from_invite_code('invalid_format')) + self.assertIsNone(steamid.from_invite_code('https://steamcommunity.com/p/cv-dgb')) + self.assertIsNone(steamid.from_invite_code('b')) + self.assertIsNone(steamid.from_invite_code('aaaaaaaaaaaaaaaaaaaaaaaaa')) + + self.assertEqual(steamid.from_invite_code('c', EUniverse.Beta), + SteamID(1, EType.Individual, EUniverse.Beta, 1)) + self.assertEqual(steamid.from_invite_code('c'), + SteamID(1, EType.Individual, EUniverse.Public, 1)) + self.assertEqual(steamid.from_invite_code('http://s.team/p/c', EUniverse.Beta), + SteamID(1, EType.Individual, EUniverse.Beta, 1)) + self.assertEqual(steamid.from_invite_code('http://s.team/p/c'), + SteamID(1, EType.Individual, EUniverse.Public, 1)) + self.assertEqual(steamid.from_invite_code('https://s.team/p/cv-dgb'), + SteamID(123456, EType.Individual, EUniverse.Public, 1)) + self.assertEqual(steamid.from_invite_code('https://s.team/p/cv-dgb/ABCDE12354'), + SteamID(123456, EType.Individual, EUniverse.Public, 1)) + self.assertEqual(steamid.from_invite_code('http://s.team/p/wwww-wwww'), + SteamID(4294967295, EType.Individual, EUniverse.Public, 1)) + + def test_from_csgo_friend_code(self): + self.assertIsNone(steamid.from_csgo_friend_code('')) + self.assertIsNone(steamid.from_csgo_friend_code('aaaaaaaaaaaaaaaaaaaaaaaaaaaa')) + self.assertIsNone(steamid.from_csgo_friend_code('11111-1111')) + + self.assertEqual(steamid.from_csgo_friend_code('AJJJS-ABAA', EUniverse.Beta), + SteamID(1, EType.Individual, EUniverse.Beta, instance=1)) + self.assertEqual(steamid.from_csgo_friend_code('AJJJS-ABAA'), + SteamID(1, EType.Individual, EUniverse.Public, instance=1)) + self.assertEqual(steamid.from_csgo_friend_code('ABNBT-GBDC'), + SteamID(123456, EType.Individual, EUniverse.Public, instance=1)) + self.assertEqual(steamid.from_csgo_friend_code('S9ZZR-999P'), + SteamID(4294967295, EType.Individual, EUniverse.Public, instance=1))
SteamID: implement CSGO friend code https://github.com/xPaw/SteamID.php/commit/fe934ce802f8aadc6fee1c3b47cd1a82f2328d75
0.0
caa7072cf0148d21593383e52ebd00a1ae8cf9ff
[ "tests/test_steamid.py::steamid_functions::test_from_csgo_friend_code", "tests/test_steamid.py::steamid_functions::test_from_invite_code", "tests/test_steamid.py::SteamID_properties::test_as_csgo_friend_code" ]
[ "tests/test_steamid.py::steamid_functions::test_arg_steam3", "tests/test_steamid.py::steamid_functions::test_steam64_from_url_timeout", "tests/test_steamid.py::steamid_functions::test_from_url", "tests/test_steamid.py::steamid_functions::test_arg_steam2", "tests/test_steamid.py::SteamID_initialization::test_kwarg_id", "tests/test_steamid.py::SteamID_initialization::test_is_valid", "tests/test_steamid.py::SteamID_initialization::test_kwargs_invalid", "tests/test_steamid.py::SteamID_initialization::test_arg_text_invalid", "tests/test_steamid.py::SteamID_initialization::test_arg_steam64_invalid_type", "tests/test_steamid.py::SteamID_initialization::test_hash", "tests/test_steamid.py::SteamID_initialization::test_arg_steam64", "tests/test_steamid.py::SteamID_initialization::test_arg_too_large_invalid", "tests/test_steamid.py::SteamID_initialization::test_arg_toomany_invalid", "tests/test_steamid.py::SteamID_initialization::test_kwarg_instance", "tests/test_steamid.py::SteamID_initialization::test_arg_steam3", "tests/test_steamid.py::SteamID_initialization::test_arg_steam2", "tests/test_steamid.py::SteamID_initialization::test_arg_steam32", "tests/test_steamid.py::SteamID_initialization::test_arg_steam64_invalid_universe", "tests/test_steamid.py::SteamID_initialization::test_kwarg_type", "tests/test_steamid.py::SteamID_initialization::test_kwarg_universe", "tests/test_steamid.py::SteamID_initialization::test_args_only", "tests/test_steamid.py::SteamID_properties::test_rich_comperison", "tests/test_steamid.py::SteamID_properties::test_as_32", "tests/test_steamid.py::SteamID_properties::test_repr", "tests/test_steamid.py::SteamID_properties::test_str", "tests/test_steamid.py::SteamID_properties::test_as_invite_url", "tests/test_steamid.py::SteamID_properties::test_as_invite_code", "tests/test_steamid.py::SteamID_properties::test_as_steam2", "tests/test_steamid.py::SteamID_properties::test_is_valid", "tests/test_steamid.py::SteamID_properties::test_as_steam2_zero", "tests/test_steamid.py::SteamID_properties::test_community_url", "tests/test_steamid.py::SteamID_properties::test_as_64", "tests/test_steamid.py::SteamID_properties::test_as_steam3" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-14 08:02:54+00:00
mit
816