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
int64 0
0
| environment_setup_commit
stringclasses 89
values | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
7.82k
| meta
dict | created_at
unknown | license
stringclasses 8
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ShawHahnLab__igseq-2 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 65385be..ac25fbe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,14 @@
## Changelog
+# dev
+
+Fixed:
+
+ * Duplicate FASTA paths found in vdj-gather will no longer result in
+ duplicated output sequences ([#2])
+
+[#2]: https://github.com/ShawHahnLab/igseq/pull/2
+
# 0.1.0 - 2021-11-19
First beta release
diff --git a/igseq/vdj.py b/igseq/vdj.py
index e6ac153..1778e34 100644
--- a/igseq/vdj.py
+++ b/igseq/vdj.py
@@ -67,6 +67,17 @@ def parse_vdj_paths(ref_paths):
attrs_list.append(attrs)
else:
raise util.IgSeqError("ref path not recognized: %s" % entry)
+ # handle duplicates produced from multiple ref_paths leading to the same
+ # files
+ groups = {}
+ for attrs in attrs_list:
+ if attrs["path"] not in groups:
+ groups[attrs["path"]] = attrs
+ else:
+ new_input = groups[attrs["path"]]["input"] + "; " + str(attrs["input"])
+ groups[attrs["path"]].update(attrs)
+ groups[attrs["path"]]["input"] = new_input
+ attrs_list = list(groups.values())
return attrs_list
def get_internal_vdj(name):
diff --git a/igseq/vdj_gather.py b/igseq/vdj_gather.py
index 40abbd1..6992dcc 100644
--- a/igseq/vdj_gather.py
+++ b/igseq/vdj_gather.py
@@ -18,5 +18,7 @@ def vdj_gather(ref_paths, dir_path_out, dry_run=False):
LOGGER.info("given ref path(s): %s", ref_paths)
LOGGER.info("given output: %s", dir_path_out)
attrs_list = vdj.parse_vdj_paths(ref_paths)
+ for attrs in attrs_list:
+ LOGGER.info("inferred FASTA: %s (from %s)", attrs["path"], attrs["input"])
paths = [attrs["path"] for attrs in attrs_list]
vdj.combine_vdj(paths, dir_path_out, dry_run=dry_run)
| ShawHahnLab/igseq | 3f0407f10e41f98acad8283d4f66e4adf1a4e3fc | diff --git a/test_igseq/test_vdj.py b/test_igseq/test_vdj.py
index 72b81d2..e0fd2ce 100644
--- a/test_igseq/test_vdj.py
+++ b/test_igseq/test_vdj.py
@@ -1,7 +1,6 @@
"""Tests for igseq.vdj."""
from pathlib import Path
-from tempfile import TemporaryDirectory
from igseq import vdj
from igseq.util import IgSeqError, DATA
from .util import TestBase
@@ -10,8 +9,7 @@ class TestParseVDJPaths(TestBase):
"""Basic test of parse_vdj_paths."""
def test_parse_vdj_paths(self):
- # It should give a list of dictionaries with info parsed from the given
- # paths.
+ """parse_vdj_paths should give a list of dicts with info parsed from the given paths"""
shared = {"fasta": True, "input": str(self.path/"input"), "type": "dir"}
attrs_list_exp = [
{"path": self.path/"input/D.fasta", "segment": "D"},
@@ -28,9 +26,26 @@ class TestParseVDJPaths(TestBase):
attrs_list = vdj.parse_vdj_paths(ref_paths)
self.assertEqual(attrs_list, attrs_list_exp)
+ def test_parse_vdj_paths_duplicates(self):
+ """parse_vdj_paths shouldn't repeat paths that come from multiple input names"""
+ # Instead it'll just squish both input names into the same entries.
+ shared = {"fasta": True, "input": str(self.path/"input"), "type": "dir"}
+ attrs_list_exp = [
+ {"path": self.path/"input/D.fasta", "segment": "D"},
+ {"path": self.path/"input/J.fasta", "segment": "J"},
+ {"path": self.path/"input/V.fasta", "segment": "V"}]
+ for attrs in attrs_list_exp:
+ attrs.update(shared)
+ ref_paths = [self.path / "input", self.path/"input/D.fasta"]
+ attrs_list_exp[0]["type"] = "file"
+ attrs_list_exp[0]["input"] = "; ".join([str(p) for p in ref_paths])
+ attrs_list = vdj.parse_vdj_paths(ref_paths)
+ self.assertEqual(attrs_list, attrs_list_exp)
+
def test_parse_vdj_paths_with_files(self):
- # Individual files should work too. In this case they're sorted as
- # they're given, since the sorting is by-ref and then by-file.
+ """parse_vdj_paths should work with filenames as inputs"""
+ # In this case they're sorted as they're given, since the sorting is
+ # by-ref and then by-file.
mkdict = lambda s: {
"path": self.path/f"input/{s}.fasta",
"input": str(self.path/f"input/{s}.fasta"),
@@ -43,8 +58,7 @@ class TestParseVDJPaths(TestBase):
self.assertEqual(attrs_list, attrs_list_exp)
def test_parse_vdj_paths_with_ref(self):
- # If we also ask for a fragment of the filenames of builtin FASTA
- # files, it should find those too
+ """parse_vdj_paths should work with builtin filename fragments"""
shared = {"fasta": True, "input": str(self.path/"input"), "type": "dir"}
attrs_list_exp = [
{"path": self.path/"input/D.fasta", "segment": "D"},
| Duplicate inferred FASTA paths should only be handled once
`vdj-gather` can take fragments of builtin file paths as input, so you could do, for example:
igseq vdj-gather sonarramesh/IGK sonarramesh/IGH/IGHD -o igdiscover-db-start
...and get IGK genes plus a placeholder D file. But something like this results in D sequences being written twice:
igseq vdj-gather sonarramesh/IGH sonarramesh/IGH/IGHD -o igdiscover-db-start
Instead `vdj.parse_vdj_paths` should condense duplicate FASTA file paths internally. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test_igseq/test_vdj.py::TestParseVDJPaths::test_parse_vdj_paths_duplicates"
] | [
"test_igseq/test_vdj.py::TestParseVDJPaths::test_parse_vdj_paths",
"test_igseq/test_vdj.py::TestParseVDJPaths::test_parse_vdj_paths_with_files",
"test_igseq/test_vdj.py::TestParseVDJPaths::test_parse_vdj_paths_with_ref",
"test_igseq/test_vdj.py::TestParseVDJPathsMissing::test_parse_vdj_paths",
"test_igseq/test_vdj.py::TestGetInternalVDJ::test_get_internal_vdj",
"test_igseq/test_vdj.py::TestParseVDJFilename::test_parse_vdj_filename",
"test_igseq/test_vdj.py::TestCombineVDJ::test_combine_vdj",
"test_igseq/test_vdj.py::TestCombineVDJWithInternal::test_combine_vdj",
"test_igseq/test_vdj.py::TestGroup::test_group",
"test_igseq/test_vdj.py::TestGroup::test_group_with_keyfunc"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-11-19T21:08:08Z" | mit |
|
ShawHahnLab__igseq-37 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 51fd6d2..675a8c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@
### Added
* `identity` command for calculating pairwise identity between arbitrary
- queries and references ([#31])
+ queries and references ([#31], [#37])
* Support for showing basic tree topology for Newick-format files in `show`
command ([#33])
@@ -15,6 +15,7 @@
* broken pipes (such as from `igseq something | something else`) are now
handled gracefully ([#30])
+[#37]: https://github.com/ShawHahnLab/igseq/pull/37
[#35]: https://github.com/ShawHahnLab/igseq/pull/35
[#33]: https://github.com/ShawHahnLab/igseq/pull/33
[#31]: https://github.com/ShawHahnLab/igseq/pull/31
diff --git a/igseq/identity.py b/igseq/identity.py
index e942641..ed23394 100644
--- a/igseq/identity.py
+++ b/igseq/identity.py
@@ -10,7 +10,8 @@ allows, for example, junction sequences from an AIRR tsv as queries and a FASTA
of known junctions as references.
The scoring is based on a simple global pairwise alignment, with matches scored
-as 1, mismatches and gaps 0.
+as 1, mismatches and gaps 0. Any existing gaps are removed before comparing
+sequences, and differeces in case (lower/upper) are disregarded.
"""
import logging
@@ -68,5 +69,12 @@ def score_identity(seq1, seq2):
"""
# These can be strings or Seq objects, but not SeqRecords.
if seq1 and seq2:
+ # We'll disregard gaps and case. If whatever these objects are can't
+ # handle those methods we'll throw a ValueError.
+ try:
+ seq1 = seq1.replace("-", "").upper()
+ seq2 = seq2.replace("-", "").upper()
+ except AttributeError as err:
+ raise ValueError("score_identity arguments should be Seq objects or strings") from err
return ALIGNER.score(seq1, seq2)/max(len(seq1), len(seq2))
return 0
| ShawHahnLab/igseq | 2e36b272d6170625d96b3df3fb6a513ff37b7a27 | diff --git a/test_igseq/test_identity.py b/test_igseq/test_identity.py
index 47738b0..9c4226e 100644
--- a/test_igseq/test_identity.py
+++ b/test_igseq/test_identity.py
@@ -138,6 +138,8 @@ class TestScoreIdentity(unittest.TestCase):
# without also needing a lot of extra metadata tracking.)
cases = [
("ACTG", "ACTG", 1.00), # identical
+ ("AC-G", "A-CG", 1.00), # identical (gaps disregarded)
+ ("ACTG", "actg", 1.00), # identical (case disregarded)
("ACTG", "", 0.00), # one blank -> 0 by definition
( "", "ACTG", 0.00), # other blank -> 0 by definition
( "", "", 0.00), # both blank -> 0 by definition
| Identity calculation should disregard gaps and uppercase/lowercase
In using the new `identity` command I realized it should ignore gaps and uppercase/lowercase differences when comparing sequences. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test_igseq/test_identity.py::TestScoreIdentity::test_score_identity",
"test_igseq/test_identity.py::TestScoreIdentity::test_score_identity_objs"
] | [
"test_igseq/test_identity.py::TestIdentity::test_identity",
"test_igseq/test_identity.py::TestIdentity::test_identity_aa",
"test_igseq/test_identity.py::TestIdentity::test_identity_csvgz_out",
"test_igseq/test_identity.py::TestIdentity::test_identity_dryrun",
"test_igseq/test_identity.py::TestIdentity::test_identity_single",
"test_igseq/test_identity.py::TestIdentity::test_identity_stdout",
"test_igseq/test_identity.py::TestIdentityTabular::test_identity",
"test_igseq/test_identity.py::TestIdentityTabular::test_identity_columns",
"test_igseq/test_identity.py::TestIdentityTabular::test_identity_single"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-19T13:25:42Z" | mit |
|
ShawHahnLab__igseq-43 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1b315d..908cee6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,9 +4,12 @@
### Added
+ * support for additional arguments for `getreads` command passed through to
+ bcl2fastq ([#43])
* `msa` command for building multiple sequence alignments with
[MUSCLE](https://drive5.com/muscle5/) ([#41])
+[#43]: https://github.com/ShawHahnLab/igseq/pull/43
[#41]: https://github.com/ShawHahnLab/igseq/pull/41
## 0.4.0 - 2022-09-17
diff --git a/igseq/__main__.py b/igseq/__main__.py
index 0d27193..f86f87b 100644
--- a/igseq/__main__.py
+++ b/igseq/__main__.py
@@ -78,10 +78,9 @@ def main(arglist=None):
try:
if args_extra:
# If there were unparsed arguments, see if we're in one of the
- # commands (currently just igblast) that can take extra
- # pass-through arguments. If so pass them along, but if not,
- # error out.
- if args.func in [_main_igblast]:
+ # commands that can take extra pass-through arguments. If so
+ # pass them along, but if not, error out.
+ if args.func in [_main_igblast, _main_getreads]:
args.func(args, args_extra)
else:
parser.parse_args(args_extra)
@@ -112,13 +111,14 @@ def main(arglist=None):
except BrokenPipeError:
os.dup2(devnull, sys.stderr.fileno())
-def _main_getreads(args):
+def _main_getreads(args, extra_args=None):
if args.no_counts:
args.countsfile = None
getreads.getreads(
path_input=args.input,
dir_out=args.outdir,
path_counts=args.countsfile,
+ extra_args=extra_args,
threads_load=args.threads_load,
threads_proc=args.threads,
dry_run=args.dry_run)
diff --git a/igseq/getreads.py b/igseq/getreads.py
index 1a65a4a..2136653 100644
--- a/igseq/getreads.py
+++ b/igseq/getreads.py
@@ -9,6 +9,10 @@ so they can be used later during demultiplexing.
This step can be skipped if you already have all of your reads in single trio
of I1/R1/R2 fastq.gz files.
+
+Any command-line arguments not recognized here are passed as-is to the
+bcl2fastq command, like the igblast command allows. See bcl2fastq --help for
+those options.
"""
import logging
@@ -22,7 +26,7 @@ LOGGER = logging.getLogger(__name__)
BCL2FASTQ = "bcl2fastq"
-def getreads(path_input, dir_out, path_counts="", threads_load=1, threads_proc=1, dry_run=False):
+def getreads(path_input, dir_out, path_counts="", extra_args=None, threads_load=1, threads_proc=1, dry_run=False):
"""Get reads directly from Illumina run directory.
path_input: path to an Illumina run directory
@@ -30,6 +34,8 @@ def getreads(path_input, dir_out, path_counts="", threads_load=1, threads_proc=1
path_counts: path to csv to write read counts to. If an empty
string, dir_out/getreads.counts.csv is used. If None, this
file isn't written.
+ extra_args: list of arguments to pass to bcl2fastq command. Must not
+ overlap with the arguments set here.
threads_load: number of threads for parallel loading
threads_proc: number of threads for parallel processing
dry_run: If True, don't actually call any commands or write any files.
@@ -54,6 +60,7 @@ def getreads(path_input, dir_out, path_counts="", threads_load=1, threads_proc=1
dir_out = Path(dir_out)
LOGGER.info("input: %s", path_input)
LOGGER.info("output: %s", dir_out)
+ LOGGER.info("extra args: %s", extra_args)
if path_counts == "":
path_counts = dir_out / "getreads.counts.csv"
@@ -102,7 +109,7 @@ def getreads(path_input, dir_out, path_counts="", threads_load=1, threads_proc=1
"--writing-threads", 1,
"--min-log-level", log_level]
try:
- _run_bcl2fastq(args)
+ _run_bcl2fastq(args, extra_args)
except subprocess.CalledProcessError as err:
msg = f"bcl2fastq exited with code {err.returncode}"
LOGGER.critical(msg)
@@ -147,7 +154,15 @@ def count_bcl2fastq_reads(summary_txt):
cts["extra-pf"] += int(row["NumberOfReadsPF"])
return cts
-def _run_bcl2fastq(args):
+def _run_bcl2fastq(args, extra_args=None):
args = [BCL2FASTQ] + [str(arg) for arg in args]
+ if extra_args:
+ # make sure none of the extra arguments, if there are any, clash with
+ # the ones we've defined above.
+ args_dashes = {arg for arg in args if str(arg).startswith("-")}
+ shared = args_dashes & set(extra_args)
+ if shared:
+ raise util.IgSeqError(f"bcl2fastq arg collision from extra arguments: {shared}")
+ args += extra_args
LOGGER.info("bcl2fastq command: %s", args)
subprocess.run(args, check=True)
| ShawHahnLab/igseq | b7fba32e2a004bb4197c7c7dd51b4b6aeb0e523b | diff --git a/test_igseq/test_getreads.py b/test_igseq/test_getreads.py
index 53f79bf..4865add 100644
--- a/test_igseq/test_getreads.py
+++ b/test_igseq/test_getreads.py
@@ -34,7 +34,7 @@ class TestGetreads(TestBase):
When called it will make empty files with the expected filenames.
"""
- def side_effect(args):
+ def side_effect(args, extra_args=None):
idx = args.index("--output-dir") + 1
path = Path(args[idx])
path.mkdir(parents=True, exist_ok=True)
@@ -84,7 +84,7 @@ class TestGetreads(TestBase):
self.mock.assert_called_once()
self.assertEqual(args_exp, args_obs)
# There should be some info message but nothing higher than that
- self.assertEqual(logcounts, {"INFO": 4})
+ self.assertEqual(logcounts, {"INFO": 5})
class TestGetreadsMissingFiles(TestGetreads):
@@ -93,7 +93,7 @@ class TestGetreadsMissingFiles(TestGetreads):
@classmethod
def make_mock_bcl2fastq(cls):
"""Mock _run_bcl2fastq that doesn't make any of the expected output files."""
- def side_effect(args):
+ def side_effect(args, extra_args=None):
idx = args.index("--output-dir") + 1
path = Path(args[idx])
path.mkdir(parents=True, exist_ok=True)
@@ -111,7 +111,7 @@ class TestGetreadsMissingFiles(TestGetreads):
self.mock.assert_called_once()
# There should be some info messages and also errors about the missing
# files
- self.assertEqual(logcounts, {"INFO": 4, "CRITICAL": 2})
+ self.assertEqual(logcounts, {"INFO": 5, "CRITICAL": 2})
class TestGetreadsExtraFiles(TestGetreads):
@@ -120,7 +120,7 @@ class TestGetreadsExtraFiles(TestGetreads):
@classmethod
def make_mock_bcl2fastq(cls):
"""Mock _run_bcl2fastq that create extra files."""
- def side_effect(args):
+ def side_effect(args, extra_args=None):
idx = args.index("--output-dir") + 1
path = Path(args[idx])
path.mkdir(parents=True, exist_ok=True)
@@ -145,7 +145,7 @@ class TestGetreadsExtraFiles(TestGetreads):
self.mock.assert_called_once()
# There should be some info messages and also a warning about the extra
# files
- self.assertEqual(logcounts, {"INFO": 4, "WARNING": 1})
+ self.assertEqual(logcounts, {"INFO": 5, "WARNING": 1})
class TestGetreadsLive(TestGetreads, TestLive):
| Support extra command-line arguments for bcl2fastq in getreads command
It should be possible to specify custom bcl2fastq arguments (.e.g. `--with-failed-reads`) to be added to the command. Should be easy enough by following the pattern already used for the igblast command. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test_igseq/test_getreads.py::TestGetreads::test_getreads",
"test_igseq/test_getreads.py::TestGetreadsMissingFiles::test_getreads",
"test_igseq/test_getreads.py::TestGetreadsExtraFiles::test_getreads"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-28T21:03:59Z" | mit |
|
ShawHahnLab__igseq-49 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4ba83d8..c57d74b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,12 @@
* `msa` command for building multiple sequence alignments with
[MUSCLE](https://drive5.com/muscle5/) ([#41])
+### Fixed
+
+ * `identity` command now uses a custom sequence ID column if one is given
+ ([#49])
+
+[#49]: https://github.com/ShawHahnLab/igseq/pull/49
[#44]: https://github.com/ShawHahnLab/igseq/pull/44
[#43]: https://github.com/ShawHahnLab/igseq/pull/43
[#41]: https://github.com/ShawHahnLab/igseq/pull/41
diff --git a/igseq/data/examples/outputs/tree/example_pattern_from_newick.nex b/igseq/data/examples/outputs/tree/example_pattern_from_newick.nex
index 2485d4a..c2fd435 100644
--- a/igseq/data/examples/outputs/tree/example_pattern_from_newick.nex
+++ b/igseq/data/examples/outputs/tree/example_pattern_from_newick.nex
@@ -3,12 +3,12 @@ begin taxa;
dimensions ntax=7;
taxlabels
'somethingelse'[&!color=#000000]
-'wk16-001'[&!color=#d186d7]
-'wk16-002'[&!color=#d186d7]
-'wk16-003'[&!color=#d186d7]
-'wk20-001'[&!color=#be4229]
-'wk20-002'[&!color=#be4229]
-'wk20-003'[&!color=#be4229]
+'wk16-001'[&!color=#be4229]
+'wk16-002'[&!color=#be4229]
+'wk16-003'[&!color=#be4229]
+'wk20-001'[&!color=#d186d7]
+'wk20-002'[&!color=#d186d7]
+'wk20-003'[&!color=#d186d7]
;
end;
diff --git a/igseq/identity.py b/igseq/identity.py
index 24a47dd..8c80b11 100644
--- a/igseq/identity.py
+++ b/igseq/identity.py
@@ -58,7 +58,7 @@ def identity(path_in, path_out, path_ref=None, fmt_in=None, fmt_in_ref=None, col
record[reader.colmap["sequence"]],
ref[reader.colmap["sequence"]])
writer.write({
- "query": record["sequence_id"],
+ "query": record[reader.colmap["sequence_id"]],
"ref": ref["sequence_id"],
"identity": score})
diff --git a/igseq/tree.py b/igseq/tree.py
index 9f61444..87f626c 100644
--- a/igseq/tree.py
+++ b/igseq/tree.py
@@ -286,6 +286,9 @@ def build_seq_sets(seq_ids, pattern=None, lists=None):
if lists:
for set_name, seq_set_ids in lists.items():
seq_sets[set_name].update(seq_set_ids)
+ # Sort by key so we get a consistent order (yes, dicts are ordered these
+ # days)
+ seq_sets = {key: seq_sets[key] for key in sorted(seq_sets.keys())}
return seq_sets
def color_seqs(seq_ids, seq_sets, seq_set_colors=None):
| ShawHahnLab/igseq | a97327884fb97b137613389607800e4215425ccf | diff --git a/test_igseq/data/test_identity/TestIdentityTabular/input_query.csv b/test_igseq/data/test_identity/TestIdentityTabular/input_query.csv
index e50c683..4708b06 100644
--- a/test_igseq/data/test_identity/TestIdentityTabular/input_query.csv
+++ b/test_igseq/data/test_identity/TestIdentityTabular/input_query.csv
@@ -1,4 +1,4 @@
-sequence_id,sequence,sequence2
-query1,ACTGACTGACTACTGG,CCAGTAGTCAGTCAGT
-query2,TCTGACCGACTACTGA,TCAGTAGTCGGTCAGA
-query3,ACAGACTGAGTACTGG,NNNNNNNNNNNNNNNN
+sequence_id,sequence_id2,sequence,sequence2
+query1,seqA,ACTGACTGACTACTGG,CCAGTAGTCAGTCAGT
+query2,seqB,TCTGACCGACTACTGA,TCAGTAGTCGGTCAGA
+query3,seqC,ACAGACTGAGTACTGG,NNNNNNNNNNNNNNNN
diff --git a/test_igseq/data/test_identity/TestIdentityTabular/output_col3.csv b/test_igseq/data/test_identity/TestIdentityTabular/output_col3.csv
new file mode 100644
index 0000000..ec8ac27
--- /dev/null
+++ b/test_igseq/data/test_identity/TestIdentityTabular/output_col3.csv
@@ -0,0 +1,4 @@
+query,ref,identity
+seqA,ref,1.0
+seqB,ref,0.8125
+seqC,ref,0.875
diff --git a/test_igseq/test_identity.py b/test_igseq/test_identity.py
index 9c4226e..fc7f544 100644
--- a/test_igseq/test_identity.py
+++ b/test_igseq/test_identity.py
@@ -103,9 +103,9 @@ class TestIdentityTabular(TestBase):
def test_identity_columns(self):
"""Test using different columns from input."""
- # Here a CSV query and CSV ref can give CSV output
- # the defaults are the same as for convert() so sequence_id and
- # sequence columns will be used.
+ # Here a CSV query and CSV ref can give CSV output.
+ # The defaults are the same as for convert() so sequence_id and
+ # sequence columns will be used unless overridden.
with TemporaryDirectory() as tmpdir:
identity(
self.path/"input_query.csv",
@@ -113,6 +113,13 @@ class TestIdentityTabular(TestBase):
self.path/"input_ref.csv",
colmap={"sequence": "sequence2"})
self.assertTxtsMatch(self.path/"output_col2.csv", Path(tmpdir)/"output.csv")
+ with TemporaryDirectory() as tmpdir:
+ identity(
+ self.path/"input_query.csv",
+ Path(tmpdir)/"output.csv",
+ self.path/"input_ref.csv",
+ colmap={"sequence_id": "sequence_id2"})
+ self.assertTxtsMatch(self.path/"output_col3.csv", Path(tmpdir)/"output.csv")
def test_identity_single(self):
"""Identity with implicit ref via query."""
| identity command ignores sequence ID column name for tabular input
The identity command uses a hardcoded reference to the `sequence_id` column and ignores any custom column like from `--col-seq-id`. (The existing tests check a custom sequence column, which works, but not a custom sequence ID column, which evidently doesn't.) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test_igseq/test_identity.py::TestIdentityTabular::test_identity_columns"
] | [
"test_igseq/test_identity.py::TestIdentity::test_identity",
"test_igseq/test_identity.py::TestIdentity::test_identity_aa",
"test_igseq/test_identity.py::TestIdentity::test_identity_csvgz_out",
"test_igseq/test_identity.py::TestIdentity::test_identity_dryrun",
"test_igseq/test_identity.py::TestIdentity::test_identity_single",
"test_igseq/test_identity.py::TestIdentity::test_identity_stdout",
"test_igseq/test_identity.py::TestIdentityTabular::test_identity",
"test_igseq/test_identity.py::TestIdentityTabular::test_identity_single",
"test_igseq/test_identity.py::TestScoreIdentity::test_score_identity",
"test_igseq/test_identity.py::TestScoreIdentity::test_score_identity_objs"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-01-03T22:12:09Z" | mit |
|
ShawHahnLab__igseq-57 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18d86e2..543636d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,14 @@
# Changelog
+## dev
+
+### Fixed
+
+ * `tree` command can now handle assigning a color code when exactly one
+ sequence set is defined ([#57])
+
+[#57]: https://github.com/ShawHahnLab/igseq/pull/57
+
## 0.5.0 - 2023-01-04
### Added
diff --git a/igseq/tree.py b/igseq/tree.py
index 87f626c..713be55 100644
--- a/igseq/tree.py
+++ b/igseq/tree.py
@@ -314,7 +314,7 @@ def make_seq_set_colors(seq_sets):
# adapted from SONAR
# this stretches across COLORS in even increments for as many as we need here
num = len(colors.COLORS)
- subset = [int( a * (num-1) / (len(seq_sets)-1) ) for a in range(num)]
+ subset = [int( a * (num-1) / max(1, (len(seq_sets)-1)) ) for a in range(num)]
try:
seq_set_colors[set_name] = colors.color_str_to_trio(colors.COLORS[subset[idx]])
except IndexError:
| ShawHahnLab/igseq | 01c186acaf91ed5813d00eb86c12bae060dacfde | diff --git a/test_igseq/test_tree.py b/test_igseq/test_tree.py
index 2fcfd73..b987469 100644
--- a/test_igseq/test_tree.py
+++ b/test_igseq/test_tree.py
@@ -193,7 +193,7 @@ class TestParseLists(TestBase):
self.assertEqual(tree.parse_lists(None), {})
-class TestParseColors(TestBase):
+class TestColors(TestBase):
def test_parse_colors(self):
# implicit naming
@@ -214,6 +214,19 @@ class TestParseColors(TestBase):
# None should be equivalent to no colors given
self.assertEqual(tree.parse_colors(None), {})
+ def test_make_seq_sets_colors(self):
+ # a basic scenario
+ self.assertEqual(
+ tree.make_seq_set_colors({"A": {"seq1", "seq2"}, "B": {"seq3", "seq4"}}),
+ {"A": [190, 66, 41], "B": [209, 134, 215]})
+ # just one set
+ self.assertEqual(
+ tree.make_seq_set_colors({"A": {"A"}}),
+ {"A": [190, 66, 41]})
+ # how about *no* sets?
+ self.assertEqual(tree.make_seq_set_colors({}), {})
+
+
class TestLooksAligned(TestBase):
| tree color-coding crashes when exactly one set is defined
When there's exactly one set of sequences defined, `make_seq_set_colors` crashes:
```
$ igseq tree -P '.*' --input-format newick <(echo '((A:1,B:1):1)') out.nex
$ igseq tree -P A --input-format newick <(echo '((A:1,B:1):1)') out.nex
Traceback (most recent call last):
File "/home/jesse/miniconda3/envs/igseqhelper/bin/igseq", line 10, in <module>
sys.exit(main())
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/__main__.py", line 89, in main
args.func(args)
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/__main__.py", line 257, in _main_tree
tree.tree(
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/tree.py", line 137, in tree
seq_colors = color_seqs(seq_ids, seq_sets_combo, colors)
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/tree.py", line 296, in color_seqs
seq_set_colors_combo = make_seq_set_colors(seq_sets)
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/tree.py", line 317, in make_seq_set_colors
subset = [int( a * (num-1) / (len(seq_sets)-1) ) for a in range(num)]
File "/home/jesse/miniconda3/envs/igseqhelper/lib/python3.9/site-packages/igseq/tree.py", line 317, in <listcomp>
subset = [int( a * (num-1) / (len(seq_sets)-1) ) for a in range(num)]
ZeroDivisionError: division by zero
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test_igseq/test_tree.py::TestColors::test_make_seq_sets_colors"
] | [
"test_igseq/test_tree.py::TestTree::test_run_fasttree_aln",
"test_igseq/test_tree.py::TestTree::test_tree_conversions",
"test_igseq/test_tree.py::TestTreeEmpty::test_run_fasttree",
"test_igseq/test_tree.py::TestTreeEmpty::test_tree",
"test_igseq/test_tree.py::TestTreeMulti::test_tree_multi_input",
"test_igseq/test_tree.py::TestTreeMultiGaps::test_tree_multi_input",
"test_igseq/test_tree.py::TestTreeDups::test_tree_duplicates",
"test_igseq/test_tree.py::TestParseLists::test_parse_lists",
"test_igseq/test_tree.py::TestColors::test_parse_colors",
"test_igseq/test_tree.py::TestLooksAligned::test_looks_aligned"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-25T16:33:22Z" | mit |
|
Shoobx__mypy-zope-80 | diff --git a/src/mypy_zope/plugin.py b/src/mypy_zope/plugin.py
index 312c0b5..46bdc1b 100644
--- a/src/mypy_zope/plugin.py
+++ b/src/mypy_zope/plugin.py
@@ -695,7 +695,7 @@ class ZopeInterfacePlugin(Plugin):
# there is a decorator for the class that will create a "type promotion",
# but ensure this only gets applied a single time per interface.
promote = Instance(iface, [])
- if not any(ti._promote == promote for ti in impl.mro):
+ if not any(promote in ti._promote for ti in impl.mro):
faketi = TypeInfo(SymbolTable(), iface.defn, iface.module_name)
faketi._promote = [promote]
impl.mro.append(faketi)
| Shoobx/mypy-zope | 5139181a07febfde688af3035d00319942df4dcf | diff --git a/tests/samples/forward_reference_to_implementer.py b/tests/samples/forward_reference_to_implementer.py
new file mode 100644
index 0000000..ce8d846
--- /dev/null
+++ b/tests/samples/forward_reference_to_implementer.py
@@ -0,0 +1,32 @@
+"""
+Reproduces a bug where MROs were incorrectly computed for implementers
+ https://github.com/Shoobx/mypy-zope/issues/34
+ https://github.com/Shoobx/mypy-zope/issues/76
+"""
+
+from zope.interface import implementer, Interface
+
+
+class IProtocol(Interface):
+ pass
+
+
+def main() -> None:
+ class Factory:
+ # It seems important for "Protocol" to show up as an attribute annotation to
+ # trigger the bug(!?)
+ protocol: "Protocol"
+
+ @implementer(IProtocol)
+ class Protocol:
+ pass
+
+
+if __name__ == '__main__':
+ main()
+
+"""
+Expect no errors. A specific test checks that we correct compute the MRO of `Protocol`.
+<output>
+</output>
+"""
diff --git a/tests/test_mro_calculation.py b/tests/test_mro_calculation.py
new file mode 100644
index 0000000..a051dcc
--- /dev/null
+++ b/tests/test_mro_calculation.py
@@ -0,0 +1,68 @@
+import os.path
+from typing import Optional, List
+
+import pytest
+from mypy import options, build
+from mypy.build import State
+from mypy.modulefinder import BuildSource
+from mypy.nodes import SymbolTableNode, TypeInfo
+
+HERE = os.path.abspath(os.path.dirname(__file__))
+SAMPLES_DIR = os.path.join(HERE, "samples")
+
+
[email protected](scope="session")
+def mypy_cache_dir(tmp_path_factory):
+ tdir = tmp_path_factory.mktemp('.mypy_cahe')
+ print("Setup cache", str(tdir))
+ return str(tdir)
+
+
+def test_mro_computation_in_forward_reference_to_implementer(mypy_cache_dir: str) -> None:
+ sample_name = "forward_reference_to_implementer"
+
+ opts = options.Options()
+ opts.show_traceback = True
+ opts.namespace_packages = True
+ opts.cache_dir = mypy_cache_dir
+ opts.plugins = ['mypy_zope:plugin']
+ # Config file is needed to load plugins, it doesn't not exist and is not
+ # supposed to.
+ opts.config_file = 'not_existing_config.ini'
+
+ samplefile = os.path.join(SAMPLES_DIR, f"{sample_name}.py")
+ base_dir = os.path.dirname(samplefile)
+ with open(samplefile) as f:
+ source = BuildSource(
+ None,
+ module=sample_name,
+ text=f.read(),
+ base_dir=base_dir,
+ )
+ result = build.build(sources=[source], options=opts)
+ assert result.errors == []
+
+ # Result.graph is a map from module name to state objects.
+ state: State = result.graph[sample_name]
+
+ # Find Mypy's representation of the Protocol class.
+ node: Optional[SymbolTableNode] = None
+ for fullname, symbol_table_node, _type_info in state.tree.local_definitions():
+ # Use startswith(...) rather than a direct comparison
+ # because the typename includes a line number at the end
+ if fullname.startswith(f"{sample_name}.Protocol"):
+ node = symbol_table_node
+ break
+
+ assert node is not None, f"Failed to find `Protocol` class in mypy's state for {samplefile}"
+
+ mro: List[TypeInfo] = node.node.mro
+ # Expected: [
+ # <TypeInfo forward_reference_to_implementer.Protocol@21>,
+ # <TypeInfo builtins.object>,
+ # <TypeInfo forward_reference_to_implementer.IProtocol>,
+ # ]
+ assert len(mro) == 3
+ assert mro[0].fullname.startswith(f"{sample_name}.Protocol")
+ assert mro[1].fullname == "builtins.object"
+ assert mro[2].fullname == f"{sample_name}.IProtocol"
| Caching errors with latest version of mypy
Hi. With the latest version of mypy and mypy-zope we're getting mypy errors that I think are cache related. The error goes away after `rm -rf .mypy_cache`
Here's the smallest repro I could make:
src/zg/foo.py:
```
from zg.bar import ZGScriptProtocol
print(ZGScriptProtocol.transport)
```
src/zg/bar.py:
```
from twisted.internet.protocol import ProcessProtocol
class ZGScriptProtocol(ProcessProtocol):
pass
```
I am able to reliably hit the problem by running the following commands:
```
$ rm -rf .mypy_cache
$ mypy src/zg/foo.py
Success: no issues found in 1 source file
$ mypy src/zg/foo.py src/zg/bar.py
src/zg/bar.py:3: error: Cannot determine consistent method resolution order (MRO) for "ZGScriptProtocol"
src/zg/foo.py:3: error: "Type[ZGScriptProtocol]" has no attribute "transport"
```
```
$ mypy --version
mypy 0.971 (compiled: yes)
```
`mypy-zope==0.3.9` and `twisted[tls]==22.4.0`
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_mro_calculation.py::test_mro_computation_in_forward_reference_to_implementer"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-09-28T00:34:37Z" | mit |
|
Shoobx__mypy-zope-88 | diff --git a/src/mypy_zope/plugin.py b/src/mypy_zope/plugin.py
index 46bdc1b..0c7971e 100644
--- a/src/mypy_zope/plugin.py
+++ b/src/mypy_zope/plugin.py
@@ -698,7 +698,10 @@ class ZopeInterfacePlugin(Plugin):
if not any(promote in ti._promote for ti in impl.mro):
faketi = TypeInfo(SymbolTable(), iface.defn, iface.module_name)
faketi._promote = [promote]
- impl.mro.append(faketi)
+ faketi.metaclass_type = iface.metaclass_type
+ # Insert the TypeInfo before the builtins.object that's at the end.
+ assert impl.mro[-1].fullname == 'builtins.object'
+ impl.mro.insert(len(impl.mro) - 1, faketi)
def plugin(version: str) -> PyType[Plugin]:
| Shoobx/mypy-zope | 3c767525b740a35e7039bf792ccfbce8590044d7 | diff --git a/tests/test_mro_calculation.py b/tests/test_mro_calculation.py
index a051dcc..eb9cf5d 100644
--- a/tests/test_mro_calculation.py
+++ b/tests/test_mro_calculation.py
@@ -59,10 +59,10 @@ def test_mro_computation_in_forward_reference_to_implementer(mypy_cache_dir: str
mro: List[TypeInfo] = node.node.mro
# Expected: [
# <TypeInfo forward_reference_to_implementer.Protocol@21>,
- # <TypeInfo builtins.object>,
# <TypeInfo forward_reference_to_implementer.IProtocol>,
+ # <TypeInfo builtins.object>,
# ]
assert len(mro) == 3
assert mro[0].fullname.startswith(f"{sample_name}.Protocol")
- assert mro[1].fullname == "builtins.object"
- assert mro[2].fullname == f"{sample_name}.IProtocol"
+ assert mro[1].fullname == f"{sample_name}.IProtocol"
+ assert mro[2].fullname == "builtins.object"
| Caching error (Metaclass conflict) with mypy 0.991
Hi. With the latest version of mypy (0.991) and mypy-zope (0.3.11) we're getting mypy errors that I think are cache related. The error goes away after `rm -rf .mypy_cache`
Here's the easiest repro I could make:
iface.py
```
from zope.interface import Interface
from zope.interface import implementer
class ISomething(Interface):
pass
class ISomething2(Interface):
pass
@implementer(ISomething)
class OneInterface:
pass
@implementer(ISomething, ISomething2)
class TwoInterfaces:
pass
```
foo.py
```
from iface import OneInterface, TwoInterfaces
class Good(OneInterface):
pass
class Bad(TwoInterfaces):
pass
```
I am able to reliably hit the problem by running the following commands:
```
$ rm -rf .mypy_cache
$ mypy iface.py
Success: no issues found in 1 source file
$ mypy foo.py
foo.py:6: error: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases [misc]
Found 1 error in 1 file (checked 1 source file)
```
As you can tell this only happens when there are multiple interfaces.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_mro_calculation.py::test_mro_computation_in_forward_reference_to_implementer"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-02-08T00:06:06Z" | mit |
|
Shopify__shopify_python_api-136 | diff --git a/.travis.yml b/.travis.yml
index 8fd1e39..98323d2 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,6 +3,7 @@ language: python
python:
- "2.7"
- "3.4"
+ - "3.5"
# command to install dependencies
install: "python setup.py install"
diff --git a/README.md b/README.md
index 4cc0d41..b2d0d1e 100644
--- a/README.md
+++ b/README.md
@@ -253,6 +253,24 @@ To run tests, simply open up the project directory in a terminal and run:
python setup.py test
```
+Alternatively, use [tox](http://tox.readthedocs.org/en/latest/) to
+sequentially test against different versions of Python in isolated
+environments:
+
+```shell
+pip install tox
+tox
+```
+
+See the tox documentation for help on running only specific environments
+at a time. The related tool [detox](https://pypi.python.org/pypi/detox)
+can be used to run tests in these environments in parallel:
+
+```shell
+pip install detox
+detox
+```
+
## Limitations
Currently there is no support for:
diff --git a/setup.py b/setup.py
index e4a6daa..1f41bb4 100644
--- a/setup.py
+++ b/setup.py
@@ -39,6 +39,7 @@ setup(name=NAME,
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
diff --git a/shopify/mixins.py b/shopify/mixins.py
index 9d3c179..c7806a0 100644
--- a/shopify/mixins.py
+++ b/shopify/mixins.py
@@ -11,8 +11,15 @@ class Countable(object):
class Metafields(object):
- def metafields(self):
- return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id)
+ def metafields(self, _options=None, **kwargs):
+ if _options is None:
+ _options = kwargs
+ return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options)
+
+ def metafields_count(self, _options=None, **kwargs):
+ if _options is None:
+ _options = kwargs
+ return int(self.get("metafields/count", **_options))
def add_metafield(self, metafield):
if self.is_new():
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..a2f77bd
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,21 @@
+[tox]
+envlist = py27, py34, py35
+
+[testenv]
+setenv =
+ PYTHONPATH = {toxinidir}:{toxinidir}/shopify
+commands = python setup.py test
+
+[testenv:flake8]
+basepython=python
+deps=
+ flake8
+ flake8_docstrings
+commands=
+ flake8 shopify
+
+[flake8]
+ignore = E126,E128
+max-line-length = 99
+exclude = .ropeproject
+max-complexity = 10
| Shopify/shopify_python_api | a78109e725cf9e400f955062399767f36f3a1f44 | diff --git a/test/fixtures/metafields_count.json b/test/fixtures/metafields_count.json
new file mode 100644
index 0000000..a113c32
--- /dev/null
+++ b/test/fixtures/metafields_count.json
@@ -0,0 +1,1 @@
+{"count":2}
diff --git a/test/product_test.py b/test/product_test.py
index c48962a..dcc9ae7 100644
--- a/test/product_test.py
+++ b/test/product_test.py
@@ -28,6 +28,26 @@ class ProductTest(TestCase):
for field in metafields:
self.assertTrue(isinstance(field, shopify.Metafield))
+ def test_get_metafields_for_product_with_params(self):
+ self.fake("products/632910392/metafields.json?limit=2", extension=False, body=self.load_fixture('metafields'))
+
+ metafields = self.product.metafields(limit=2)
+ self.assertEqual(2, len(metafields))
+ for field in metafields:
+ self.assertTrue(isinstance(field, shopify.Metafield))
+
+ def test_get_metafields_for_product_count(self):
+ self.fake("products/632910392/metafields/count", body=self.load_fixture('metafields_count'))
+
+ metafields_count = self.product.metafields_count()
+ self.assertEqual(2, metafields_count)
+
+ def test_get_metafields_for_product_count_with_params(self):
+ self.fake("products/632910392/metafields/count.json?value_type=string", extension=False, body=self.load_fixture('metafields_count'))
+
+ metafields_count = self.product.metafields_count(value_type="string")
+ self.assertEqual(2, metafields_count)
+
def test_update_loaded_variant(self):
self.fake("products/632910392/variants/808950810", method='PUT', code=200, body=self.load_fixture('variant'))
| metafields() method should be able to take options parameters for limit and page
```
import shopify
product = shopify.Product.find(5972485446)
metafields = product.metafields()
print(len(metafields))
> 50
metafields = product.metafields(limit=250)
> TypeError: metafields() got an unexpected keyword argument 'limit'
```
I looked into the code, and it seems like it may be a simple fix. If I come up with something I'll submit a pull request, if I can't I'll let it be known here so somebody else can try tackling it. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/product_test.py::ProductTest::test_get_metafields_for_product_count",
"test/product_test.py::ProductTest::test_get_metafields_for_product_count_with_params",
"test/product_test.py::ProductTest::test_get_metafields_for_product_with_params"
] | [
"test/product_test.py::ProductTest::test_add_metafields_to_product",
"test/product_test.py::ProductTest::test_add_variant_to_product",
"test/product_test.py::ProductTest::test_get_metafields_for_product",
"test/product_test.py::ProductTest::test_update_loaded_variant"
] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-04-18T03:46:33Z" | mit |
|
Shopify__shopify_python_api-330 | diff --git a/README.md b/README.md
index 4959665..45111bc 100644
--- a/README.md
+++ b/README.md
@@ -85,15 +85,17 @@ service. pyactiveresource has to be configured with a fully authorized
URL of a particular store first. To obtain that URL you can follow
these steps:
-1. First create a new application in either the partners admin or
- your store admin. For a private App you'll need the API_KEY and
- the PASSWORD otherwise you'll need the API_KEY and SHARED_SECRET.
+1. First create a new application in either the partners admin or your store
+ admin. You will need an API_VERSION equal to a valid version string of a
+ [Shopify API Version](https://help.shopify.com/en/api/versioning). For a
+ private App you'll need the API_KEY and the PASSWORD otherwise you'll need
+ the API_KEY and SHARED_SECRET.
2. For a private App you just need to set the base site url as
follows:
```python
- shop_url = "https://%s:%s@SHOP_NAME.myshopify.com/admin" % (API_KEY, PASSWORD)
+ shop_url = "https://%s:%s@SHOP_NAME.myshopify.com/admin/api/%s" % (API_KEY, PASSWORD, API_VERSION)
shopify.ShopifyResource.set_site(shop_url)
```
diff --git a/shopify/base.py b/shopify/base.py
index c902152..6cfee0e 100644
--- a/shopify/base.py
+++ b/shopify/base.py
@@ -77,6 +77,11 @@ class ShopifyResourceMeta(ResourceMeta):
ShopifyResource._site = cls._threadlocal.site = value
if value is not None:
parts = urllib.parse.urlparse(value)
+ host = parts.hostname
+ if parts.port:
+ host += ":" + str(parts.port)
+ new_site = urllib.parse.urlunparse((parts.scheme, host, parts.path, '', '', ''))
+ ShopifyResource._site = cls._threadlocal.site = new_site
if parts.username:
cls.user = urllib.parse.unquote(parts.username)
if parts.password:
| Shopify/shopify_python_api | 748fc93d09a3e4467cd0e605a855b84cf029f415 | diff --git a/test/base_test.py b/test/base_test.py
index 9e78bdb..8847857 100644
--- a/test/base_test.py
+++ b/test/base_test.py
@@ -98,13 +98,18 @@ class BaseTest(TestCase):
t2.start()
t2.join()
- def test_setting_site_without_token(self):
+ def test_setting_with_user_and_pass_strips_them(self):
+ shopify.ShopifyResource.clear_session()
self.fake(
'shop',
- url='https://user:[email protected]/admin/api/unstable/shop.json',
+ url='https://this-is-my-test-show.myshopify.com/admin/shop.json',
method='GET',
body=self.load_fixture('shop'),
headers={'Authorization': u'Basic dXNlcjpwYXNz'}
)
- shopify.ShopifyResource.set_site('https://user:[email protected]/admin/api/unstable')
+ API_KEY = 'user'
+ PASSWORD = 'pass'
+ shop_url = "https://%s:%[email protected]/admin" % (API_KEY, PASSWORD)
+ shopify.ShopifyResource.set_site(shop_url)
res = shopify.Shop.current()
+ self.assertEqual('Apple Computers', res.name)
diff --git a/test/session_test.py b/test/session_test.py
index d76c0f9..bf41591 100644
--- a/test/session_test.py
+++ b/test/session_test.py
@@ -84,7 +84,7 @@ class SessionTest(TestCase):
assigned_site = shopify.ShopifyResource.site
self.assertEqual('https://testshop.myshopify.com/admin/api/unstable', assigned_site)
- self.assertEqual('https://None/admin/api/unstable', shopify.ShopifyResource.site)
+ self.assertEqual('https://none/admin/api/unstable', shopify.ShopifyResource.site)
def test_create_permission_url_returns_correct_url_with_single_scope_and_redirect_uri(self):
shopify.Session.setup(api_key="My_test_key", secret="My test secret")
| Shopify API url not working
Hi,
Currently, I'm just playing around, with this library. I created a development store and a private app.
When I'm trying to create a product I got the following error:
Python 3.7.2
ShopifyAPI==5.0.1
Traceback (most recent call last):
File "C:\Users\danish\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 877, in _get_hostport
port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '[email protected]'
Any help will be appreciated.
Thanks | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/session_test.py::SessionTest::test_temp_works_without_currently_active_session",
"test/base_test.py::BaseTest::test_setting_with_user_and_pass_strips_them"
] | [
"test/session_test.py::SessionTest::test_hmac_calculation",
"test/session_test.py::SessionTest::test_not_be_valid_without_token",
"test/session_test.py::SessionTest::test_be_valid_with_any_token_and_any_url",
"test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_and_redirect_uri",
"test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_no_scope_and_redirect_uri",
"test/session_test.py::SessionTest::test_return_site_for_session",
"test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_no_scope_and_redirect_uri_and_state",
"test/session_test.py::SessionTest::test_raise_error_if_params_passed_but_signature_omitted",
"test/session_test.py::SessionTest::test_setup_api_key_and_secret_for_all_sessions",
"test/session_test.py::SessionTest::test_not_be_valid_without_a_url",
"test/session_test.py::SessionTest::test_parameter_validation_handles_missing_params",
"test/session_test.py::SessionTest::test_append_the_myshopify_domain_if_not_given",
"test/session_test.py::SessionTest::test_temp_reset_shopify_ShopifyResource_site_to_original_value",
"test/session_test.py::SessionTest::test_hmac_calculation_with_ampersand_and_equal_sign_characters",
"test/session_test.py::SessionTest::test_hmac_validation",
"test/session_test.py::SessionTest::test_raise_error_if_hmac_does_not_match_expected",
"test/session_test.py::SessionTest::test_use_https_protocol_by_default_for_all_sessions",
"test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_and_redirect_uri_and_state",
"test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_dual_scope_and_redirect_uri",
"test/session_test.py::SessionTest::test_myshopify_domain_supports_non_standard_ports",
"test/session_test.py::SessionTest::test_raise_error_if_hmac_is_invalid",
"test/session_test.py::SessionTest::test_return_token_if_hmac_is_valid",
"test/session_test.py::SessionTest::test_raise_exception_if_code_invalid_in_request_token",
"test/session_test.py::SessionTest::test_raise_error_if_timestamp_is_too_old",
"test/session_test.py::SessionTest::test_param_validation_of_param_values_with_lists",
"test/session_test.py::SessionTest::test_ignore_everything_but_the_subdomain_in_the_shop",
"test/base_test.py::BaseTest::test_activate_session_should_set_site_and_headers_for_given_session",
"test/base_test.py::BaseTest::test_headers_is_thread_safe",
"test/base_test.py::BaseTest::test_delete_should_send_custom_headers_with_request",
"test/base_test.py::BaseTest::test_activate_session_with_one_session_then_clearing_and_activating_with_another_session_shoul_request_to_correct_shop",
"test/base_test.py::BaseTest::test_headers_includes_user_agent",
"test/base_test.py::BaseTest::test_activate_session_should_set_site_given_version",
"test/base_test.py::BaseTest::test_clear_session_should_clear_site_and_headers_from_Base"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-06-25T19:39:19Z" | mit |
|
Shopify__shopify_python_api-354 | diff --git a/shopify/base.py b/shopify/base.py
index bcab899..65349e6 100644
--- a/shopify/base.py
+++ b/shopify/base.py
@@ -208,43 +208,7 @@ class ShopifyResource(ActiveResource, mixins.Countable):
@classmethod
def find(cls, id_=None, from_=None, **kwargs):
"""Checks the resulting collection for pagination metadata."""
-
- collection = super(ShopifyResource, cls).find(id_=id_, from_=from_,
- **kwargs)
-
- # pyactiveresource currently sends all headers from the response with
- # the collection.
- if isinstance(collection, Collection) and \
- "headers" in collection.metadata:
- headers = collection.metadata["headers"]
- if "Link" in headers:
- pagination = cls._parse_pagination(headers["Link"])
- return PaginatedCollection(collection, metadata={
- "pagination": pagination,
- "resource_class": cls
- })
-
+ collection = super(ShopifyResource, cls).find(id_=id_, from_=from_, **kwargs)
+ if isinstance(collection, Collection) and "headers" in collection.metadata:
+ return PaginatedCollection(collection, metadata={"resource_class": cls})
return collection
-
- @classmethod
- def _parse_pagination(cls, data):
- """Parses a Link header into a dict for cursor-based pagination.
-
- Args:
- data: The Link header value as a string.
- Returns:
- A dict with rel names as keys and URLs as values.
- """
-
- # Example Link header:
- # <https://xxx.shopify.com/admin/...>; rel="previous",
- # <https://xxx.shopify.com/admin/...>; rel="next"
-
- values = data.split(", ")
-
- result = {}
- for value in values:
- link, rel = value.split("; ")
- result[rel.split('"')[1]] = link[1:-1]
-
- return result
diff --git a/shopify/collection.py b/shopify/collection.py
index 5fa4a68..a604b1a 100644
--- a/shopify/collection.py
+++ b/shopify/collection.py
@@ -26,11 +26,12 @@ class PaginatedCollection(Collection):
metadata = obj.metadata
super(PaginatedCollection, self).__init__(obj, metadata=metadata)
else:
- super(PaginatedCollection, self).__init__(metadata=metadata or {},
- *args, **kwargs)
- if not ("pagination" in self.metadata and "resource_class" in self.metadata):
- raise AttributeError("Cursor-based pagination requires \"pagination\" and \"resource_class\" attributes in the metadata.")
+ super(PaginatedCollection, self).__init__(metadata=metadata or {}, *args, **kwargs)
+ if not ("resource_class" in self.metadata):
+ raise AttributeError("Cursor-based pagination requires a \"resource_class\" attribute in the metadata.")
+
+ self.metadata["pagination"] = self.__parse_pagination()
self.next_page_url = self.metadata["pagination"].get('next', None)
self.previous_page_url = self.metadata["pagination"].get('previous', None)
@@ -39,6 +40,16 @@ class PaginatedCollection(Collection):
self._current_iter = None
self._no_iter_next = kwargs.pop("no_iter_next", False)
+ def __parse_pagination(self):
+ if "headers" not in self.metadata or "Link" not in self.metadata["headers"]:
+ return {}
+ values = self.metadata["headers"]["Link"].split(", ")
+ result = {}
+ for value in values:
+ link, rel = value.split("; ")
+ result[rel.split('"')[1]] = link[1:-1]
+ return result
+
def has_previous_page(self):
"""Returns true if the current page has any previous pages before it.
"""
| Shopify/shopify_python_api | 3cec005f5af28622fba023c67f739784a23f98a4 | diff --git a/test/pagination_test.py b/test/pagination_test.py
index 461e8e0..3ee05ad 100644
--- a/test/pagination_test.py
+++ b/test/pagination_test.py
@@ -28,6 +28,13 @@ class PaginationTest(TestCase):
body=json.dumps({ "products": fixture[:2] }),
response_headers=next_headers)
+ def test_nonpaginates_collection(self):
+ self.fake('draft_orders', method='GET', code=200, body=self.load_fixture('draft_orders'))
+ draft_orders = shopify.DraftOrder.find()
+ self.assertEqual(1, len(draft_orders))
+ self.assertEqual(517119332, draft_orders[0].id)
+ self.assertIsInstance(draft_orders, shopify.collection.PaginatedCollection, "find() result is not PaginatedCollection")
+
def test_paginated_collection(self):
items = shopify.Product.find(limit=2)
self.assertIsInstance(items, shopify.collection.PaginatedCollection, "find() result is not PaginatedCollection")
| Cursor pagination issue with single page results
I was trying out the new cursor pagination 6.0.0 release and came across an issue.
page1 = shopify.Product.find(limit=100)
while page1.has_next_page():
// do stuff
I can an error
AttributeError: 'Collection' object has no attribute 'has_next_page'
This happens when I have less then limit results returned so there is only 1 page of results. It seems to return a Collection object instead of a PaginatedCollection.
If I reduce the limit so there will be at least 2 pages, it works fine.
For now I will use a limit I know will return multiple pages, but this means always making an extra api call.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/pagination_test.py::PaginationTest::test_nonpaginates_collection"
] | [
"test/pagination_test.py::PaginationTest::test_paginated_collection",
"test/pagination_test.py::PaginationTest::test_paginated_collection_iterator",
"test/pagination_test.py::PaginationTest::test_paginated_collection_no_cache",
"test/pagination_test.py::PaginationTest::test_paginated_iterator",
"test/pagination_test.py::PaginationTest::test_pagination_next_page",
"test/pagination_test.py::PaginationTest::test_pagination_previous"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-01-27T15:13:24Z" | mit |
|
Shopify__shopify_python_api-358 | diff --git a/shopify/base.py b/shopify/base.py
index 65349e6..d14401e 100644
--- a/shopify/base.py
+++ b/shopify/base.py
@@ -210,5 +210,5 @@ class ShopifyResource(ActiveResource, mixins.Countable):
"""Checks the resulting collection for pagination metadata."""
collection = super(ShopifyResource, cls).find(id_=id_, from_=from_, **kwargs)
if isinstance(collection, Collection) and "headers" in collection.metadata:
- return PaginatedCollection(collection, metadata={"resource_class": cls})
+ return PaginatedCollection(collection, metadata={"resource_class": cls}, **kwargs)
return collection
diff --git a/shopify/collection.py b/shopify/collection.py
index a604b1a..b254218 100644
--- a/shopify/collection.py
+++ b/shopify/collection.py
@@ -38,14 +38,18 @@ class PaginatedCollection(Collection):
self._next = None
self._previous = None
self._current_iter = None
- self._no_iter_next = kwargs.pop("no_iter_next", False)
+ self._no_iter_next = kwargs.pop("no_iter_next", True)
def __parse_pagination(self):
- if "headers" not in self.metadata or "Link" not in self.metadata["headers"]:
+ if "headers" not in self.metadata:
return {}
- values = self.metadata["headers"]["Link"].split(", ")
+
+ values = self.metadata["headers"].get("Link", self.metadata["headers"].get("link", None))
+ if values is None:
+ return {}
+
result = {}
- for value in values:
+ for value in values.split(", "):
link, rel = value.split("; ")
result[rel.split('"')[1]] = link[1:-1]
return result
| Shopify/shopify_python_api | cd049439a62b84475b3693f82d455fb342f4abc7 | diff --git a/test/pagination_test.py b/test/pagination_test.py
index 3ee05ad..6b00bb7 100644
--- a/test/pagination_test.py
+++ b/test/pagination_test.py
@@ -82,8 +82,6 @@ class PaginationTest(TestCase):
i = iter(c)
self.assertEqual(next(i).id, 1)
self.assertEqual(next(i).id, 2)
- self.assertEqual(next(i).id, 3)
- self.assertEqual(next(i).id, 4)
with self.assertRaises(StopIteration):
next(i)
| cursor-based pagination not working (header name case-sensitivity?)
I am trying to implement the new cursor-based pagination, with ShopifyPythonAPI/6.0.1 on Python/2.7.16 and pyactiveresource 2.2.0. I am testing with the API version 2020-10.
`has_next_page()` always returns false for me even when there are more items. Looking at your source code, `PaginatedCollection`'s `__parse_pagination` method looks for `metadata['header']['Link']` yet for some reasons, all header names are in lower-cases on my environment.
```
>>> p = shopify.Product.find(limit=3)
>>> p.has_next_page()
False
>>> p.metadata['pagination']
{}
>>> p.metadata['headers']['link']
'<https://STORE.myshopify.com/admin/api/2020-01/products.json?limit=3&page_info=CURSOR>; rel="next"'
>>> p.metadata['headers']['Link']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Link'
```
on a side note, it would be nice if we could retrieve page_info value from PaginatedCollection, so I can use it to fetch the next page. This way I don't need to keep the original page object to access the next page. I see `shopify.Product.find(page_info=CURSOR)` works, although i would feel better if it was documented.
Thanks. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/pagination_test.py::PaginationTest::test_paginated_collection_iterator"
] | [
"test/pagination_test.py::PaginationTest::test_nonpaginates_collection",
"test/pagination_test.py::PaginationTest::test_paginated_collection",
"test/pagination_test.py::PaginationTest::test_paginated_collection_no_cache",
"test/pagination_test.py::PaginationTest::test_paginated_iterator",
"test/pagination_test.py::PaginationTest::test_pagination_next_page",
"test/pagination_test.py::PaginationTest::test_pagination_previous"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-02-06T17:23:08Z" | mit |
|
Shopify__shopify_python_api-363 | diff --git a/shopify/resources/event.py b/shopify/resources/event.py
index 5d266d0..0fc1e6f 100644
--- a/shopify/resources/event.py
+++ b/shopify/resources/event.py
@@ -7,6 +7,6 @@ class Event(ShopifyResource):
def _prefix(cls, options={}):
resource = options.get("resource")
if resource:
- return "%s/s/%s" % (cls.site, resource, options["resource_id"])
+ return "%s/%s/%s" % (cls.site, resource, options["resource_id"])
else:
return cls.site
| Shopify/shopify_python_api | 16053bb8c6a27a0af992e4d6efc5bfdbb7931136 | diff --git a/test/event_test.py b/test/event_test.py
new file mode 100644
index 0000000..67e8033
--- /dev/null
+++ b/test/event_test.py
@@ -0,0 +1,12 @@
+import shopify
+from test.test_helper import TestCase
+
+class EventTest(TestCase):
+ def test_prefix_uses_resource(self):
+ prefix = shopify.Event._prefix(options={'resource': "orders", "resource_id": 42})
+ self.assertEqual("https://this-is-my-test-show.myshopify.com/admin/api/unstable/orders/42", prefix)
+
+ def test_prefix_doesnt_need_resource(self):
+ prefix = shopify.Event._prefix()
+ self.assertEqual("https://this-is-my-test-show.myshopify.com/admin/api/unstable", prefix)
+
| TypeError: not all arguments converted during string formatting in /resources/events.py
Getting the following error trying query order events
```
>>> import shopify
>>> shopify.Order.find(2098647662664).events()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/shopify/mixins.py", line 36, in events
return shopify.resources.Event.find(resource=self.__class__.plural, resource_id=self.id)
File "/usr/local/lib/python3.6/site-packages/pyactiveresource/activeresource.py", line 385, in find
return cls._find_every(from_=from_, **kwargs)
File "/usr/local/lib/python3.6/site-packages/pyactiveresource/activeresource.py", line 522, in _find_every
path = cls._collection_path(prefix_options, query_options)
File "/usr/local/lib/python3.6/site-packages/pyactiveresource/activeresource.py", line 613, in _collection_path
'prefix': cls._prefix(prefix_options),
File "/usr/local/lib/python3.6/site-packages/shopify/resources/event.py", line 10, in _prefix
return "%s/s/%s" % (cls.site, resource, options["resource_id"])
TypeError: not all arguments converted during string formatting
```
there appears to a missing percent sign for the string formatter:
https://github.com/Shopify/shopify_python_api/blob/master/shopify/resources/event.py#L10 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/event_test.py::EventTest::test_prefix_uses_resource"
] | [
"test/event_test.py::EventTest::test_prefix_doesnt_need_resource"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-02-27T00:27:46Z" | mit |
|
Shopify__shopify_python_api-457 | diff --git a/CHANGELOG b/CHANGELOG
index 795baab..246a91b 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,6 +1,7 @@
- Added support for Fulfillment.update_tracking ([#432](https://github.com/Shopify/shopify_python_api/pull/432))
- Add FulfillmentEvent resource ([#454](https://github.com/Shopify/shopify_python_api/pull/454))
- Fix for being unable to get the len() of a filter ([#456](https://github.com/Shopify/shopify_python_api/pull/456))
+- Add ApplicationCredit resource ([#457](https://github.com/Shopify/shopify_python_api/pull/457))
== Version 8.2.0
- [Feature] Add support for Dynamic API Versioning. When the library is initialized, it will now make a request to
diff --git a/shopify/resources/__init__.py b/shopify/resources/__init__.py
index 803c535..1622073 100644
--- a/shopify/resources/__init__.py
+++ b/shopify/resources/__init__.py
@@ -17,6 +17,7 @@ from .rule import Rule
from .tax_line import TaxLine
from .script_tag import ScriptTag
from .application_charge import ApplicationCharge
+from .application_credit import ApplicationCredit
from .recurring_application_charge import RecurringApplicationCharge
from .usage_charge import UsageCharge
from .asset import Asset
diff --git a/shopify/resources/application_credit.py b/shopify/resources/application_credit.py
new file mode 100644
index 0000000..83b8de1
--- /dev/null
+++ b/shopify/resources/application_credit.py
@@ -0,0 +1,4 @@
+from ..base import ShopifyResource
+
+class ApplicationCredit(ShopifyResource):
+ pass
| Shopify/shopify_python_api | 9cafb36fc6b3301e031d85ede398771a8b713602 | diff --git a/test/application_credit_test.py b/test/application_credit_test.py
new file mode 100644
index 0000000..630d023
--- /dev/null
+++ b/test/application_credit_test.py
@@ -0,0 +1,38 @@
+import shopify
+import json
+from test.test_helper import TestCase
+
+class ApplicationCreditTest(TestCase):
+ def test_get_application_credit(self):
+ self.fake('application_credits/445365009', method='GET', body=self.load_fixture('application_credit'), code=200)
+ application_credit = shopify.ApplicationCredit.find(445365009)
+ self.assertEqual('5.00', application_credit.amount)
+
+ def test_get_all_application_credits(self):
+ self.fake('application_credits', method='GET', body=self.load_fixture('application_credits'), code=200)
+ application_credits = shopify.ApplicationCredit.find()
+ self.assertEqual(1, len(application_credits))
+ self.assertEqual(445365009, application_credits[0].id)
+
+ def test_create_application_credit(self):
+ self.fake(
+ 'application_credits',
+ method='POST',
+ body=self.load_fixture('application_credit'),
+ headers={'Content-type': 'application/json'},
+ code=201
+ )
+
+ application_credit = shopify.ApplicationCredit.create({
+ 'description': 'application credit for refund',
+ 'amount': 5.0
+ })
+
+ expected_body = {
+ "application_credit": {
+ "description": "application credit for refund",
+ "amount": 5.0
+ }
+ }
+
+ self.assertEqual(expected_body, json.loads(self.http.request.data.decode("utf-8")))
diff --git a/test/fixtures/application_credit.json b/test/fixtures/application_credit.json
new file mode 100644
index 0000000..4d6c3de
--- /dev/null
+++ b/test/fixtures/application_credit.json
@@ -0,0 +1,8 @@
+{
+ "application_credit": {
+ "id": 445365009,
+ "amount": "5.00",
+ "description": "credit for application refund",
+ "test": null
+ }
+}
diff --git a/test/fixtures/application_credits.json b/test/fixtures/application_credits.json
new file mode 100644
index 0000000..b487a52
--- /dev/null
+++ b/test/fixtures/application_credits.json
@@ -0,0 +1,10 @@
+{
+ "application_credits": [
+ {
+ "id": 445365009,
+ "amount": "5.00",
+ "description": "credit for application refund",
+ "test": null
+ }
+ ]
+}
diff --git a/test/fulfillment_event_test.py b/test/fulfillment_event_test.py
index 1ba9a73..c58cc6e 100644
--- a/test/fulfillment_event_test.py
+++ b/test/fulfillment_event_test.py
@@ -1,6 +1,5 @@
import shopify
from test.test_helper import TestCase
-from pyactiveresource.activeresource import ActiveResource
class FulFillmentEventTest(TestCase):
def test_get_fulfillment_event(self):
@@ -21,4 +20,3 @@ class FulFillmentEventTest(TestCase):
fulfillment_event = shopify.FulfillmentEvent.find(12584341209251, order_id='2776493818019', fulfillment_id='2608403447971')
fulfillment_event.status = incorrect_status
fulfillment_event.save()
-
| Missing support for ApplicationCredit
I need to create ApplicationCredit objects, but there is no such resource in this SDK | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/application_credit_test.py::ApplicationCreditTest::test_create_application_credit",
"test/application_credit_test.py::ApplicationCreditTest::test_get_all_application_credits",
"test/application_credit_test.py::ApplicationCreditTest::test_get_application_credit"
] | [
"test/fulfillment_event_test.py::FulFillmentEventTest::test_create_fulfillment_event",
"test/fulfillment_event_test.py::FulFillmentEventTest::test_error_on_incorrect_status",
"test/fulfillment_event_test.py::FulFillmentEventTest::test_get_fulfillment_event"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-02-08T22:02:08Z" | mit |
|
SirAnthony__slpp-32 | diff --git a/slpp.py b/slpp.py
index 19a6405..9f35cc0 100644
--- a/slpp.py
+++ b/slpp.py
@@ -43,9 +43,6 @@ class SLPP(object):
def decode(self, text):
if not text or not isinstance(text, six.string_types):
return
- # FIXME: only short comments removed
- reg = re.compile('--.*$', re.M)
- text = reg.sub('', text, 0)
self.text = text
self.at, self.ch, self.depth = 0, '', 0
self.len = len(text)
@@ -101,6 +98,18 @@ class SLPP(object):
else:
break
+ self.skip_comments()
+
+ def skip_comments(self):
+ if self.ch == '-' and self.text[self.at] == '-':
+ # `--` is a comment, skip to next new line
+ while self.ch:
+ if re.match('\n', self.ch):
+ self.white()
+ break
+ else:
+ self.next_chr()
+
def next_chr(self):
if self.at >= self.len:
self.ch = None
| SirAnthony/slpp | b9474965a8fd5759847c8cbdfa873069a43a0bb8 | diff --git a/tests.py b/tests.py
index 6f03ee8..9fe8353 100755
--- a/tests.py
+++ b/tests.py
@@ -157,5 +157,14 @@ class TestSLPP(unittest.TestCase):
t('{ [5] = 111, [4] = 52.1, 43, [3] = 54.3, false, 9 }')
t('{ [1] = 1, [2] = "2", 3, 4, [5] = 5 }')
+ def test_comments(self):
+ lua = '-- starting comment\n{\n["multiline_string"] = "A multiline string where one of the lines starts with\n-- two dashes",\n-- middle comment\n["another_multiline_string"] = "A multiline string where one of the lines starts with\n-- two dashes\nfollowed by another line",\n["trailing_comment"] = "A string with" -- a trailing comment\n}\n-- ending comment'
+ dict = {
+ "multiline_string": "A multiline string where one of the lines starts with\n-- two dashes",
+ "another_multiline_string": "A multiline string where one of the lines starts with\n-- two dashes\nfollowed by another line",
+ "trailing_comment": "A string with"
+ }
+ self.assertEqual(slpp.decode(lua), dict)
+
if __name__ == '__main__':
unittest.main()
| lua.decode('"--3"') fails
This looks like a bug in the string parsing to me - as if the parser tries to detect comments inside literal strings.
`'--3'` is a perfectly valid lua string, of course. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests.py::TestSLPP::test_comments"
] | [
"tests.py::TestUtilityFunctions::test_differ",
"tests.py::TestUtilityFunctions::test_is_iterator",
"tests.py::TestSLPP::test_basic",
"tests.py::TestSLPP::test_bool",
"tests.py::TestSLPP::test_consistency",
"tests.py::TestSLPP::test_nil",
"tests.py::TestSLPP::test_numbers",
"tests.py::TestSLPP::test_string",
"tests.py::TestSLPP::test_table",
"tests.py::TestSLPP::test_unicode"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-17T13:03:09Z" | mit |
|
SmileyChris__django-countries-339 | diff --git a/django_countries/fields.py b/django_countries/fields.py
index 3b3db00..ee211f1 100644
--- a/django_countries/fields.py
+++ b/django_countries/fields.py
@@ -279,7 +279,7 @@ class CountryField(CharField):
kwargs["max_length"] = len(self.countries) * 3 - 1
else:
kwargs["max_length"] = 2
- super(CharField, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def check(self, **kwargs):
errors = super().check(**kwargs)
| SmileyChris/django-countries | 72040a01239681bf0a8b1da93e46154fbaac6a48 | diff --git a/django_countries/tests/test_fields.py b/django_countries/tests/test_fields.py
index 43316ca..983dc1b 100644
--- a/django_countries/tests/test_fields.py
+++ b/django_countries/tests/test_fields.py
@@ -1,7 +1,9 @@
import pickle
import tempfile
from unittest import mock
+from unittest.case import skipUnless
+import django
from django.db import models
from django.core import validators, checks
from django.core.management import call_command
@@ -17,7 +19,20 @@ from django_countries.tests import forms, custom_countries
from django_countries.tests.models import Person, AllowNull, MultiCountry, WithProp
+# Django 3.2 introduced a db_collation attr on fields.
+def has_db_collation():
+ major, minor = django.VERSION[0:2]
+ return (major > 3) or (major==3 and minor >=2)
+
+
class TestCountryField(TestCase):
+
+ @skipUnless(has_db_collation(), "Django version < 3.2")
+ def test_db_collation(self):
+ # test fix for issue 338
+ country = fields.CountryField()
+ self.assertTrue(hasattr(country, "db_collation"))
+
def test_logic(self):
person = Person(name="Chris Beaven", country="NZ")
| Applying migrations with CountryField fails with Django 3.2
I've created a simple model with a `CountryField`. Creating a migration for this model works fine (at least when using the latest version from Git). However, applying the migration fails (traceback included below).
**Environment:**
- Django 3.2b1 (from PyPI)
- django-countries 7.1.dev0 (latest version from Git)
**Traceback (most recent call last):**
```
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle
self.check(databases=[database])
File "venv/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check
all_issues = checks.run_checks(
File "venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "venv/lib/python3.8/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models
errors.extend(model.check(**kwargs))
File "venv/lib/python3.8/site-packages/django/db/models/base.py", line 1271, in check
*cls._check_fields(**kwargs),
File "venv/lib/python3.8/site-packages/django/db/models/base.py", line 1380, in _check_fields
errors.extend(field.check(**kwargs))
File "venv/lib/python3.8/site-packages/django_countries/fields.py", line 285, in check
errors = super().check(**kwargs)
File "venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1013, in check
*self._check_db_collation(databases),
File "venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1045, in _check_db_collation
self.db_collation is None or
AttributeError: 'CountryField' object has no attribute 'db_collation'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"django_countries/tests/test_fields.py::TestCountryField::test_COUNTRIES_FLAG_URL_setting",
"django_countries/tests/test_fields.py::TestCountryField::test_blank",
"django_countries/tests/test_fields.py::TestCountryField::test_create_modelform",
"django_countries/tests/test_fields.py::TestCountryField::test_custom_field_flag_url",
"django_countries/tests/test_fields.py::TestCountryField::test_custom_field_str_attr",
"django_countries/tests/test_fields.py::TestCountryField::test_db_collation",
"django_countries/tests/test_fields.py::TestCountryField::test_deconstruct",
"django_countries/tests/test_fields.py::TestCountryField::test_deferred",
"django_countries/tests/test_fields.py::TestCountryField::test_flag",
"django_countries/tests/test_fields.py::TestCountryField::test_flag_css",
"django_countries/tests/test_fields.py::TestCountryField::test_flag_css_blank",
"django_countries/tests/test_fields.py::TestCountryField::test_get_property_from_class",
"django_countries/tests/test_fields.py::TestCountryField::test_in",
"django_countries/tests/test_fields.py::TestCountryField::test_len",
"django_countries/tests/test_fields.py::TestCountryField::test_logic",
"django_countries/tests/test_fields.py::TestCountryField::test_lookup_country",
"django_countries/tests/test_fields.py::TestCountryField::test_lookup_text",
"django_countries/tests/test_fields.py::TestCountryField::test_model_with_prop",
"django_countries/tests/test_fields.py::TestCountryField::test_multi_null_country",
"django_countries/tests/test_fields.py::TestCountryField::test_name",
"django_countries/tests/test_fields.py::TestCountryField::test_null",
"django_countries/tests/test_fields.py::TestCountryField::test_nullable_deferred",
"django_countries/tests/test_fields.py::TestCountryField::test_only",
"django_countries/tests/test_fields.py::TestCountryField::test_render_form",
"django_countries/tests/test_fields.py::TestCountryField::test_save_empty_country",
"django_countries/tests/test_fields.py::TestCountryField::test_text",
"django_countries/tests/test_fields.py::TestCountryField::test_unicode_flag_blank",
"django_countries/tests/test_fields.py::TestCountryField::test_unicode_flags",
"django_countries/tests/test_fields.py::TestValidation::test_get_prep_value_empty_string",
"django_countries/tests/test_fields.py::TestValidation::test_get_prep_value_invalid_type",
"django_countries/tests/test_fields.py::TestValidation::test_get_prep_value_none",
"django_countries/tests/test_fields.py::TestValidation::test_validate",
"django_countries/tests/test_fields.py::TestValidation::test_validate_alpha3",
"django_countries/tests/test_fields.py::TestValidation::test_validate_empty",
"django_countries/tests/test_fields.py::TestValidation::test_validate_invalid",
"django_countries/tests/test_fields.py::TestValidation::test_validate_multiple",
"django_countries/tests/test_fields.py::TestValidation::test_validate_multiple_empty",
"django_countries/tests/test_fields.py::TestValidation::test_validate_multiple_invalid",
"django_countries/tests/test_fields.py::TestValidation::test_validate_multiple_uneditable",
"django_countries/tests/test_fields.py::TestCountryCustom::test_deconstruct",
"django_countries/tests/test_fields.py::TestCountryCustom::test_field",
"django_countries/tests/test_fields.py::TestCountryCustom::test_name",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_all_countries",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_deconstruct",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_empty",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_empty_save",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_multiple",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_set_countries",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_set_country",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_set_list",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_set_text",
"django_countries/tests/test_fields.py::TestCountryMultiple::test_single",
"django_countries/tests/test_fields.py::TestCountryObject::test_alpha2_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_alpha2_code_invalid",
"django_countries/tests/test_fields.py::TestCountryObject::test_alpha3",
"django_countries/tests/test_fields.py::TestCountryObject::test_alpha3_invalid",
"django_countries/tests/test_fields.py::TestCountryObject::test_country_from_blank_ioc_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_country_from_ioc_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_country_from_nonexistence_ioc_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_empty_flag_url",
"django_countries/tests/test_fields.py::TestCountryObject::test_extensions",
"django_countries/tests/test_fields.py::TestCountryObject::test_flag_on_empty_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_hash",
"django_countries/tests/test_fields.py::TestCountryObject::test_ioc_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric_code",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric_code_invalid",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric_invalid",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric_padded",
"django_countries/tests/test_fields.py::TestCountryObject::test_numeric_padded_invalid",
"django_countries/tests/test_fields.py::TestCountryObject::test_repr",
"django_countries/tests/test_fields.py::TestCountryObject::test_str",
"django_countries/tests/test_fields.py::TestCountryObject::test_str_attr",
"django_countries/tests/test_fields.py::TestModelForm::test_blank_choice",
"django_countries/tests/test_fields.py::TestModelForm::test_blank_choice_label",
"django_countries/tests/test_fields.py::TestModelForm::test_no_blank_choice",
"django_countries/tests/test_fields.py::TestModelForm::test_translated_choices",
"django_countries/tests/test_fields.py::TestModelForm::test_validation",
"django_countries/tests/test_fields.py::TestPickling::test_custom_country_pickling",
"django_countries/tests/test_fields.py::TestPickling::test_standard_country_pickling",
"django_countries/tests/test_fields.py::TestLoadData::test_basic"
] | [] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-03-01T15:40:24Z" | mit |
|
SparkPost__python-sparkpost-141 | diff --git a/sparkpost/transmissions.py b/sparkpost/transmissions.py
index 3586e2f..667b891 100644
--- a/sparkpost/transmissions.py
+++ b/sparkpost/transmissions.py
@@ -4,6 +4,7 @@ import json
from email.utils import parseaddr
from .base import Resource
+from .exceptions import SparkPostException
try:
@@ -137,6 +138,10 @@ class Transmissions(Resource):
return parsed_address
def _extract_recipients(self, recipients):
+
+ if not (isinstance(recipients, (list, dict))):
+ raise SparkPostException('recipients must be a list or dict')
+
formatted_recipients = []
for recip in recipients:
if isinstance(recip, string_types):
| SparkPost/python-sparkpost | 8808080ed4cfe17eadb0114eb5b7c12fb311e7a7 | diff --git a/test/test_transmissions.py b/test/test_transmissions.py
index 9847fb2..a5d6ae0 100644
--- a/test/test_transmissions.py
+++ b/test/test_transmissions.py
@@ -9,7 +9,7 @@ import six
from sparkpost import SparkPost
from sparkpost import Transmissions
-from sparkpost.exceptions import SparkPostAPIException
+from sparkpost.exceptions import SparkPostAPIException, SparkPostException
def test_translate_keys_with_list():
@@ -29,6 +29,12 @@ def test_translate_keys_with_recips():
{'address': {'email': 'foobar'}}]
+def test_exceptions_for_recipients():
+ t = Transmissions('uri', 'key')
+ with pytest.raises(SparkPostException):
+ t._translate_keys(recipients='test')
+
+
def test_translate_keys_with_unicode_recips():
t = Transmissions('uri', 'key')
results = t._translate_keys(recipients=[u'[email protected]',
| Validate recipients as list or dict
We currently don't do any input validation for recipients. It'd be pretty simple to check for list or dict and throw an appropriate exception. This will help avoid some confusion around the error received when a string, for example, is passed. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_transmissions.py::test_exceptions_for_recipients"
] | [
"test/test_transmissions.py::test_translate_keys_with_recips",
"test/test_transmissions.py::test_format_header_to",
"test/test_transmissions.py::test_cc_with_sub_data",
"test/test_transmissions.py::test_success_get",
"test/test_transmissions.py::test_translate_keys_with_unicode_recips",
"test/test_transmissions.py::test_translate_keys_with_list",
"test/test_transmissions.py::test_success_send_with_attachments",
"test/test_transmissions.py::test_success_delete",
"test/test_transmissions.py::test_fail_get",
"test/test_transmissions.py::test_translate_keys_with_multiple_cc",
"test/test_transmissions.py::test_translate_keys_with_bcc",
"test/test_transmissions.py::test_translate_keys_with_cc",
"test/test_transmissions.py::test_fail_send",
"test/test_transmissions.py::test_success_send",
"test/test_transmissions.py::test_translate_keys_with_inline_css",
"test/test_transmissions.py::test_fail_delete",
"test/test_transmissions.py::test_translate_keys_for_from_email",
"test/test_transmissions.py::test_translate_keys_for_email_parsing",
"test/test_transmissions.py::test_success_send_with_inline_images",
"test/test_transmissions.py::test_success_list"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2017-03-02T22:01:40Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-12T14:58:47Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-26T09:01:21Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T06:48:44Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T02:30:52Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-15T20:25:45Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-06T06:08:27Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-27T12:55:47Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-01T08:59:17Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-07T09:56:44Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-30T11:43:01Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-31T22:19:33Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-11T19:51:10Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-30T18:07:16Z" | bsd-3-clause |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-03T16:30:39Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-04T21:06:13Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-28T17:07:11Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-28T21:01:46Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-31T19:37:47Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-07T18:04:40Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-31T20:39:21Z" | bsd-3-clause |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-01T05:42:11Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-04T08:47:59Z" | bsd-3-clause |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-23T17:54:50Z" | bsd-3-clause |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-26T14:24:02Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-03T19:38:43Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T08:11:23Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-25T10:17:01Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-17T13:04:32Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-08T22:27:18Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T16:21:03Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-14T11:28:31Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_visibility_change.py::test_visibility_changes"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-12-21T14:35:07Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-21T22:58:36Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-23T15:09:12Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T17:34:37Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T15:18:25Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-20T11:41:22Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-03T10:38:45Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-09T14:57:44Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-09T15:57:46Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-15T12:23:11Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-16T10:15:16Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-22T12:55:30Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-30T03:54:01Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-07T11:37:25Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-30T12:55:51Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T15:15:47Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-22T09:26:53Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-22T09:52:46Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-22T14:22:57Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T17:16:33Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T15:46:23Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-17T09:38:33Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-20T16:42:54Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-25T09:56:48Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-27T02:55:55Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-09T17:49:08Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-13T14:10:51Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-05T17:55:54Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-16T14:55:05Z" | mit |
|
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! ",
+ "&ersand",
+ "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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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[&ersand]",
"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-16T17:31:17Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T09:37:08Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-05T20:44:48Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-19T14:50:01Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-28T14:03:23Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-27T14:12:56Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-28T09:27:13Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-29T09:34:12Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-03T16:48:13Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-20T22:15:31Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-18T12:33:00Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-19T18:21:23Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-14T00:18:58Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-21T18:19:18Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-16T17:28:19Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-10T15:08:12Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-22T13:46:43Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-23T11:06:36Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-18T10:17:34Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-08T17:34:17Z" | apache-2.0 |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-24T04:09:07Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-25T22:44:55Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-02T08:20:27Z" | mit |
|
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 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"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-26T10:44:15Z" | mit |