instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
tobymao__sqlglot-3360
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 71339b88..2e53a675 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -518,6 +518,7 @@ class Postgres(Dialect): exp.Variance: rename_func("VAR_SAMP"), exp.Xor: bool_xor_sql, } + TRANSFORMS.pop(exp.CommentColumnConstraint) PROPERTIES_LOCATION = { **generator.Generator.PROPERTIES_LOCATION, @@ -526,6 +527,10 @@ class Postgres(Dialect): exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, } + def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -> str: + self.unsupported("Column comments are not supported in the CREATE statement") + return "" + def unnest_sql(self, expression: exp.Unnest) -> str: if len(expression.expressions) == 1: from sqlglot.optimizer.annotate_types import annotate_types diff --git a/sqlglot/lineage.py b/sqlglot/lineage.py index c91bb36e..f4a3dec5 100644 --- a/sqlglot/lineage.py +++ b/sqlglot/lineage.py @@ -129,12 +129,6 @@ def to_node( reference_node_name: t.Optional[str] = None, trim_selects: bool = True, ) -> Node: - source_names = { - dt.alias: dt.comments[0].split()[1] - for dt in scope.derived_tables - if dt.comments and dt.comments[0].startswith("source: ") - } - # Find the specific select clause that is the source of the column we want. # This can either be a specific, named select or a generic `*` clause. select = ( @@ -242,6 +236,19 @@ def to_node( # If the source is a UDTF find columns used in the UTDF to generate the table if isinstance(source, exp.UDTF): source_columns |= set(source.find_all(exp.Column)) + derived_tables = [ + source.expression.parent + for source in scope.sources.values() + if isinstance(source, Scope) and source.is_derived_table + ] + else: + derived_tables = scope.derived_tables + + source_names = { + dt.alias: dt.comments[0].split()[1] + for dt in derived_tables + if dt.comments and dt.comments[0].startswith("source: ") + } for c in source_columns: table = c.table diff --git a/sqlglot/optimizer/__init__.py b/sqlglot/optimizer/__init__.py index 34ea6cb1..050f246c 100644 --- a/sqlglot/optimizer/__init__.py +++ b/sqlglot/optimizer/__init__.py @@ -1,11 +1,11 @@ # ruff: noqa: F401 -from sqlglot.optimizer.optimizer import RULES, optimize +from sqlglot.optimizer.optimizer import RULES as RULES, optimize as optimize from sqlglot.optimizer.scope import ( - Scope, - build_scope, - find_all_in_scope, - find_in_scope, - traverse_scope, - walk_in_scope, + Scope as Scope, + build_scope as build_scope, + find_all_in_scope as find_all_in_scope, + find_in_scope as find_in_scope, + traverse_scope as traverse_scope, + walk_in_scope as walk_in_scope, )
tobymao/sqlglot
f697cb16b6d744253febb2f83476853e63e06f88
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 5a55a7d6..1ed7d82f 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -314,6 +314,12 @@ class TestPostgres(Validator): ) self.validate_identity("SELECT * FROM t1*", "SELECT * FROM t1") + self.validate_all( + "CREATE TABLE t (c INT)", + read={ + "mysql": "CREATE TABLE t (c INT COMMENT 'comment')", + }, + ) self.validate_all( 'SELECT * FROM "test_table" ORDER BY RANDOM() LIMIT 5', write={ diff --git a/tests/test_lineage.py b/tests/test_lineage.py index c782d9ae..cbadf7bb 100644 --- a/tests/test_lineage.py +++ b/tests/test_lineage.py @@ -224,16 +224,50 @@ class TestLineage(unittest.TestCase): downstream.source.sql(dialect="snowflake"), "LATERAL FLATTEN(INPUT => TEST_TABLE.RESULT, OUTER => TRUE) AS FLATTENED(SEQ, KEY, PATH, INDEX, VALUE, THIS)", ) - self.assertEqual( - downstream.expression.sql(dialect="snowflake"), - "VALUE", - ) + self.assertEqual(downstream.expression.sql(dialect="snowflake"), "VALUE") self.assertEqual(len(downstream.downstream), 1) downstream = downstream.downstream[0] self.assertEqual(downstream.name, "TEST_TABLE.RESULT") self.assertEqual(downstream.source.sql(dialect="snowflake"), "TEST_TABLE AS TEST_TABLE") + node = lineage( + "FIELD", + "SELECT FLATTENED.VALUE:field::text AS FIELD FROM SNOWFLAKE.SCHEMA.MODEL AS MODEL_ALIAS, LATERAL FLATTEN(INPUT => MODEL_ALIAS.A) AS FLATTENED", + schema={"SNOWFLAKE": {"SCHEMA": {"TABLE": {"A": "integer"}}}}, + sources={"SNOWFLAKE.SCHEMA.MODEL": "SELECT A FROM SNOWFLAKE.SCHEMA.TABLE"}, + dialect="snowflake", + ) + self.assertEqual(node.name, "FIELD") + + downstream = node.downstream[0] + self.assertEqual(downstream.name, "FLATTENED.VALUE") + self.assertEqual( + downstream.source.sql(dialect="snowflake"), + "LATERAL FLATTEN(INPUT => MODEL_ALIAS.A) AS FLATTENED(SEQ, KEY, PATH, INDEX, VALUE, THIS)", + ) + self.assertEqual(downstream.expression.sql(dialect="snowflake"), "VALUE") + self.assertEqual(len(downstream.downstream), 1) + + downstream = downstream.downstream[0] + self.assertEqual(downstream.name, "MODEL_ALIAS.A") + self.assertEqual(downstream.source_name, "SNOWFLAKE.SCHEMA.MODEL") + self.assertEqual( + downstream.source.sql(dialect="snowflake"), + "SELECT TABLE.A AS A FROM SNOWFLAKE.SCHEMA.TABLE AS TABLE", + ) + self.assertEqual(downstream.expression.sql(dialect="snowflake"), "TABLE.A AS A") + self.assertEqual(len(downstream.downstream), 1) + + downstream = downstream.downstream[0] + self.assertEqual(downstream.name, "TABLE.A") + self.assertEqual( + downstream.source.sql(dialect="snowflake"), "SNOWFLAKE.SCHEMA.TABLE AS TABLE" + ) + self.assertEqual( + downstream.expression.sql(dialect="snowflake"), "SNOWFLAKE.SCHEMA.TABLE AS TABLE" + ) + def test_subquery(self) -> None: node = lineage( "output",
No `source_name` in column lineage with `LATERAL FLATTEN` **Fully reproducible code snippet** ```python from sqlglot.lineage import lineage query = """SELECT FLATTENED.VALUE:field::text AS FIELD FROM SNOWFLAKE.SCHEMA.MODEL AS MODEL_ALIAS, LATERAL FLATTEN(INPUT => MODEL_ALIAS.A ) AS FLATTENED """ sources = {"SNOWFLAKE.SCHEMA.MODEL": "SELECT A FROM SNOWFLAKE.SCHEMA.TABLE"} schemas = { "SCHEMA": { "TABLE": {"A": "integer"}, } } result = lineage("FIELD", query, schemas, sources, dialect="snowflake") for node in result.walk(): print(f"Name: {node.name}, Source: {node.source_name}") ``` The output is: ``` Name: FIELD, Source: Name: FLATTENED.VALUE, Source: Name: MODEL_ALIAS.A, Source: Name: TABLE.A, Source: ``` I would expect the `MODEL_ALIAS.A` node to have `source_name` equal to `SNOWFLAKE.SCHEMA.MODEL` because that's the source (`sources` argument to the `lineage` function) where that column appears. That's how that field seems to work in other queries. For example, changing the query to: ```sql SELECT MODEL_ALIAS.A AS FIELD FROM SNOWFLAKE.SCHEMA.MODEL AS MODEL_ALIAS ``` gives: ``` Name: FIELD, Source: Name: MODEL_ALIAS.A, Source: SNOWFLAKE.SCHEMA.MODEL Name: TABLE.A, Source: ``` I believe the root cause is that the expanded-and-qualified query has a `source: ` comment after the the first element in the `FROM` clause but not for the `LATERAL FLATTEN`?
0.0
f697cb16b6d744253febb2f83476853e63e06f88
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres", "tests/test_lineage.py::TestLineage::test_lineage_lateral_flatten" ]
[ "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance", "tests/test_lineage.py::TestLineage::test_ddl_lineage", "tests/test_lineage.py::TestLineage::test_lineage", "tests/test_lineage.py::TestLineage::test_lineage_cte_name_appears_in_schema", "tests/test_lineage.py::TestLineage::test_lineage_cte_union", "tests/test_lineage.py::TestLineage::test_lineage_external_col", "tests/test_lineage.py::TestLineage::test_lineage_normalize", "tests/test_lineage.py::TestLineage::test_lineage_source_union", "tests/test_lineage.py::TestLineage::test_lineage_source_with_cte", "tests/test_lineage.py::TestLineage::test_lineage_source_with_star", "tests/test_lineage.py::TestLineage::test_lineage_sql_with_cte", "tests/test_lineage.py::TestLineage::test_lineage_union", "tests/test_lineage.py::TestLineage::test_lineage_values", "tests/test_lineage.py::TestLineage::test_select_star", "tests/test_lineage.py::TestLineage::test_subquery", "tests/test_lineage.py::TestLineage::test_trim", "tests/test_lineage.py::TestLineage::test_unnest" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-26 13:03:48+00:00
mit
6,035
tobymao__sqlglot-3385
diff --git a/sqlglot/dialects/trino.py b/sqlglot/dialects/trino.py index 457e2f05..4b5f8e0d 100644 --- a/sqlglot/dialects/trino.py +++ b/sqlglot/dialects/trino.py @@ -1,7 +1,7 @@ from __future__ import annotations from sqlglot import exp -from sqlglot.dialects.dialect import merge_without_target_sql +from sqlglot.dialects.dialect import merge_without_target_sql, trim_sql from sqlglot.dialects.presto import Presto @@ -9,12 +9,19 @@ class Trino(Presto): SUPPORTS_USER_DEFINED_TYPES = False LOG_BASE_FIRST = True + class Parser(Presto.Parser): + FUNCTION_PARSERS = { + **Presto.Parser.FUNCTION_PARSERS, + "TRIM": lambda self: self._parse_trim(), + } + class Generator(Presto.Generator): TRANSFORMS = { **Presto.Generator.TRANSFORMS, exp.ArraySum: lambda self, e: f"REDUCE({self.sql(e, 'this')}, 0, (acc, x) -> acc + x, acc -> acc)", exp.Merge: merge_without_target_sql, + exp.Trim: trim_sql, } SUPPORTED_JSON_PATH_PARTS = {
tobymao/sqlglot
f85b8e1017acb9d6b64489076a461d647076b419
diff --git a/tests/dialects/test_trino.py b/tests/dialects/test_trino.py new file mode 100644 index 00000000..ccc1407f --- /dev/null +++ b/tests/dialects/test_trino.py @@ -0,0 +1,18 @@ +from tests.dialects.test_dialect import Validator + + +class TestTrino(Validator): + dialect = "trino" + + def test_trim(self): + self.validate_identity("SELECT TRIM('!' FROM '!foo!')") + self.validate_identity("SELECT TRIM(BOTH '$' FROM '$var$')") + self.validate_identity("SELECT TRIM(TRAILING 'ER' FROM UPPER('worker'))") + self.validate_identity( + "SELECT TRIM(LEADING FROM ' abcd')", + "SELECT LTRIM(' abcd')", + ) + self.validate_identity( + "SELECT TRIM('!foo!', '!')", + "SELECT TRIM('!' FROM '!foo!')", + )
Can't parse `trim` in TrinoSQL **Fully reproducible code snippet** Please include a fully reproducible code snippet or the input sql, dialect, and expected output. ```python import sqlglot print(sqlglot.__version__) sql = "SELECT trim(',' FROM some_col);" result = sqlglot.parse(sql, read="trino") print(repr(result)) ``` Expected: ``` 23.12.2 [Select( expressions=[ Trim( this=Column( this=Identifier(this=some_col, quoted=False)), expression=Literal(this=,, is_string=True))])] ``` Got: ``` 23.12.2 Traceback (most recent call last): File "proof.py", line 7, in <module> result = sqlglot.parse(sql, read="trino") File ".../python3.8/site-packages/sqlglot/__init__.py", line 102, in parse return Dialect.get_or_raise(read or dialect).parse(sql, **opts) File ".../python3.8/site-packages/sqlglot/dialects/dialect.py", line 506, in parse return self.parser(**opts).parse(self.tokenize(sql), sql) File ".../python3.8/site-packages/sqlglot/parser.py", line 1175, in parse return self._parse( File ".../python3.8/site-packages/sqlglot/parser.py", line 1241, in _parse expressions.append(parse_method(self)) File ".../python3.8/site-packages/sqlglot/parser.py", line 1476, in _parse_statement expression = self._parse_set_operations(expression) if expression else self._parse_select() File ".../python3.8/site-packages/sqlglot/parser.py", line 2532, in _parse_select projections = self._parse_projections() File ".../python3.8/site-packages/sqlglot/parser.py", line 2480, in _parse_projections return self._parse_expressions() File ".../python3.8/site-packages/sqlglot/parser.py", line 5695, in _parse_expressions return self._parse_csv(self._parse_expression) File ".../python3.8/site-packages/sqlglot/parser.py", line 5649, in _parse_csv parse_result = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3805, in _parse_expression return self._parse_alias(self._parse_conjunction()) File ".../python3.8/site-packages/sqlglot/parser.py", line 3808, in _parse_conjunction return self._parse_tokens(self._parse_equality, self.CONJUNCTION) File ".../python3.8/site-packages/sqlglot/parser.py", line 5663, in _parse_tokens this = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3811, in _parse_equality return self._parse_tokens(self._parse_comparison, self.EQUALITY) File ".../python3.8/site-packages/sqlglot/parser.py", line 5663, in _parse_tokens this = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3814, in _parse_comparison return self._parse_tokens(self._parse_range, self.COMPARISON) File ".../python3.8/site-packages/sqlglot/parser.py", line 5663, in _parse_tokens this = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3817, in _parse_range this = this or self._parse_bitwise() File ".../python3.8/site-packages/sqlglot/parser.py", line 3941, in _parse_bitwise this = self._parse_term() File ".../python3.8/site-packages/sqlglot/parser.py", line 3973, in _parse_term return self._parse_tokens(self._parse_factor, self.TERM) File ".../python3.8/site-packages/sqlglot/parser.py", line 5663, in _parse_tokens this = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3977, in _parse_factor this = parse_method() File ".../python3.8/site-packages/sqlglot/parser.py", line 3998, in _parse_unary return self._parse_at_time_zone(self._parse_type()) File ".../python3.8/site-packages/sqlglot/parser.py", line 4020, in _parse_type this = self._parse_column() File ".../python3.8/site-packages/sqlglot/parser.py", line 4220, in _parse_column this = self._parse_column_reference() File ".../python3.8/site-packages/sqlglot/parser.py", line 4224, in _parse_column_reference this = self._parse_field() File ".../python3.8/site-packages/sqlglot/parser.py", line 4347, in _parse_field field = self._parse_primary() or self._parse_function( File ".../python3.8/site-packages/sqlglot/parser.py", line 4370, in _parse_function func = self._parse_function_call( File ".../python3.8/site-packages/sqlglot/parser.py", line 4458, in _parse_function_call self._match_r_paren(this) File ".../python3.8/site-packages/sqlglot/parser.py", line 6196, in _match_r_paren self.raise_error("Expecting )") File ".../python3.8/site-packages/sqlglot/parser.py", line 1285, in raise_error raise error sqlglot.errors.ParseError: Expecting ). Line 1, Col: 20. SELECT trim(',' FROM some_col); ``` **Official Documentation** https://trino.io/docs/current/functions/string.html?highlight=trim#trim
0.0
f85b8e1017acb9d6b64489076a461d647076b419
[ "tests/dialects/test_trino.py::TestTrino::test_trim" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2024-04-30 21:59:25+00:00
mit
6,036
tobymao__sqlglot-805
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py index 0ab32188..6be68ace 100644 --- a/sqlglot/dialects/bigquery.py +++ b/sqlglot/dialects/bigquery.py @@ -110,17 +110,17 @@ class BigQuery(Dialect): KEYWORDS = { **tokens.Tokenizer.KEYWORDS, + "BEGIN": TokenType.COMMAND, + "BEGIN TRANSACTION": TokenType.BEGIN, "CURRENT_DATETIME": TokenType.CURRENT_DATETIME, "CURRENT_TIME": TokenType.CURRENT_TIME, "GEOGRAPHY": TokenType.GEOGRAPHY, - "INT64": TokenType.BIGINT, "FLOAT64": TokenType.DOUBLE, + "INT64": TokenType.BIGINT, + "NOT DETERMINISTIC": TokenType.VOLATILE, "QUALIFY": TokenType.QUALIFY, "UNKNOWN": TokenType.NULL, "WINDOW": TokenType.WINDOW, - "NOT DETERMINISTIC": TokenType.VOLATILE, - "BEGIN": TokenType.COMMAND, - "BEGIN TRANSACTION": TokenType.BEGIN, } KEYWORDS.pop("DIV") @@ -131,6 +131,7 @@ class BigQuery(Dialect): "DATE_ADD": _date_add(exp.DateAdd), "DATETIME_ADD": _date_add(exp.DatetimeAdd), "DIV": lambda args: exp.IntDiv(this=seq_get(args, 0), expression=seq_get(args, 1)), + "REGEXP_CONTAINS": exp.RegexpLike.from_arg_list, "TIME_ADD": _date_add(exp.TimeAdd), "TIMESTAMP_ADD": _date_add(exp.TimestampAdd), "DATE_SUB": _date_add(exp.DateSub), @@ -183,6 +184,7 @@ class BigQuery(Dialect): exp.VolatilityProperty: lambda self, e: f"DETERMINISTIC" if e.name == "IMMUTABLE" else "NOT DETERMINISTIC", + exp.RegexpLike: rename_func("REGEXP_CONTAINS"), } TYPE_MAPPING = {
tobymao/sqlglot
3d0216fd102e7dbe585999e9cb961f31cd5bfa53
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py index 5c5a7713..1d60ec65 100644 --- a/tests/dialects/test_bigquery.py +++ b/tests/dialects/test_bigquery.py @@ -6,6 +6,11 @@ class TestBigQuery(Validator): dialect = "bigquery" def test_bigquery(self): + self.validate_all( + "REGEXP_CONTAINS('foo', '.*')", + read={"bigquery": "REGEXP_CONTAINS('foo', '.*')"}, + write={"mysql": "REGEXP_LIKE('foo', '.*')"}, + ), self.validate_all( '"""x"""', write={
Functions transpiled incorrectly from MySQL to BigQuery ```python import sqlglot print(sqlglot.transpile("SELECT 'foo' regexp '.*';", read="mysql", write="bigquery")) ``` This currently transpiles to `SELECT REGEXP_LIKE('foo', '.*')` which is not valid for BigQuery (I guess the correct function would be `REGEXP_CONTAINS`). Overall, how robust should I expect transpilation to be? Are certain language pairs better supported than others? Are functions more problematic than other constructs?
0.0
3d0216fd102e7dbe585999e9cb961f31cd5bfa53
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery" ]
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-12-05 22:59:24+00:00
mit
6,037
tobymao__sqlglot-902
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index ef21f0bb..26d8f945 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -2130,6 +2130,7 @@ class DataType(Expression): JSON = auto() JSONB = auto() INTERVAL = auto() + TIME = auto() TIMESTAMP = auto() TIMESTAMPTZ = auto() TIMESTAMPLTZ = auto() diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 133bf7f8..370b8a4f 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -112,6 +112,7 @@ class Parser(metaclass=_Parser): TokenType.JSON, TokenType.JSONB, TokenType.INTERVAL, + TokenType.TIME, TokenType.TIMESTAMP, TokenType.TIMESTAMPTZ, TokenType.TIMESTAMPLTZ, @@ -319,6 +320,7 @@ class Parser(metaclass=_Parser): } TIMESTAMPS = { + TokenType.TIME, TokenType.TIMESTAMP, TokenType.TIMESTAMPTZ, TokenType.TIMESTAMPLTZ, @@ -1915,7 +1917,10 @@ class Parser(metaclass=_Parser): ): value = exp.DataType(this=exp.DataType.Type.TIMESTAMPLTZ, expressions=expressions) elif self._match(TokenType.WITHOUT_TIME_ZONE): - value = exp.DataType(this=exp.DataType.Type.TIMESTAMP, expressions=expressions) + if type_token == TokenType.TIME: + value = exp.DataType(this=exp.DataType.Type.TIME, expressions=expressions) + else: + value = exp.DataType(this=exp.DataType.Type.TIMESTAMP, expressions=expressions) maybe_func = maybe_func and value is None diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py index 0efa7d02..8c5f13bd 100644 --- a/sqlglot/tokens.py +++ b/sqlglot/tokens.py @@ -86,6 +86,7 @@ class TokenType(AutoName): VARBINARY = auto() JSON = auto() JSONB = auto() + TIME = auto() TIMESTAMP = auto() TIMESTAMPTZ = auto() TIMESTAMPLTZ = auto() @@ -671,6 +672,7 @@ class Tokenizer(metaclass=_Tokenizer): "BLOB": TokenType.VARBINARY, "BYTEA": TokenType.VARBINARY, "VARBINARY": TokenType.VARBINARY, + "TIME": TokenType.TIME, "TIMESTAMP": TokenType.TIMESTAMP, "TIMESTAMPTZ": TokenType.TIMESTAMPTZ, "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ,
tobymao/sqlglot
70ebdf63648e94bdb13c68fddd6ee5db31fcda7d
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 1e048d5b..583d3496 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -122,6 +122,10 @@ class TestPostgres(Validator): "TO_TIMESTAMP(123::DOUBLE PRECISION)", write={"postgres": "TO_TIMESTAMP(CAST(123 AS DOUBLE PRECISION))"}, ) + self.validate_all( + "SELECT to_timestamp(123)::time without time zone", + write={"postgres": "SELECT CAST(TO_TIMESTAMP(123) AS TIME)"}, + ) self.validate_identity( "CREATE TABLE A (LIKE B INCLUDING CONSTRAINT INCLUDING COMPRESSION EXCLUDING COMMENTS)"
Postgres parse error on cast to time The following valid Postgres query produces a parsing error: ```python import sqlglot sql = """ SELECT to_timestamp(123)::time without time zone """ sqlglot.parse_one(sql, read="postgres") ```
0.0
70ebdf63648e94bdb13c68fddd6ee5db31fcda7d
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres" ]
[ "tests/dialects/test_postgres.py::TestPostgres::test_ddl" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-09 17:34:44+00:00
mit
6,038
tobymao__sqlglot-911
diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py index 3ef467b1..04d46d28 100644 --- a/sqlglot/dialects/clickhouse.py +++ b/sqlglot/dialects/clickhouse.py @@ -1,5 +1,7 @@ from __future__ import annotations +import typing as t + from sqlglot import exp, generator, parser, tokens from sqlglot.dialects.dialect import Dialect, inline_array_sql, var_map_sql from sqlglot.parser import parse_var_map @@ -22,6 +24,7 @@ class ClickHouse(Dialect): KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "ASOF": TokenType.ASOF, + "GLOBAL": TokenType.GLOBAL, "DATETIME64": TokenType.DATETIME, "FINAL": TokenType.FINAL, "FLOAT32": TokenType.FLOAT, @@ -42,12 +45,27 @@ class ClickHouse(Dialect): "QUANTILEIF": lambda params, args: exp.QuantileIf(parameters=params, expressions=args), } + RANGE_PARSERS = { + **parser.Parser.RANGE_PARSERS, + TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN) + and self._parse_in(this, is_global=True), + } + JOIN_KINDS = {*parser.Parser.JOIN_KINDS, TokenType.ANY, TokenType.ASOF} # type: ignore TABLE_ALIAS_TOKENS = {*parser.Parser.TABLE_ALIAS_TOKENS} - {TokenType.ANY} # type: ignore - def _parse_table(self, schema=False): - this = super()._parse_table(schema) + def _parse_in( + self, this: t.Optional[exp.Expression], is_global: bool = False + ) -> exp.Expression: + this = super()._parse_in(this) + this.set("is_global", is_global) + return this + + def _parse_table( + self, schema: bool = False, alias_tokens: t.Optional[t.Collection[TokenType]] = None + ) -> t.Optional[exp.Expression]: + this = super()._parse_table(schema=schema, alias_tokens=alias_tokens) if self._match(TokenType.FINAL): this = self.expression(exp.Final, this=this) diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index 2167c675..c78387d8 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -2449,6 +2449,7 @@ class In(Predicate): "query": False, "unnest": False, "field": False, + "is_global": False, } @@ -3002,8 +3003,10 @@ class StrToTime(Func): arg_types = {"this": True, "format": True} +# Spark allows unix_timestamp() +# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html class StrToUnix(Func): - arg_types = {"this": True, "format": True} + arg_types = {"this": False, "format": False} class NumberToStr(Func): diff --git a/sqlglot/generator.py b/sqlglot/generator.py index 21ab41eb..c690ec09 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -1141,6 +1141,8 @@ class Generator: query = expression.args.get("query") unnest = expression.args.get("unnest") field = expression.args.get("field") + is_global = " GLOBAL" if expression.args.get("is_global") else "" + if query: in_sql = self.wrap(query) elif unnest: @@ -1149,7 +1151,8 @@ class Generator: in_sql = self.sql(field) else: in_sql = f"({self.expressions(expression, flat=True)})" - return f"{self.sql(expression, 'this')} IN {in_sql}" + + return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" def in_unnest_op(self, unnest: exp.Unnest) -> str: return f"(SELECT {self.sql(unnest)})" diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py index e211ff78..32989920 100644 --- a/sqlglot/tokens.py +++ b/sqlglot/tokens.py @@ -182,6 +182,7 @@ class TokenType(AutoName): FUNCTION = auto() FROM = auto() GENERATED = auto() + GLOBAL = auto() GROUP_BY = auto() GROUPING_SETS = auto() HAVING = auto()
tobymao/sqlglot
55a21cdb4fdc235433a0cedf93a907f5a70e6d23
diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py index 6801e6f8..109e9f38 100644 --- a/tests/dialects/test_clickhouse.py +++ b/tests/dialects/test_clickhouse.py @@ -16,6 +16,7 @@ class TestClickhouse(Validator): self.validate_identity("SELECT * FROM foo ANY JOIN bla") self.validate_identity("SELECT quantile(0.5)(a)") self.validate_identity("SELECT quantiles(0.5)(a) AS x FROM t") + self.validate_identity("SELECT * FROM foo WHERE x GLOBAL IN (SELECT * FROM bar)") self.validate_all( "SELECT fname, lname, age FROM person ORDER BY age DESC NULLS FIRST, fname ASC NULLS LAST, lname", diff --git a/tests/dialects/test_spark.py b/tests/dialects/test_spark.py index 7395e727..f287a89d 100644 --- a/tests/dialects/test_spark.py +++ b/tests/dialects/test_spark.py @@ -207,6 +207,7 @@ TBLPROPERTIES ( ) def test_spark(self): + self.validate_identity("SELECT UNIX_TIMESTAMP()") self.validate_all( "ARRAY_SORT(x, (left, right) -> -1)", write={
Support "GLOBAL IN" in sql query while using transpile function I'm using CLICKHOUSE dialect ```python from sqlglot import transpile, Dialects sql = """ SELECT field FROM table WHERE (SELECT count(*) FROM q) > 0 AND scheme.field GLOBAL IN (SELECT DISTINCT field FROM q) """ sql = transpile(sql, read=Dialects.CLICKHOUSE, identify=True, pretty=True)[0] ``` Here is the ERROR that I get: ``` sqlglot.errors.ParseError: Invalid expression / Unexpected token. Line 5, Col: 22. SELECT field FROM table where (select count(*) from q) > 0 and scheme.field g̲l̲o̲b̲a̲l̲ in (select distinct field from q)) ```
0.0
55a21cdb4fdc235433a0cedf93a907f5a70e6d23
[ "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse", "tests/dialects/test_spark.py::TestSpark::test_spark" ]
[ "tests/dialects/test_spark.py::TestSpark::test_ddl", "tests/dialects/test_spark.py::TestSpark::test_hint", "tests/dialects/test_spark.py::TestSpark::test_iif", "tests/dialects/test_spark.py::TestSpark::test_to_date" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-11 13:11:31+00:00
mit
6,039
tomMoral__loky-202
diff --git a/loky/backend/context.py b/loky/backend/context.py index 0f744c5..dfeb4ed 100644 --- a/loky/backend/context.py +++ b/loky/backend/context.py @@ -211,8 +211,8 @@ class LokyContext(BaseContext): """ def Semaphore(self, value=1): """Returns a semaphore object""" - from . import synchronize - return synchronize.Semaphore(value=value) + from .synchronize import Semaphore + return Semaphore(value=value) def BoundedSemaphore(self, value): """Returns a bounded semaphore object""" diff --git a/loky/backend/reduction.py b/loky/backend/reduction.py index 0d40c5e..0bad5f6 100644 --- a/loky/backend/reduction.py +++ b/loky/backend/reduction.py @@ -188,7 +188,11 @@ def set_loky_pickler(loky_pickler=None): if sys.version_info < (3,): self.dispatch = self._dispatch.copy() else: - self.dispatch_table = self._dispatch_table.copy() + if getattr(self, "dispatch_table", None) is not None: + self.dispatch_table.update(self._dispatch_table.copy()) + else: + self.dispatch_table = self._dispatch_table.copy() + for type, reduce_func in reducers.items(): self.register(type, reduce_func) diff --git a/loky/backend/semaphore_tracker.py b/loky/backend/semaphore_tracker.py index 7d3f23e..c83b8c6 100644 --- a/loky/backend/semaphore_tracker.py +++ b/loky/backend/semaphore_tracker.py @@ -37,10 +37,13 @@ except ImportError: from .semlock import sem_unlink if sys.version_info < (3,): - BrokenPipeError = IOError + BrokenPipeError = OSError __all__ = ['ensure_running', 'register', 'unregister'] +_HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask') +_IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM) + VERBOSE = False @@ -68,6 +71,13 @@ class SemaphoreTracker(object): return # => dead, launch it again os.close(self._fd) + try: + # Clean-up to avoid dangling processes. + os.waitpid(self._pid, 0) + except OSError: + # The process was terminated or is a child from an ancestor + # of the current process. + pass self._fd = None self._pid = None @@ -80,8 +90,9 @@ class SemaphoreTracker(object): except Exception: pass - cmd = 'from {} import main; main(%d)'.format(main.__module__) r, w = os.pipe() + cmd = 'from {} import main; main({}, {})'.format( + main.__module__, r, VERBOSE) try: fds_to_pass.append(r) # process will out live us, so no need to wait on pid @@ -94,9 +105,23 @@ class SemaphoreTracker(object): import re for i in range(1, len(args)): args[i] = re.sub("-R+", "-R", args[i]) - args += ['-c', cmd % r] + args += ['-c', cmd] util.debug("launching Semaphore tracker: {}".format(args)) - pid = spawnv_passfds(exe, args, fds_to_pass) + # bpo-33613: Register a signal mask that will block the + # signals. This signal mask will be inherited by the child + # that is going to be spawned and will protect the child from a + # race condition that can make the child die before it + # registers signal handlers for SIGINT and SIGTERM. The mask is + # unregistered after spawning the child. + try: + if _HAVE_SIGMASK: + signal.pthread_sigmask(signal.SIG_BLOCK, + _IGNORED_SIGNALS) + pid = spawnv_passfds(exe, args, fds_to_pass) + finally: + if _HAVE_SIGMASK: + signal.pthread_sigmask(signal.SIG_UNBLOCK, + _IGNORED_SIGNALS) except BaseException: os.close(w) raise @@ -142,19 +167,22 @@ unregister = _semaphore_tracker.unregister getfd = _semaphore_tracker.getfd -def main(fd): +def main(fd, verbose=0): '''Run semaphore tracker.''' # protect the process from ^C and "killall python" etc signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN) + if _HAVE_SIGMASK: + signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) + for f in (sys.stdin, sys.stdout): try: f.close() except Exception: pass - if VERBOSE: # pragma: no cover + if verbose: # pragma: no cover sys.stderr.write("Main semaphore tracker is running\n") sys.stderr.flush() @@ -168,14 +196,14 @@ def main(fd): if cmd == b'REGISTER': name = name.decode('ascii') cache.add(name) - if VERBOSE: # pragma: no cover + if verbose: # pragma: no cover sys.stderr.write("[SemaphoreTracker] register {}\n" .format(name)) sys.stderr.flush() elif cmd == b'UNREGISTER': name = name.decode('ascii') cache.remove(name) - if VERBOSE: # pragma: no cover + if verbose: # pragma: no cover sys.stderr.write("[SemaphoreTracker] unregister {}" ": cache({})\n" .format(name, len(cache))) @@ -205,16 +233,16 @@ def main(fd): try: try: sem_unlink(name) - if VERBOSE: # pragma: no cover + if verbose: # pragma: no cover sys.stderr.write("[SemaphoreTracker] unlink {}\n" .format(name)) sys.stderr.flush() except Exception as e: - warnings.warn('semaphore_tracker: %r: %r' % (name, e)) + warnings.warn('semaphore_tracker: %s: %r' % (name, e)) finally: pass - if VERBOSE: # pragma: no cover + if verbose: # pragma: no cover sys.stderr.write("semaphore tracker shut down\n") sys.stderr.flush() diff --git a/loky/backend/spawn.py b/loky/backend/spawn.py index fb375e5..c0390e4 100644 --- a/loky/backend/spawn.py +++ b/loky/backend/spawn.py @@ -151,7 +151,7 @@ def prepare(data): if 'orig_dir' in data: process.ORIGINAL_DIR = data['orig_dir'] - if 'tacker_pid' in data: + if 'tracker_pid' in data: from . import semaphore_tracker semaphore_tracker._semaphore_tracker._pid = data["tracker_pid"]
tomMoral/loky
1f5f77eb18735831a80c9936be52c831d12bcaa5
diff --git a/tests/test_semaphore_tracker.py b/tests/test_semaphore_tracker.py new file mode 100644 index 0000000..9e04a1d --- /dev/null +++ b/tests/test_semaphore_tracker.py @@ -0,0 +1,199 @@ +"""Tests for the SemaphoreTracker class""" +import errno +import gc +import io +import os +import pytest +import re +import signal +import sys +import time +import warnings +import weakref + +from loky import ProcessPoolExecutor +import loky.backend.semaphore_tracker as semaphore_tracker +from loky.backend.semlock import sem_unlink +from loky.backend.context import get_context + + +def get_sem_tracker_pid(): + semaphore_tracker.ensure_running() + return semaphore_tracker._semaphore_tracker._pid + + [email protected](sys.platform == "win32", + reason="no semaphore_tracker on windows") +class TestSemaphoreTracker: + def test_child_retrieves_semaphore_tracker(self): + parent_sem_tracker_pid = get_sem_tracker_pid() + executor = ProcessPoolExecutor(max_workers=1) + + # Register a semaphore in the parent process, and un-register it in the + # child process. If the two processes do not share the same + # semaphore_tracker, a cache KeyError should be printed in stderr. + import subprocess + semlock_name = 'loky-mysemaphore' + cmd = '''if 1: + import os, sys + + from loky import ProcessPoolExecutor + from loky.backend import semaphore_tracker + from loky.backend.semlock import SemLock + + semaphore_tracker.VERBOSE=True + semlock_name = "{}" + + # We don't need to create the semaphore as registering / unregistering + # operations simply add / remove entries from a cache, but do not + # manipulate the actual semaphores. + semaphore_tracker.register(semlock_name) + + def unregister(name): + # semaphore_tracker.unregister is actually a bound method of the + # SemaphoreTracker. We need a custom wrapper to avoid object + # serialization. + from loky.backend import semaphore_tracker + semaphore_tracker.unregister(semlock_name) + + e = ProcessPoolExecutor(1) + e.submit(unregister, semlock_name).result() + e.shutdown() + ''' + try: + child_sem_tracker_pid = executor.submit( + get_sem_tracker_pid).result() + + # First simple pid retrieval check (see #200) + assert child_sem_tracker_pid == parent_sem_tracker_pid + + p = subprocess.Popen( + [sys.executable, '-E', '-c', cmd.format(semlock_name)], + stderr=subprocess.PIPE) + p.wait() + + err = p.stderr.read().decode('utf-8') + p.stderr.close() + + assert re.search("unregister %s" % semlock_name, err) is not None + assert re.search("KeyError: '%s'" % semlock_name, err) is None + + finally: + executor.shutdown() + + + # The following four tests are inspired from cpython _test_multiprocessing + def test_semaphore_tracker(self): + # + # Check that killing process does not leak named semaphores + # + import subprocess + cmd = '''if 1: + import time, os + from loky.backend.synchronize import Lock + + # close manually the read end of the pipe in the child process + # because pass_fds does not exist for python < 3.2 + os.close(%d) + + lock1 = Lock() + lock2 = Lock() + os.write(%d, lock1._semlock.name.encode("ascii") + b"\\n") + os.write(%d, lock2._semlock.name.encode("ascii") + b"\\n") + time.sleep(10) + ''' + r, w = os.pipe() + + if sys.version_info[:2] >= (3, 2): + fd_kws = {'pass_fds': [w, r]} + else: + fd_kws = {'close_fds': False} + p = subprocess.Popen([sys.executable, + '-E', '-c', cmd % (r, w, w)], + stderr=subprocess.PIPE, + **fd_kws) + os.close(w) + with io.open(r, 'rb', closefd=True) as f: + name1 = f.readline().rstrip().decode('ascii') + name2 = f.readline().rstrip().decode('ascii') + + # subprocess holding a reference to lock1 is still alive, so this call + # should succeed + sem_unlink(name1) + p.terminate() + p.wait() + time.sleep(2.0) + with pytest.raises(OSError) as ctx: + sem_unlink(name2) + # docs say it should be ENOENT, but OSX seems to give EINVAL + assert ctx.value.errno in (errno.ENOENT, errno.EINVAL) + err = p.stderr.read().decode('utf-8') + p.stderr.close() + expected = ('semaphore_tracker: There appear to be 2 leaked ' + 'semaphores') + assert re.search(expected, err) is not None + + # lock1 is still registered, but was destroyed externally: the tracker + # is expected to complain. + expected = ("semaphore_tracker: %s: (OSError\\(%d|" + "FileNotFoundError)" % (name1, errno.ENOENT)) + assert re.search(expected, err) is not None + + def check_semaphore_tracker_death(self, signum, should_die): + # bpo-31310: if the semaphore tracker process has died, it should + # be restarted implicitly. + from loky.backend.semaphore_tracker import _semaphore_tracker + pid = _semaphore_tracker._pid + if pid is not None: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _semaphore_tracker.ensure_running() + # in python < 3.3 , the race condition described in bpo-33613 still + # exists, as this fixe requires signal.pthread_sigmask + time.sleep(1.0) + pid = _semaphore_tracker._pid + + os.kill(pid, signum) + time.sleep(1.0) # give it time to die + + ctx = get_context("loky") + with warnings.catch_warnings(record=True) as all_warn: + warnings.simplefilter("always") + + # remove unrelated MacOS warning messages first + warnings.filterwarnings( + "ignore", message='semaphore are broken on OSX') + + sem = ctx.Semaphore() + sem.acquire() + sem.release() + wr = weakref.ref(sem) + # ensure `sem` gets collected, which triggers communication with + # the semaphore tracker + del sem + gc.collect() + assert wr() is None + if should_die: + assert len(all_warn) == 1 + the_warn = all_warn[0] + assert issubclass(the_warn.category, UserWarning) + assert "semaphore_tracker: process died" in str( + the_warn.message) + else: + assert len(all_warn) == 0 + + def test_semaphore_tracker_sigint(self): + # Catchable signal (ignored by semaphore tracker) + self.check_semaphore_tracker_death(signal.SIGINT, False) + + def test_semaphore_tracker_sigterm(self): + # Catchable signal (ignored by semaphore tracker) + self.check_semaphore_tracker_death(signal.SIGTERM, False) + + @pytest.mark.skipif(sys.version_info[0] < 3, + reason="warnings.catch_warnings limitation") + def test_semaphore_tracker_sigkill(self): + # Uncatchable signal. + self.check_semaphore_tracker_death(signal.SIGKILL, True)
_pid attribute of SemaphoreTracker is not passed to child Since #106, workers created by `loky` inherit their parent's semaphore tracker. However, it seems that the `_pid` attribute gets lost. This test here fails. I'll add a patch soon. ```python from loky import ProcessPoolExecutor import loky.backend.semaphore_tracker def get_semaphore_pid(): sem_tracker = loky.backend.semaphore_tracker._semaphore_tracker sem_tracker.ensure_running() return sem_tracker._pid def test_child_uses_parent_semaphore_tracker(): parent_semtracker_pid = get_semaphore_pid() executor = ProcessPoolExecutor(max_workers=2) child_semtracker_pid = executor.submit(get_semaphore_pid).result() assert parent_semtracker_pid == child_semtracker_pid if __name__ == "__main__": test_child_uses_parent_semaphore_tracker() ```
0.0
1f5f77eb18735831a80c9936be52c831d12bcaa5
[ "tests/test_semaphore_tracker.py::TestSemaphoreTracker::test_semaphore_tracker" ]
[ "tests/test_semaphore_tracker.py::TestSemaphoreTracker::test_semaphore_tracker_sigint", "tests/test_semaphore_tracker.py::TestSemaphoreTracker::test_semaphore_tracker_sigterm", "tests/test_semaphore_tracker.py::TestSemaphoreTracker::test_semaphore_tracker_sigkill" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-12 13:45:15+00:00
bsd-3-clause
6,040
tomerfiliba__plumbum-366
diff --git a/plumbum/cli/image.py b/plumbum/cli/image.py index b207fa3..502af80 100644 --- a/plumbum/cli/image.py +++ b/plumbum/cli/image.py @@ -2,7 +2,7 @@ from __future__ import print_function, division from plumbum import colors from .termsize import get_terminal_size -import . as cli +from .. import cli import sys class Image(object):
tomerfiliba/plumbum
16508155d6361be7a815d264c89e2b893120266b
diff --git a/tests/test_color.py b/tests/test_color.py index 5f4cd3f..2b8105d 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -2,6 +2,8 @@ import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound from plumbum.colorlib.names import color_html, FindNearest +# Just check to see if this file is importable +from plumbum.cli.image import Image class TestNearestColor: def test_exact(self):
SyntaxError in plumbum/cli/image.py image.py contains the line import . as cli All versions of python I tried (3.6, 3.5, 2.7) raise SyntaxError reading this line. According to the Python Language Reference, such syntax of the import statement is not allowed. What exactly is the purpose of this line? And how to achieve this purpose in legal python?
0.0
16508155d6361be7a815d264c89e2b893120266b
[ "tests/test_color.py::TestNearestColor::test_allcolors", "tests/test_color.py::TestColorLoad::test_rgb", "tests/test_color.py::TestColorLoad::test_simple_name", "tests/test_color.py::TestColorLoad::test_different_names", "tests/test_color.py::TestColorLoad::test_loading_methods", "tests/test_color.py::TestANSIColor::test_ansi" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-12-22 22:08:12+00:00
mit
6,041
tomerfiliba__plumbum-372
diff --git a/build.py b/build.py index 1cfd980..cacb752 100755 --- a/build.py +++ b/build.py @@ -25,7 +25,7 @@ class BuildProject(cli.Application): if twine is None: print("Twine not installed, cannot securely upload. Install twine.") else: - twine['upload','dist/*gztar' 'dist/*.exe' '*.whl'] & FG + twine['upload', 'dist/*tar.gz', 'dist/*.exe', 'dist/*.whl'] & FG if __name__ == "__main__": diff --git a/dev-requirements.txt b/dev-requirements.txt index db117b1..ebc89d8 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,5 +1,6 @@ pytest pytest-cov +pytest-mock pycparser<2.18 ; python_version < '2.7' paramiko<2.4 ; python_version < '2.7' paramiko ; python_version >= '2.7' diff --git a/plumbum/cli/application.py b/plumbum/cli/application.py index 75bad0e..5434de1 100644 --- a/plumbum/cli/application.py +++ b/plumbum/cli/application.py @@ -406,15 +406,13 @@ class Application(object): ngettext( "Expected at least {0} positional argument, got {1}", "Expected at least {0} positional arguments, got {1}", - min_args).format( - min_args, tailargs)) + min_args).format(min_args, tailargs)) elif len(tailargs) > max_args: raise PositionalArgumentsError( ngettext( "Expected at most {0} positional argument, got {1}", "Expected at most {0} positional arguments, got {1}", - max_args).format( - max_args, tailargs)) + max_args).format(max_args, tailargs)) # Positional arguement validataion if hasattr(self.main, 'positional'): diff --git a/plumbum/cli/i18n.py b/plumbum/cli/i18n.py index b85db2c..45ef8b9 100644 --- a/plumbum/cli/i18n.py +++ b/plumbum/cli/i18n.py @@ -8,9 +8,9 @@ if loc is None or loc.startswith('en'): return str def ngettext(self, str1, strN, n): if n==1: - return str1.format(n) + return str1.replace("{0}", str(n)) else: - return strN.format(n) + return strN.replace("{0}", str(n)) def get_translation_for(package_name): return NullTranslation() diff --git a/plumbum/machines/ssh_machine.py b/plumbum/machines/ssh_machine.py index e963745..68819a2 100644 --- a/plumbum/machines/ssh_machine.py +++ b/plumbum/machines/ssh_machine.py @@ -276,6 +276,7 @@ class PuttyMachine(SshMachine): user = local.env.user if port is not None: ssh_opts.extend(["-P", str(port)]) + scp_opts = list(scp_opts) + ["-P", str(port)] port = None SshMachine.__init__(self, host, user, port, keyfile = keyfile, ssh_command = ssh_command, scp_command = scp_command, ssh_opts = ssh_opts, scp_opts = scp_opts, encoding = encoding, @@ -292,5 +293,3 @@ class PuttyMachine(SshMachine): def session(self, isatty = False, new_session = False): return ShellSession(self.popen((), (["-t"] if isatty else ["-T"]), new_session = new_session), self.custom_encoding, isatty, self.connect_timeout) - -
tomerfiliba/plumbum
4ea9e4c00a8d36900071393954d2df90931ad689
diff --git a/tests/test_cli.py b/tests/test_cli.py index 95bc7c6..71298de 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -25,7 +25,9 @@ class SimpleApp(cli.Application): self.eggs = old self.tailargs = args - +class PositionalApp(cli.Application): + def main(self, one): + print("Got", one) class Geet(cli.Application): debug = cli.Flag("--debug") @@ -123,6 +125,24 @@ class TestCLI: _, rc = SimpleApp.run(["foo", "--bacon=hello"], exit = False) assert rc == 2 + + # Testing #371 + def test_extra_args(self, capsys): + + _, rc = PositionalApp.run(["positionalapp"], exit = False) + assert rc != 0 + stdout, stderr = capsys.readouterr() + assert "Expected at least" in stdout + + _, rc = PositionalApp.run(["positionalapp", "one"], exit = False) + assert rc == 0 + stdout, stderr = capsys.readouterr() + + _, rc = PositionalApp.run(["positionalapp", "one", "two"], exit = False) + assert rc != 0 + stdout, stderr = capsys.readouterr() + assert "Expected at most" in stdout + def test_subcommands(self): _, rc = Geet.run(["geet", "--debug"], exit = False) assert rc == 0 diff --git a/tests/test_putty.py b/tests/test_putty.py new file mode 100644 index 0000000..763407f --- /dev/null +++ b/tests/test_putty.py @@ -0,0 +1,69 @@ +"""Test that PuttyMachine initializes its SshMachine correctly""" + +import pytest +from plumbum import PuttyMachine, SshMachine + +from plumbum._testtools import xfail_on_pypy + + [email protected](params=['default', '322']) +def ssh_port(request): + return request.param + + +class TestPuttyMachine: + @xfail_on_pypy + def test_putty_command(self, mocker, ssh_port): + local = mocker.patch('plumbum.machines.ssh_machine.local') + init = mocker.spy(SshMachine, '__init__') + mocker.patch('plumbum.machines.ssh_machine.BaseRemoteMachine') + + host = mocker.MagicMock() + user = local.env.user + port = keyfile = None + ssh_command = local["plink"] + scp_command = local["pscp"] + ssh_opts = ["-ssh"] + if ssh_port == 'default': + putty_port = None + scp_opts = () + else: + putty_port = int(ssh_port) + ssh_opts.extend(['-P', ssh_port]) + scp_opts = ['-P', ssh_port] + encoding = mocker.MagicMock() + connect_timeout = 20 + new_session = True + + PuttyMachine( + host, + port=putty_port, + connect_timeout=connect_timeout, + new_session=new_session, + encoding=encoding, + ) + + init.assert_called_with( + mocker.ANY, + host, + user, + port, + keyfile=keyfile, + ssh_command=ssh_command, + scp_command=scp_command, + ssh_opts=ssh_opts, + scp_opts=scp_opts, + encoding=encoding, + connect_timeout=connect_timeout, + new_session=new_session, + ) + + def test_putty_str(self, mocker): + local = mocker.patch('plumbum.machines.ssh_machine.local') + mocker.patch('plumbum.machines.ssh_machine.BaseRemoteMachine') + + host = mocker.MagicMock() + user = local.env.user + + machine = PuttyMachine(host) + assert str(machine) == 'putty-ssh://{0}@{1}'.format(user, host)
"IndexError: tuple index out of range" on missing arguments ![image](https://user-images.githubusercontent.com/19155205/34913485-79a6fe3a-f8c4-11e7-8771-2f6066a9bba6.png) When trying to run a subcommand without the correct amount of arguments I get a python exception. Using conda and python 3.6 plumbum version: - plumbum=1.6.5=py36_0
0.0
4ea9e4c00a8d36900071393954d2df90931ad689
[ "tests/test_cli.py::TestCLI::test_extra_args", "tests/test_putty.py::TestPuttyMachine::test_putty_command[322]" ]
[ "tests/test_cli.py::TestInheritedApp::test_help", "tests/test_cli.py::TestCLI::test_meta_switches", "tests/test_cli.py::TestCLI::test_okay", "tests/test_cli.py::TestCLI::test_failures", "tests/test_cli.py::TestCLI::test_subcommands", "tests/test_cli.py::TestCLI::test_unbind", "tests/test_cli.py::TestCLI::test_default_main", "tests/test_cli.py::TestCLI::test_lazy_subcommand", "tests/test_cli.py::TestCLI::test_reset_switchattr", "tests/test_cli.py::TestCLI::test_invoke", "tests/test_cli.py::TestCLI::test_env_var", "tests/test_cli.py::TestCLI::test_mandatory_env_var", "tests/test_putty.py::TestPuttyMachine::test_putty_command[default]", "tests/test_putty.py::TestPuttyMachine::test_putty_str" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-01-24 09:29:04+00:00
mit
6,042
tomerfiliba__plumbum-605
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0da79ea..03c4749 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,7 @@ jobs: with: fetch-depth: 0 - uses: actions/setup-python@v2 - - uses: pre-commit/[email protected] + - uses: pre-commit/[email protected] - name: pylint run: | echo "::add-matcher::$GITHUB_WORKSPACE/.github/matchers/pylint.json" diff --git a/noxfile.py b/noxfile.py index 9b68bfe..9fae464 100644 --- a/noxfile.py +++ b/noxfile.py @@ -22,7 +22,7 @@ def pylint(session): Run pylint. """ - session.install(".", "paramiko", "ipython", "pylint") + session.install(".", "paramiko", "ipython", "pylint~=2.14.3") session.run("pylint", "plumbum", *session.posargs) diff --git a/plumbum/cli/progress.py b/plumbum/cli/progress.py index 3d21a8a..fce6b3c 100644 --- a/plumbum/cli/progress.py +++ b/plumbum/cli/progress.py @@ -69,7 +69,7 @@ class ProgressBase(ABC): return rval def next(self): - return self.__next__() + return next(self) @property def value(self): diff --git a/plumbum/commands/base.py b/plumbum/commands/base.py index 51e667d..eafbde3 100644 --- a/plumbum/commands/base.py +++ b/plumbum/commands/base.py @@ -547,7 +547,7 @@ class StdinDataRedirection(BaseCommand): return self.cmd.machine def popen(self, args=(), **kwargs): - if "stdin" in kwargs and kwargs["stdin"] != PIPE: + if kwargs.get("stdin") not in (PIPE, None): raise RedirectionError("stdin is already redirected") data = self.data if isinstance(data, str) and self._get_encoding() is not None: @@ -558,8 +558,9 @@ class StdinDataRedirection(BaseCommand): f.write(chunk) data = data[self.CHUNK_SIZE :] f.seek(0) + kwargs["stdin"] = f # try: - return self.cmd.popen(args, stdin=f, **kwargs) + return self.cmd.popen(args, **kwargs) # finally: # f.close() diff --git a/plumbum/fs/atomic.py b/plumbum/fs/atomic.py index 5aebc80..d796b2f 100644 --- a/plumbum/fs/atomic.py +++ b/plumbum/fs/atomic.py @@ -290,7 +290,7 @@ class PidFile: return self._ctx = self.atomicfile.locked(blocking=False) try: - self._ctx.__enter__() + self._ctx.__enter__() # pylint: disable=unnecessary-dunder-call except OSError: self._ctx = None try: diff --git a/pyproject.toml b/pyproject.toml index b34fa89..27ddb99 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,6 +68,7 @@ ignore = [ [tool.pylint] master.py-version = "3.6" master.jobs = "0" +master.load-plugins = ["pylint.extensions.no_self_use"] reports.output-format = "colorized" similarities.ignore-imports = "yes" messages_control.enable = [ @@ -103,4 +104,5 @@ messages_control.disable = [ "too-many-return-statements", "too-many-statements", "unidiomatic-typecheck", # TODO: might be able to remove + "unnecessary-lambda-assignment", # TODO: 4 instances ]
tomerfiliba/plumbum
5fa1452846aae4a1fd2904bf145b0801c2050508
diff --git a/tests/test_local.py b/tests/test_local.py index dc76a7b..d96d39b 100644 --- a/tests/test_local.py +++ b/tests/test_local.py @@ -639,6 +639,25 @@ class TestLocalMachine: assert result[1] == EXPECT assert EXPECT == capfd.readouterr()[0] + @skip_on_windows + @pytest.mark.parametrize( + "modifier, expected", + [ + (FG, None), + (TF(FG=True), True), + (RETCODE(FG=True), 0), + (TEE, (0, "meow", "")), + ], + ) + def test_redirection_stdin_modifiers_fg(self, modifier, expected, capfd): + "StdinDataRedirection compatible with modifiers which write to stdout" + from plumbum.cmd import cat + + cmd = cat << "meow" + + assert cmd & modifier == expected + assert capfd.readouterr() == ("meow", "") + @skip_on_windows def test_logger_pipe(self): from plumbum.cmd import bash
StdinDataRedirection commands fail upon modification (TEE, FG, etc.) Commands to which standard input has been supplied from a Python string – which are `StdinDataRedirection` commands – erroneously throw exception `RedirectionError` when combined with built-in modifiers – stdin is already redirected – even though `stdin` is only being redirected the one time. --- ```python >>> from plumbum import TEE, FG, local # this works >>> local['ls']['-d', '/'] & FG / >>> local['ls']['-d', '/'] & TEE / (0, '/\n', '') # this does not work >>> (local['cat']['-'] << 'this breaks') & FG Traceback (most recent call last): … raise RedirectionError("stdin is already redirected") plumbum.commands.base.RedirectionError: stdin is already redirected ``` --- Affected modifiers invoke `cmd.run(stdin=None, …)`. It appears sufficient to change these to simply **omit the keyword** pair `stdin=None`. However, it's unclear whether this would have unwanted side-effects; and, it seems rather that `StdinDataRedirection` is in the wrong, in throwing an exception over the value `None`. `BaseRedirection.popen` permits either `PIPE` or `None`: ```python if self.KWARG in kwargs and kwargs[self.KWARG] not in (PIPE, None): raise RedirectionError(…) ``` `StdinDataRedirection.popen` only permits `PIPE`: ```python if "stdin" in kwargs and kwargs["stdin"] != PIPE: raise RedirectionError(…) ``` → As such, the resolution is perhaps that the above check in `StdinDataRedirection.popen` be made to mirror `BaseRedirection.popen`.
0.0
5fa1452846aae4a1fd2904bf145b0801c2050508
[ "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier0-None]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier1-True]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier2-0]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier3-expected3]" ]
[ "tests/test_local.py::TestLocalPopen::test_contextmanager", "tests/test_local.py::TestLocalPath::test_name", "tests/test_local.py::TestLocalPath::test_dirname", "tests/test_local.py::TestLocalPath::test_uri", "tests/test_local.py::TestLocalPath::test_pickle", "tests/test_local.py::TestLocalPath::test_empty", "tests/test_local.py::TestLocalPath::test_chown", "tests/test_local.py::TestLocalPath::test_split", "tests/test_local.py::TestLocalPath::test_suffix", "tests/test_local.py::TestLocalPath::test_newname", "tests/test_local.py::TestLocalPath::test_relative_to", "tests/test_local.py::TestLocalPath::test_read_write", "tests/test_local.py::TestLocalPath::test_parts", "tests/test_local.py::TestLocalPath::test_iterdir", "tests/test_local.py::TestLocalPath::test_stem", "tests/test_local.py::TestLocalPath::test_root_drive", "tests/test_local.py::TestLocalPath::test_compare_pathlib", "tests/test_local.py::TestLocalPath::test_suffix_expected", "tests/test_local.py::TestLocalPath::test_touch", "tests/test_local.py::TestLocalPath::test_copy_override", "tests/test_local.py::TestLocalPath::test_copy_nonexistant_dir", "tests/test_local.py::TestLocalPath::test_unlink", "tests/test_local.py::TestLocalPath::test_unhashable", "tests/test_local.py::TestLocalPath::test_getpath", "tests/test_local.py::TestLocalPath::test_path_dir", "tests/test_local.py::TestLocalPath::test_mkdir", "tests/test_local.py::TestLocalPath::test_mkdir_mode", "tests/test_local.py::TestLocalPath::test_str_getitem", "tests/test_local.py::TestLocalPath::test_fspath", "tests/test_local.py::TestLocalMachine::test_getattr", "tests/test_local.py::TestLocalMachine::test_imports", "tests/test_local.py::TestLocalMachine::test_get", "tests/test_local.py::TestLocalMachine::test_shadowed_by_dir", "tests/test_local.py::TestLocalMachine::test_repr_command", "tests/test_local.py::TestLocalMachine::test_cwd", "tests/test_local.py::TestLocalMachine::test_mixing_chdir", "tests/test_local.py::TestLocalMachine::test_contains", "tests/test_local.py::TestLocalMachine::test_path", "tests/test_local.py::TestLocalMachine::test_glob_spaces", "tests/test_local.py::TestLocalMachine::test_env", "tests/test_local.py::TestLocalMachine::test_local", "tests/test_local.py::TestLocalMachine::test_piping", "tests/test_local.py::TestLocalMachine::test_redirection", "tests/test_local.py::TestLocalMachine::test_popen", "tests/test_local.py::TestLocalMachine::test_run", "tests/test_local.py::TestLocalMachine::test_timeout", "tests/test_local.py::TestLocalMachine::test_pipe_stderr", "tests/test_local.py::TestLocalMachine::test_fair_error_attribution", "tests/test_local.py::TestLocalMachine::test_iter_lines_timeout", "tests/test_local.py::TestLocalMachine::test_iter_lines_buffer_size", "tests/test_local.py::TestLocalMachine::test_iter_lines_timeout_by_type", "tests/test_local.py::TestLocalMachine::test_iter_lines_error", "tests/test_local.py::TestLocalMachine::test_iter_lines_line_timeout", "tests/test_local.py::TestLocalMachine::test_modifiers", "tests/test_local.py::TestLocalMachine::test_tee_modifier", "tests/test_local.py::TestLocalMachine::test_tee_race", "tests/test_local.py::TestLocalMachine::test_logger_pipe", "tests/test_local.py::TestLocalMachine::test_logger_pipe_line_timeout", "tests/test_local.py::TestLocalMachine::test_arg_expansion", "tests/test_local.py::TestLocalMachine::test_session", "tests/test_local.py::TestLocalMachine::test_quoting", "tests/test_local.py::TestLocalMachine::test_exception_pickling", "tests/test_local.py::TestLocalMachine::test_tempdir", "tests/test_local.py::TestLocalMachine::test_direct_open_tmpdir", "tests/test_local.py::TestLocalMachine::test_read_write_str", "tests/test_local.py::TestLocalMachine::test_read_write_unicode", "tests/test_local.py::TestLocalMachine::test_read_write_bin", "tests/test_local.py::TestLocalMachine::test_links", "tests/test_local.py::TestLocalMachine::test_list_processes", "tests/test_local.py::TestLocalMachine::test_pgrep", "tests/test_local.py::TestLocalMachine::test_local_daemon", "tests/test_local.py::TestLocalMachine::test_atomic_file", "tests/test_local.py::TestLocalMachine::test_atomic_file2", "tests/test_local.py::TestLocalMachine::test_pid_file", "tests/test_local.py::TestLocalMachine::test_atomic_counter", "tests/test_local.py::TestLocalMachine::test_atomic_counter2", "tests/test_local.py::TestLocalMachine::test_bound_env", "tests/test_local.py::TestLocalMachine::test_nesting_lists_as_argv", "tests/test_local.py::TestLocalMachine::test_contains_ls", "tests/test_local.py::TestLocalMachine::test_issue_139", "tests/test_local.py::TestLocalMachine::test_pipeline_failure", "tests/test_local.py::TestLocalMachine::test_cmd", "tests/test_local.py::TestLocalMachine::test_pipeline_retcode", "tests/test_local.py::TestLocalMachine::test_pipeline_stdin", "tests/test_local.py::TestLocalMachine::test_run_bg", "tests/test_local.py::TestLocalMachine::test_run_fg", "tests/test_local.py::TestLocalMachine::test_run_tee", "tests/test_local.py::TestLocalMachine::test_run_tf", "tests/test_local.py::TestLocalMachine::test_run_retcode", "tests/test_local.py::TestLocalMachine::test_run_nohup", "tests/test_local.py::TestLocalEncoding::test_inout_rich", "tests/test_local.py::TestLocalEncoding::test_out_rich", "tests/test_local.py::TestLocalEncoding::test_runfile_rich", "tests/test_local.py::test_local_glob_path" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-22 20:56:50+00:00
mit
6,043
tomerfiliba__plumbum-621
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f65c073..e53a554 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,7 +33,7 @@ jobs: - name: pylint run: | echo "::add-matcher::$GITHUB_WORKSPACE/.github/matchers/pylint.json" - pipx run nox -s pylint + pipx run --python python nox -s pylint tests: name: Tests on 🐍 ${{ matrix.python-version }} ${{ matrix.os }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3f5f487..3770b2e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -81,7 +81,6 @@ repos: - id: python-check-blanket-noqa - id: python-check-blanket-type-ignore - id: python-no-log-warn - - id: python-no-eval - id: python-use-type-annotations - id: rst-backticks - id: rst-directive-colons diff --git a/plumbum/cli/application.py b/plumbum/cli/application.py index 788ccb5..d83e6f1 100644 --- a/plumbum/cli/application.py +++ b/plumbum/cli/application.py @@ -501,6 +501,12 @@ class Application: ) m = inspect.getfullargspec(self.main) + + if sys.version_info < (3, 10): + sig = inspect.signature(self.main) + else: + sig = inspect.signature(self.main, eval_str=True) + max_args = sys.maxsize if m.varargs else len(m.args) - 1 min_args = len(m.args) - 1 - (len(m.defaults) if m.defaults else 0) if len(tailargs) < min_args: @@ -530,17 +536,24 @@ class Application: m.varargs, ) - elif hasattr(m, "annotations"): + elif hasattr(m, "annotations") and m.annotations: args_names = list(m.args[1:]) positional = [None] * len(args_names) varargs = None # All args are positional, so convert kargs to positional for item in m.annotations: + annotation = ( + sig.parameters[item].annotation + if item != "return" + else sig.return_annotation + ) + if sys.version_info < (3, 10) and isinstance(annotation, str): + annotation = eval(annotation) if item == m.varargs: - varargs = m.annotations[item] + varargs = annotation elif item != "return": - positional[args_names.index(item)] = m.annotations[item] + positional[args_names.index(item)] = annotation tailargs = self._positional_validate( tailargs, positional, varargs, m.args[1:], m.varargs diff --git a/pyproject.toml b/pyproject.toml index bf9042f..8a7ee77 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -106,4 +106,5 @@ messages_control.disable = [ "unidiomatic-typecheck", # TODO: might be able to remove "unnecessary-lambda-assignment", # TODO: 4 instances "unused-import", # identical to flake8 but has typing false positives + "eval-used", # Needed for Python <3.10 annotations ]
tomerfiliba/plumbum
da87b67d3efcaa61554756d56775ac44a3379c00
diff --git a/tests/test_3_cli.py b/tests/test_3_cli.py index 9b8af84..279a56b 100644 --- a/tests/test_3_cli.py +++ b/tests/test_3_cli.py @@ -14,7 +14,7 @@ class TestProg3: class Main4Validator(cli.Application): - def main(self, myint: int, myint2: int, *mylist: int) -> None: + def main(self, myint: int, myint2: int, *mylist: "int") -> None: print(myint, myint2, mylist)
Future support for from __future__ import annotations I added `YAMLWizard` to some code using plumbum's `cli`, and after added the required `__future__` line I discovered that my `main` function wouldn't typecheck its command line arguments anymore. Picture something like this: ``` from __future__ import annotations from plumbum import cli # import YAMLWizard # skipped for simplicity class app(cli.Application): def main(self, *dirs: cli.ExistingDirectory): pass ``` I hope it's clear what's expected here. Anyhow, what will actually happen due to the `annotations` feature is that the annotations get processed differently, and apparently don't work the same way. So instead of typechecking the command line as expected, the program always terminates with a runtime error that "str object is not callable." Workarounds: 1. Just separate cli.Application and __future__.annotation use into separate modules. It's what I'm doing now. 2. Don't typecheck the command line. I did that for a bit, but it's annoying.
0.0
da87b67d3efcaa61554756d56775ac44a3379c00
[ "tests/test_3_cli.py::TestProg4::test_prog" ]
[ "tests/test_3_cli.py::TestProg3::test_prog" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-05 21:19:23+00:00
mit
6,044
tomerfiliba__plumbum-661
diff --git a/docs/index.rst b/docs/index.rst index 78bf283..c1b2ed0 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -166,7 +166,7 @@ that I wrote for `RPyC <https://rpyc.readthedocs.io/>`_. When I combined the two Credits ======= -The project has been inspired by **PBS** (now called `sh <http://amoffat.github.io/sh/>`_) +The project has been inspired by **PBS** (now called `sh <http://sh.rtfd.org>`_) of `Andrew Moffat <https://github.com/amoffat>`_, and has borrowed some of his ideas (namely treating programs like functions and the nice trick for importing commands). However, I felt there was too much magic going on in PBS, diff --git a/plumbum/commands/base.py b/plumbum/commands/base.py index 52c0f26..3172c52 100644 --- a/plumbum/commands/base.py +++ b/plumbum/commands/base.py @@ -398,8 +398,6 @@ class Pipeline(BaseCommand): dstproc = self.dstcmd.popen(**kwargs) # allow p1 to receive a SIGPIPE if p2 exits srcproc.stdout.close() - if srcproc.stderr is not None: - dstproc.stderr = srcproc.stderr if srcproc.stdin and src_kwargs.get("stdin") != PIPE: srcproc.stdin.close() dstproc.srcproc = srcproc diff --git a/plumbum/commands/modifiers.py b/plumbum/commands/modifiers.py index 98b3749..af59071 100644 --- a/plumbum/commands/modifiers.py +++ b/plumbum/commands/modifiers.py @@ -226,6 +226,7 @@ class _TEE(ExecutionModifier): buf.append(data) + p.wait() # To get return code in p stdout = "".join([x.decode("utf-8") for x in outbuf]) stderr = "".join([x.decode("utf-8") for x in errbuf]) return p.returncode, stdout, stderr diff --git a/plumbum/commands/processes.py b/plumbum/commands/processes.py index 802ede4..89c2763 100644 --- a/plumbum/commands/processes.py +++ b/plumbum/commands/processes.py @@ -18,14 +18,44 @@ def _check_process(proc, retcode, timeout, stdout, stderr): return proc.returncode, stdout, stderr +def _get_piped_streams(proc): + """Get a list of all valid standard streams for proc that were opened with PIPE option. + + If proc was started from a Pipeline command, this function assumes it will have a + "srcproc" member pointing to the previous command in the pipeline. That link will + be used to traverse all started processes started from the pipeline, the list will + include stdout/stderr streams opened as PIPE for all commands in the pipeline. + If that was not the case, some processes could write to pipes no one reads from + which would result in process stalling after the pipe's buffer is filled. + + Streams that were closed (because they were redirected to the input of a subsequent command) + are not included in the result + """ + streams = [] + + def add_stream(type_, stream): + if stream is None or stream.closed: + return + streams.append((type_, stream)) + + while proc: + add_stream(1, proc.stderr) + add_stream(0, proc.stdout) + proc = getattr(proc, "srcproc", None) + + return streams + + def _iter_lines_posix(proc, decode, linesize, line_timeout=None): from selectors import EVENT_READ, DefaultSelector + streams = _get_piped_streams(proc) + # Python 3.4+ implementation def selector(): sel = DefaultSelector() - sel.register(proc.stdout, EVENT_READ, 0) - sel.register(proc.stderr, EVENT_READ, 1) + for stream_type, stream in streams: + sel.register(stream, EVENT_READ, stream_type) while True: ready = sel.select(line_timeout) if not ready and line_timeout: @@ -41,10 +71,9 @@ def _iter_lines_posix(proc, decode, linesize, line_timeout=None): yield ret if proc.poll() is not None: break - for line in proc.stdout: - yield 0, decode(line) - for line in proc.stderr: - yield 1, decode(line) + for stream_type, stream in streams: + for line in stream: + yield stream_type, decode(line) def _iter_lines_win32(proc, decode, linesize, line_timeout=None):
tomerfiliba/plumbum
668d98aea069f7b4ca20607694038166a93a1cf2
diff --git a/tests/test_local.py b/tests/test_local.py index 889624a..3b5eb51 100644 --- a/tests/test_local.py +++ b/tests/test_local.py @@ -607,7 +607,7 @@ class TestLocalMachine: @skip_on_windows def test_modifiers(self): - from plumbum.cmd import grep, ls + from plumbum.cmd import cat, grep, ls f = (ls["-a"] | grep["\\.py"]) & BG f.wait() @@ -615,11 +615,17 @@ class TestLocalMachine: command = ls["-a"] | grep["local"] command_false = ls["-a"] | grep["not_a_file_here"] + command_false_2 = command_false | cat command & FG assert command & TF assert not (command_false & TF) + assert not (command_false_2 & TF) assert command & RETCODE == 0 assert command_false & RETCODE == 1 + assert command_false_2 & RETCODE == 1 + assert (command & TEE)[0] == 0 + assert (command_false & TEE(retcode=None))[0] == 1 + assert (command_false_2 & TEE(retcode=None))[0] == 1 @skip_on_windows def test_tee_modifier(self, capfd): diff --git a/tests/test_pipelines.py b/tests/test_pipelines.py new file mode 100644 index 0000000..8ea47e2 --- /dev/null +++ b/tests/test_pipelines.py @@ -0,0 +1,87 @@ +from typing import List, Tuple + +import pytest + +import plumbum +from plumbum._testtools import skip_on_windows +from plumbum.commands import BaseCommand + + +@skip_on_windows [email protected](3) +def test_draining_stderr(generate_cmd, process_cmd): + stdout, stderr = get_output_with_iter_lines( + generate_cmd | process_cmd | process_cmd + ) + expected_output = {f"generated {i}" for i in range(5000)} + expected_output.update(f"consumed {i}" for i in range(5000)) + assert set(stderr) - expected_output == set() + assert len(stderr) == 15000 + assert len(stdout) == 5000 + + +@skip_on_windows [email protected](3) +def test_draining_stderr_with_stderr_redirect(tmp_path, generate_cmd, process_cmd): + stdout, stderr = get_output_with_iter_lines( + generate_cmd | (process_cmd >= str(tmp_path / "output.txt")) | process_cmd + ) + expected_output = {f"generated {i}" for i in range(5000)} + expected_output.update(f"consumed {i}" for i in range(5000)) + assert set(stderr) - expected_output == set() + assert len(stderr) == 10000 + assert len(stdout) == 5000 + + +@skip_on_windows [email protected](3) +def test_draining_stderr_with_stdout_redirect(tmp_path, generate_cmd, process_cmd): + stdout, stderr = get_output_with_iter_lines( + generate_cmd | process_cmd | process_cmd > str(tmp_path / "output.txt") + ) + expected_output = {f"generated {i}" for i in range(5000)} + expected_output.update(f"consumed {i}" for i in range(5000)) + assert set(stderr) - expected_output == set() + assert len(stderr) == 15000 + assert len(stdout) == 0 + + [email protected]() +def generate_cmd(tmp_path): + generate = tmp_path / "generate.py" + generate.write_text( + """\ +import sys +for i in range(5000): + print("generated", i, file=sys.stderr) + print(i) +""" + ) + return plumbum.local["python"][generate] + + [email protected]() +def process_cmd(tmp_path): + process = tmp_path / "process.py" + process.write_text( + """\ +import sys +for line in sys.stdin: + i = line.strip() + print("consumed", i, file=sys.stderr) + print(i) +""" + ) + return plumbum.local["python"][process] + + +def get_output_with_iter_lines(cmd: BaseCommand) -> Tuple[List[str], List[str]]: + stderr, stdout = [], [] + proc = cmd.popen() + for stdout_line, stderr_line in proc.iter_lines(retcode=[0, None]): + if stderr_line: + stderr.append(stderr_line) + if stdout_line: + stdout.append(stdout_line) + proc.wait() + return stdout, stderr
TEE return code for pipeline is wrong when non-last command fails Based on #145 ```py from plumbum.cmd import yes, head from plumbum import TEE, RETCODE chain = yes['-x'] | head print(chain & RETCODE) # prints 1 with chain.bgrun(retcode=None) as p: print(p.run()[0]) # prints 1 print((chain & TEE(retcode=None))[0]) # prints 0 ```
0.0
668d98aea069f7b4ca20607694038166a93a1cf2
[ "tests/test_local.py::TestLocalMachine::test_modifiers", "tests/test_pipelines.py::test_draining_stderr", "tests/test_pipelines.py::test_draining_stderr_with_stderr_redirect", "tests/test_pipelines.py::test_draining_stderr_with_stdout_redirect" ]
[ "tests/test_local.py::TestLocalPopen::test_contextmanager", "tests/test_local.py::TestLocalPath::test_name", "tests/test_local.py::TestLocalPath::test_dirname", "tests/test_local.py::TestLocalPath::test_uri", "tests/test_local.py::TestLocalPath::test_pickle", "tests/test_local.py::TestLocalPath::test_empty", "tests/test_local.py::TestLocalPath::test_chown", "tests/test_local.py::TestLocalPath::test_split", "tests/test_local.py::TestLocalPath::test_suffix", "tests/test_local.py::TestLocalPath::test_newname", "tests/test_local.py::TestLocalPath::test_relative_to", "tests/test_local.py::TestLocalPath::test_read_write", "tests/test_local.py::TestLocalPath::test_parts", "tests/test_local.py::TestLocalPath::test_iterdir", "tests/test_local.py::TestLocalPath::test_stem", "tests/test_local.py::TestLocalPath::test_root_drive", "tests/test_local.py::TestLocalPath::test_compare_pathlib", "tests/test_local.py::TestLocalPath::test_suffix_expected", "tests/test_local.py::TestLocalPath::test_touch", "tests/test_local.py::TestLocalPath::test_copy_override", "tests/test_local.py::TestLocalPath::test_copy_nonexistant_dir", "tests/test_local.py::TestLocalPath::test_unlink", "tests/test_local.py::TestLocalPath::test_unhashable", "tests/test_local.py::TestLocalPath::test_getpath", "tests/test_local.py::TestLocalPath::test_path_dir", "tests/test_local.py::TestLocalPath::test_mkdir", "tests/test_local.py::TestLocalPath::test_mkdir_mode", "tests/test_local.py::TestLocalPath::test_str_getitem", "tests/test_local.py::TestLocalPath::test_fspath", "tests/test_local.py::TestLocalMachine::test_getattr", "tests/test_local.py::TestLocalMachine::test_imports", "tests/test_local.py::TestLocalMachine::test_pathlib", "tests/test_local.py::TestLocalMachine::test_get", "tests/test_local.py::TestLocalMachine::test_shadowed_by_dir", "tests/test_local.py::TestLocalMachine::test_repr_command", "tests/test_local.py::TestLocalMachine::test_cwd", "tests/test_local.py::TestLocalMachine::test_mixing_chdir", "tests/test_local.py::TestLocalMachine::test_contains", "tests/test_local.py::TestLocalMachine::test_path", "tests/test_local.py::TestLocalMachine::test_glob_spaces", "tests/test_local.py::TestLocalMachine::test_env", "tests/test_local.py::TestLocalMachine::test_local", "tests/test_local.py::TestLocalMachine::test_piping", "tests/test_local.py::TestLocalMachine::test_redirection", "tests/test_local.py::TestLocalMachine::test_popen", "tests/test_local.py::TestLocalMachine::test_run", "tests/test_local.py::TestLocalMachine::test_timeout", "tests/test_local.py::TestLocalMachine::test_pipe_stderr", "tests/test_local.py::TestLocalMachine::test_fair_error_attribution", "tests/test_local.py::TestLocalMachine::test_iter_lines_timeout", "tests/test_local.py::TestLocalMachine::test_iter_lines_buffer_size", "tests/test_local.py::TestLocalMachine::test_iter_lines_timeout_by_type", "tests/test_local.py::TestLocalMachine::test_iter_lines_error", "tests/test_local.py::TestLocalMachine::test_iter_lines_line_timeout", "tests/test_local.py::TestLocalMachine::test_tee_modifier", "tests/test_local.py::TestLocalMachine::test_tee_race", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier0-None]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier1-True]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier2-0]", "tests/test_local.py::TestLocalMachine::test_redirection_stdin_modifiers_fg[modifier3-expected3]", "tests/test_local.py::TestLocalMachine::test_logger_pipe", "tests/test_local.py::TestLocalMachine::test_logger_pipe_line_timeout", "tests/test_local.py::TestLocalMachine::test_arg_expansion", "tests/test_local.py::TestLocalMachine::test_session", "tests/test_local.py::TestLocalMachine::test_quoting", "tests/test_local.py::TestLocalMachine::test_exception_pickling", "tests/test_local.py::TestLocalMachine::test_tempdir", "tests/test_local.py::TestLocalMachine::test_direct_open_tmpdir", "tests/test_local.py::TestLocalMachine::test_read_write_str", "tests/test_local.py::TestLocalMachine::test_read_write_unicode", "tests/test_local.py::TestLocalMachine::test_read_write_bin", "tests/test_local.py::TestLocalMachine::test_links", "tests/test_local.py::TestLocalMachine::test_list_processes", "tests/test_local.py::TestLocalMachine::test_pgrep", "tests/test_local.py::TestLocalMachine::test_local_daemon", "tests/test_local.py::TestLocalMachine::test_atomic_file", "tests/test_local.py::TestLocalMachine::test_atomic_file2", "tests/test_local.py::TestLocalMachine::test_pid_file", "tests/test_local.py::TestLocalMachine::test_atomic_counter", "tests/test_local.py::TestLocalMachine::test_atomic_counter2", "tests/test_local.py::TestLocalMachine::test_bound_env", "tests/test_local.py::TestLocalMachine::test_nesting_lists_as_argv", "tests/test_local.py::TestLocalMachine::test_contains_ls", "tests/test_local.py::TestLocalMachine::test_issue_139", "tests/test_local.py::TestLocalMachine::test_pipeline_failure", "tests/test_local.py::TestLocalMachine::test_cmd", "tests/test_local.py::TestLocalMachine::test_pipeline_retcode", "tests/test_local.py::TestLocalMachine::test_pipeline_stdin", "tests/test_local.py::TestLocalMachine::test_run_bg", "tests/test_local.py::TestLocalMachine::test_run_fg", "tests/test_local.py::TestLocalMachine::test_run_tee", "tests/test_local.py::TestLocalMachine::test_run_tf", "tests/test_local.py::TestLocalMachine::test_run_retcode", "tests/test_local.py::TestLocalMachine::test_run_nohup", "tests/test_local.py::TestLocalEncoding::test_inout_rich", "tests/test_local.py::TestLocalEncoding::test_out_rich", "tests/test_local.py::TestLocalEncoding::test_runfile_rich", "tests/test_local.py::test_local_glob_path" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-31 20:34:24+00:00
mit
6,045
tommyjcarpenter__osmtogeojson-8
diff --git a/Changelog.md b/Changelog.md index 60d3034..0be1e85 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,7 +2,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/). +and this project will later on adhere to [Semantic Versioning](http://semver.org/). + +Note: A change of a minor/patch version still may result in changed GeoJSON export results! ## [0.0.1] * Project creation +## [0.0.2] + * Prefix osm "id" property by an "at"-sign (fixes #5) + * Create GeometryCollection for relations with mixed member types (fixes #3) diff --git a/osmtogeojson/osmtogeojson.py b/osmtogeojson/osmtogeojson.py index 36eb032..6a05cd3 100644 --- a/osmtogeojson/osmtogeojson.py +++ b/osmtogeojson/osmtogeojson.py @@ -1,5 +1,8 @@ +import logging from osmtogeojson import merge +logger = logging.getLogger(__name__) + def _determine_feature_type(way_nodes): # get more advanced??? if way_nodes[0] == way_nodes[-1]: @@ -65,6 +68,7 @@ def _process_relations(resulting_geojson, relation_storage, way_storage, node_st way_types = [] way_coordinate_blocks = [] + only_way_members = True for mem in r["members"]: if mem["type"] == "way": way_id = mem["ref"] @@ -73,7 +77,7 @@ def _process_relations(resulting_geojson, relation_storage, way_storage, node_st way_coordinate_blocks.append(processed["geometry"]["coordinates"]) ways_used_in_relations[way_id] = 1 else: - print(mem["type"]) + only_way_members = False rel["geometry"] = {} @@ -86,8 +90,31 @@ def _process_relations(resulting_geojson, relation_storage, way_storage, node_st rel["geometry"]["coordinates"] = [x for x in way_coordinate_blocks] merge.merge_line_string(rel) else: - print(way_types) - + # relation does not consist of Polygons or LineStrings only... + # In this case, overpass reports every individual member with its relation reference + # Another option would be to export such a relation as GeometryCollection + + rel["geometry"]["type"] = "GeometryCollection" + member_geometries = [] + for mem in r["members"]: + if mem["type"] == "way": + way_id = mem["ref"] + processed = _process_single_way(way_id, way_storage[way_id], node_storage, nodes_used_in_ways) + member_geometries.append(processed["geometry"]) + elif mem["type"] == "node": + node_id = mem["ref"] + node = node_storage[node_id] + geometry = {} + geometry["type"] = "Point" + geometry["coordinates"] = [node["lon"], node["lat"]] + member_geometries.append(geometry) + # Well, used_in_rels, but we want to ignore it as well, don't we? + nodes_used_in_ways[node_id] = 1 + else: + logger.warn("Relations members not yet handled (%s)", rel_id) + + rel["geometry"]["geometries"] = member_geometries + resulting_geojson["features"].append(rel) return ways_used_in_relations diff --git a/setup.py b/setup.py index 78fbb6b..ef27f82 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='osmtogeojson', - version='0.0.1', + version='0.0.2', packages=find_packages(exclude=["tests.*", "tests"]), author="Tommy Carpenter", author_email="",
tommyjcarpenter/osmtogeojson
128ec15acd298926dc9070b91ce45546a581b90f
diff --git a/tests/fixtures/geomcollection_geojson.json b/tests/fixtures/geomcollection_geojson.json new file mode 100644 index 0000000..a7e435f --- /dev/null +++ b/tests/fixtures/geomcollection_geojson.json @@ -0,0 +1,82 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "id": "relation/5576903", + "properties": { + "@id": "relation/5576903", + "amenity": "parking", + "fee": "yes", + "name": "Schillerplatz", + "opening_hours": "24/7", + "operator": "APCOA PARKING Deutschland GmbH", + "parking": "underground", + "site": "parking", + "type": "site", + "url": "https://service.stuttgart.de/lhs-services/ivlz/index.php?uid=35&objectid=108523&objecttype=dept&page=svc&servicetype=parking&serviceid=9356&detailid=65&showservice=1", + "website": "https://www.apcoa.de/parken-in/stuttgart/schillerplatz.html" + }, + "geometry": { + "geometries": [ + { + "coordinates": [ + [ + 9.1785771, + 48.7769778 + ], + [ + 9.1785466, + 48.7769462 + ] + ], + "type": "LineString" + }, + { + "coordinates": [ + [ + [ + 9.178599, + 48.7769776 + ], + [ + 9.1785505, + 48.7769354 + ], + [ + 9.1785521, + 48.7769096 + ], + [ + 9.1785628, + 48.776876 + ], + [ + 9.1786147, + 48.7768176 + ], + [ + 9.1786676, + 48.7767825 + ], + [ + 9.178599, + 48.7769776 + ] + ] + ], + "type": "Polygon" + }, + { + "coordinates": [ + 9.1786676, + 48.7767825 + ], + "type": "Point" + } + ], + "type": "GeometryCollection" + } + } + ] +} \ No newline at end of file diff --git a/tests/fixtures/geomcollection_overpass.json b/tests/fixtures/geomcollection_overpass.json new file mode 100644 index 0000000..c6e803f --- /dev/null +++ b/tests/fixtures/geomcollection_overpass.json @@ -0,0 +1,144 @@ +{ + "version": 0.6, + "generator": "Overpass API 0.7.55.6 486819c8", + "osm3s": { + "timestamp_osm_base": "2019-04-25T18:26:02Z", + "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL." + }, + "notes": "This is a shortened test fixture, the real feature has some more members...", + "elements": [ +{ + "type": "node", + "id": 20850150, + "lat": 48.7767825, + "lon": 9.1786676, + "tags": { + "amenity": "parking_entrance", + "foot": "yes", + "maxheight": "2", + "parking": "underground" + } +}, +{ + "type": "node", + "id": 3801571628, + "lat": 48.7768176, + "lon": 9.1786147 +}, +{ + "type": "node", + "id": 3801571632, + "lat": 48.7768760, + "lon": 9.1785628 +}, +{ + "type": "node", + "id": 3817566170, + "lat": 48.7769096, + "lon": 9.1785521, + "tags": { + "barrier": "lift_gate", + "layer": "-1", + "location": "underground" + } +}, +{ + "type": "node", + "id": 3801571640, + "lat": 48.7769354, + "lon": 9.1785505 +}, +{ + "type": "node", + "id": 3801569051, + "lat": 48.7769776, + "lon": 9.1785990 +}, +{ + "type": "node", + "id": 3801571641, + "lat": 48.7769462, + "lon": 9.1785466 +}, +{ + "type": "node", + "id": 3801571647, + "lat": 48.7769778, + "lon": 9.1785771 +}, +{ + "type": "way", + "id": 376770460, + "nodes": [ + 3801571647, + 3801571641 + ], + "tags": { + "covered": "yes", + "highway": "footway", + "indoor": "yes", + "layer": "-2", + "location": "underground", + "ref": "Ebene B" + } +}, +{ + "type": "way", + "id": 376770534, + "nodes": [ + 3801569051, + 3801571640, + 3817566170, + 3801571632, + 3801571628, + 20850150, + 3801569051 + ], + "tags": { + "highway": "service", + "incline": "up", + "layer": "-1", + "location": "underground", + "oneway": "yes", + "service": "driveway", + "sidewalk": "right", + "tunnel": "yes" + } +}, +{ + "type": "relation", + "id": 5576903, + "members": [ + { + "type": "way", + "ref": 376770460, + "role": "" + }, + { + "type": "way", + "ref": 376770534, + "role": "" + }, + { + "type": "node", + "ref": 20850150, + "role": "exit" + } + ], + "tags": { + "amenity": "parking", + "fee": "yes", + "name": "Schillerplatz", + "opening_hours": "24/7", + "operator": "APCOA PARKING Deutschland GmbH", + "parking": "underground", + "site": "parking", + "type": "site", + "url": "https://service.stuttgart.de/lhs-services/ivlz/index.php?uid=35&objectid=108523&objecttype=dept&page=svc&servicetype=parking&serviceid=9356&detailid=65&showservice=1", + "website": "https://www.apcoa.de/parken-in/stuttgart/schillerplatz.html" + } +} + + ] +} + diff --git a/tests/test_conversion.py b/tests/test_conversion.py new file mode 100644 index 0000000..69eafb8 --- /dev/null +++ b/tests/test_conversion.py @@ -0,0 +1,31 @@ +import json +import unittest + +from osmtogeojson import osmtogeojson + +class ConversionTest(unittest.TestCase): + + # We want to see the differences + maxDiff = None + + def test_relation_with_different_member_types_becomes_GeometryCollection(self): + self.compare_files("geomcollection_overpass.json", "geomcollection_geojson.json") + + def not_yet_test_np(self): + self.compare_files("np_overpass.json", "np_geojson.json") + + def not_yet_test_summitschool(self): + self.compare_files("summitschool_overpass.json", "summitschool_geojson.json") + + def compare_files(self, inputfile, geojsonfile): + with open("tests/fixtures/" + inputfile, "r") as f: + osm_json = json.loads(f.read()) + + with open("tests/fixtures/" + geojsonfile, "r") as f: + expected_geojson = json.loads(f.read()) + + actual_geojson = osmtogeojson.process_osm_json(osm_json) + self.assertEqual(actual_geojson, expected_geojson) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file
Relations with LineString and Polygon members have no geometry If a relation has Polygons and LineStrings way members, the resulting feature has no geometry. tyrasd/osmtogeojson instead seems to export every member as feature with an @relations property. osmtogeojson should either behave accordingly or provide all members geometries as a GeometryCollection. Example for [relation/5576903](https://openstreetmap.org/relation/5576903): ``` { "type": "Feature", "properties": { "@id": "way/376770457", "covered": "yes", "highway": "service", "indoor": "yes", "layer": "-2", "location": "underground", "oneway": "yes", "ref": "Ebene B", "service": "parking_aisle", "sidewalk": "left", "@relations": [ { "role": "", "rel": 5576903, "reltags": { "amenity": "parking", "fee": "yes", "name": "Schillerplatz", "opening_hours": "24/7", "operator": "APCOA PARKING Deutschland GmbH", "parking": "underground", "site": "parking", "type": "site", "url": "https://service.stuttgart.de/lhs-services/ivlz/index.php?uid=35&objectid=108523&objecttype=dept&page=svc&servicetype=parking&serviceid=9356&detailid=65&showservice=1", "website": "https://www.apcoa.de/parken-in/stuttgart/schillerplatz.html" } } ] }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 9.178458, 48.7770338 ], ... ]] } } ```
0.0
128ec15acd298926dc9070b91ce45546a581b90f
[ "tests/test_conversion.py::ConversionTest::test_relation_with_different_member_types_becomes_GeometryCollection" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-26 12:03:29+00:00
mit
6,046
tonioo__sievelib-79
diff --git a/README.rst b/README.rst index 68ff377..e278c60 100644 --- a/README.rst +++ b/README.rst @@ -38,12 +38,13 @@ The following extensions are also supported: * Copying Without Side Effects (`RFC 3894 <https://tools.ietf.org/html/rfc3894>`_) * Body (`RFC 5173 <https://tools.ietf.org/html/rfc5173>`_) -* Date and Index (`RFC 5260 <https://tools.ietf.org/html/rfc5260>`_) * Vacation (`RFC 5230 <http://tools.ietf.org/html/rfc5230>`_) +* Relational (`RFC 5231 <https://tools.ietf.org/html/rfc5231>`_) * Imap4flags (`RFC 5232 <https://tools.ietf.org/html/rfc5232>`_) The following extensions are partially supported: +* Date and Index (`RFC 5260 <https://tools.ietf.org/html/rfc5260>`_) * Checking Mailbox Status and Accessing Mailbox Metadata (`RFC 5490 <https://tools.ietf.org/html/rfc5490>`_) Extending the parser diff --git a/sievelib/commands.py b/sievelib/commands.py index 7f6df2e..d26bcb5 100644 --- a/sievelib/commands.py +++ b/sievelib/commands.py @@ -98,10 +98,21 @@ address_part = {"name": "address-part", "values": [":localpart", ":domain", ":all"], "type": ["tag"], "required": False} -match_type = {"name": "match-type", - "values": [":is", ":contains", ":matches"], - "type": ["tag"], - "required": False} +match_type = { + "name": "match-type", + "values": [":is", ":contains", ":matches"], + "extension_values": { + ":count": "relational", + ":value": "relational" + }, + "extra_arg": { + "type": "string", + "values": ['"gt"', '"ge"', '"lt"', '"le"', '"eq"', '"ne"'], + "valid_for": [":count", ":value"] + }, + "type": ["tag"], + "required": False +} class Command(object): @@ -343,9 +354,17 @@ class Command(object): :param value: the value to check :return: True on succes, False otherwise """ - if "values" not in arg: + if "values" not in arg and "extension_values" not in arg: + return True + if "values" in arg and value.lower() in arg["values"]: return True - return value.lower() in arg["values"] + if "extension_values" in arg: + extension = arg["extension_values"].get(value.lower()) + if extension: + if extension not in RequireCommand.loaded_extensions: + raise ExtensionNotLoaded(extension) + return True + return False def __is_valid_type(self, typ, typlist): """ Check if type is valid based on input type list @@ -431,7 +450,6 @@ class Command(object): condition = ( atype in curarg["type"] and - ("values" not in curarg or avalue in curarg["values"]) and self.__is_valid_value_for_arg(curarg, avalue) ) if condition: @@ -892,6 +910,59 @@ class HasflagCommand(TestCommand): self.rargs_cnt = 1 +class DateCommand(TestCommand): + """date command, part of the date extension. + + https://tools.ietf.org/html/rfc5260#section-4 + """ + + extension = "date" + args_definition = [ + {"name": "zone", + "type": ["tag"], + "write_tag": True, + "values": [":zone", ":originalzone"], + "extra_arg": {"type": "string", "valid_for": [":zone"]}, + "required": False}, + comparator, + match_type, + {"name": "header-name", + "type": ["string"], + "required": True}, + {"name": "date-part", + "type": ["string"], + "required": True}, + {"name": "key-list", + "type": ["string", "stringlist"], + "required": True} + ] + + +class CurrentdateCommand(TestCommand): + """currentdate command, part of the date extension. + + http://tools.ietf.org/html/rfc5260#section-5 + """ + + extension = "date" + args_definition = [ + {"name": "zone", + "type": ["tag"], + "write_tag": True, + "values": [":zone"], + "extra_arg": {"type": "string"}, + "required": False}, + comparator, + match_type, + {"name": "date-part", + "type": ["string"], + "required": True}, + {"name": "key-list", + "type": ["string", "stringlist"], + "required": True} + ] + + class VacationCommand(ActionCommand): args_definition = [ {"name": "subject", @@ -937,7 +1008,7 @@ class VacationCommand(ActionCommand): class SetCommand(ControlCommand): - """currentdate command, part of the variables extension + """set command, part of the variables extension http://tools.ietf.org/html/rfc5229 """ @@ -953,37 +1024,6 @@ class SetCommand(ControlCommand): ] -class CurrentdateCommand(ControlCommand): - - """currentdate command, part of the date extension - - http://tools.ietf.org/html/rfc5260#section-5 - """ - - extension = "date" - accept_children = True - args_definition = [ - {"name": "zone", - "type": ["tag"], - "write_tag": True, - "values": [":zone"], - "extra_arg": {"type": "string"}, - "required": False}, - {"name": "match-value", - "type": ["tag"], - "required": True}, - {"name": "comparison", - "type": ["string"], - "required": True}, - {"name": "match-against", - "type": ["string"], - "required": True}, - {"name": "match-against-field", - "type": ["string"], - "required": True} - ] - - def add_commands(cmds): """ Adds one or more commands to the module namespace.
tonioo/sievelib
64ff2381866f7c820d579ce980eeec87d76a3f0d
diff --git a/sievelib/tests/test_parser.py b/sievelib/tests/test_parser.py index 65e6393..430cdf1 100644 --- a/sievelib/tests/test_parser.py +++ b/sievelib/tests/test_parser.py @@ -779,10 +779,20 @@ if exists ["subject"] class DateCommands(SieveTest): + + def test_date_command(self): + self.compilation_ok(b"""require ["date", "relational", "fileinto"]; +if allof(header :is "from" "[email protected]", + date :value "ge" :originalzone "date" "hour" "09", + date :value "lt" :originalzone "date" "hour" "17") +{ fileinto "urgent"; } +""") + def test_currentdate_command(self): self.compilation_ok(b"""require ["date", "relational"]; -if allof ( currentdate :value "ge" "date" "2013-10-23" , currentdate :value "le" "date" "2014-10-12" ) +if allof(currentdate :value "ge" "date" "2013-10-23", + currentdate :value "le" "date" "2014-10-12") { discard; } @@ -791,7 +801,8 @@ if allof ( currentdate :value "ge" "date" "2013-10-23" , currentdate :value "le" def test_currentdate_command_timezone(self): self.compilation_ok(b"""require ["date", "relational"]; -if allof ( currentdate :zone "+0100" :value "ge" "date" "2013-10-23" , currentdate :value "le" "date" "2014-10-12" ) +if allof(currentdate :zone "+0100" :value "ge" "date" "2013-10-23", + currentdate :value "le" "date" "2014-10-12") { discard; } @@ -800,13 +811,22 @@ if allof ( currentdate :zone "+0100" :value "ge" "date" "2013-10-23" , currentda def test_currentdate_norel(self): self.compilation_ok(b"""require ["date"]; -if allof ( - currentdate :zone "+0100" :is "date" "2013-10-23" -) +if allof ( + currentdate :zone "+0100" :is "date" "2013-10-23" +) { discard; }""") + def test_currentdate_extension_not_loaded(self): + self.compilation_ko(b"""require ["date"]; + +if allof ( currentdate :value "ge" "date" "2013-10-23" , currentdate :value "le" "date" "2014-10-12" ) +{ + discard; +} +""") + class VariablesCommands(SieveTest): def test_set_command(self):
Better support of relational and date extensions The current implementation is buggy.
0.0
64ff2381866f7c820d579ce980eeec87d76a3f0d
[ "sievelib/tests/test_parser.py::DateCommands::test_currentdate_extension_not_loaded", "sievelib/tests/test_parser.py::DateCommands::test_date_command" ]
[ "sievelib/tests/test_parser.py::AdditionalCommands::test_add_command", "sievelib/tests/test_parser.py::AdditionalCommands::test_quota_notification", "sievelib/tests/test_parser.py::ValidEncodings::test_utf8_file", "sievelib/tests/test_parser.py::ValidSyntaxes::test_body_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_complex_allof_with_not", "sievelib/tests/test_parser.py::ValidSyntaxes::test_explicit_comparator", "sievelib/tests/test_parser.py::ValidSyntaxes::test_fileinto_create", "sievelib/tests/test_parser.py::ValidSyntaxes::test_hash_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_hasflag", "sievelib/tests/test_parser.py::ValidSyntaxes::test_just_one_command", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiline_string", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiple_not", "sievelib/tests/test_parser.py::ValidSyntaxes::test_nested_blocks", "sievelib/tests/test_parser.py::ValidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::ValidSyntaxes::test_reject_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_rfc5228_extended", "sievelib/tests/test_parser.py::ValidSyntaxes::test_singletest_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_string_with_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_true_test", "sievelib/tests/test_parser.py::ValidSyntaxes::test_truefalse_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_basic", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_medium", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_limit", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_multiline", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_single_mail_address", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_comma_inside_arguments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_not", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_extra_arg", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_parenthesis", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon_in_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nested_comments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list2", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unclosed_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unknown_token", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_comparator_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_exists_get_string_or_list", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_fileinto", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_mailbox", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_nested_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_not_included_extension", "sievelib/tests/test_parser.py::LanguageRestrictions::test_test_outside_control", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unexpected_argument", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unknown_control", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command_timezone", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_norel", "sievelib/tests/test_parser.py::VariablesCommands::test_set_command", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_fileinto_with_copy", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_redirect_with_copy" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-02-25 10:50:21+00:00
mit
6,047
tonioo__sievelib-82
diff --git a/sievelib/commands.py b/sievelib/commands.py index d26bcb5..c2db5a4 100644 --- a/sievelib/commands.py +++ b/sievelib/commands.py @@ -962,6 +962,22 @@ class CurrentdateCommand(TestCommand): "required": True} ] + def args_as_tuple(self): + """Return arguments as a list.""" + result = ("currentdate", ) + result += ( + ":zone", + self.arguments["zone"].strip('"'), + self.arguments["match-type"], + self.arguments["date-part"].strip('"') + ) + if self.arguments["key-list"].startswith("["): + result = result + tuple( + tools.to_list(self.arguments["key-list"])) + else: + result = result + (self.arguments["key-list"].strip('"'),) + return result + class VacationCommand(ActionCommand): args_definition = [ diff --git a/sievelib/factory.py b/sievelib/factory.py index eb9b32e..8c065aa 100644 --- a/sievelib/factory.py +++ b/sievelib/factory.py @@ -215,6 +215,23 @@ class FiltersSet(object): "stringlist", "[%s]" % (",".join('"%s"' % val for val in c[3:])) ) + elif cname == "currentdate": + cmd = commands.get_command_instance( + "currentdate", ifcontrol, False) + self.require(cmd.extension) + cmd.check_next_arg("tag", c[1]) + cmd.check_next_arg("string", self.__quote_if_necessary(c[2])) + if c[3].startswith(":not"): + comp_tag = c[3].replace("not", "") + negate = True + else: + comp_tag = c[3] + cmd.check_next_arg("tag", comp_tag) + cmd.check_next_arg("string", self.__quote_if_necessary(c[4])) + cmd.check_next_arg( + "stringlist", + "[%s]" % (",".join('"%s"' % val for val in c[5:])) + ) else: # header command fallback if c[1].startswith(':not'): @@ -356,7 +373,8 @@ class FiltersSet(object): commands.SizeCommand, commands.ExistsCommand, commands.BodyCommand, - commands.EnvelopeCommand)): + commands.EnvelopeCommand, + commands.CurrentdateCommand)): args = node.args_as_tuple() if negate: if node.name in ["header", "envelope"]: @@ -367,6 +385,12 @@ class FiltersSet(object): (":not{}".format(args[2][1:]),) + args[3:] ) + elif node.name == "currentdate": + args = ( + args[:3] + + (":not{}".format(args[3][1:]),) + + args[4:] + ) elif node.name == "exists": args = ("not{}".format(args[0]),) + args[1:] negate = False
tonioo/sievelib
a8c63b395ac67830d65670dde026775f1742c6bb
diff --git a/sievelib/tests/test_factory.py b/sievelib/tests/test_factory.py index 42b3964..e2e602d 100644 --- a/sievelib/tests/test_factory.py +++ b/sievelib/tests/test_factory.py @@ -68,6 +68,17 @@ class FactoryTestCase(unittest.TestCase): conditions = self.fs.get_filter_conditions("ruleC") self.assertEqual(orig_conditions, conditions) + orig_conditions = [( + "currentdate", ":zone", "+0100", ":notis", "date", "2019-02-26" + )] + self.fs.addfilter( + "ruleD", + orig_conditions, + [("fileinto", "INBOX")] + ) + conditions = self.fs.get_filter_conditions("ruleD") + self.assertEqual(orig_conditions, conditions) + def test_get_filter_matchtype(self): """Test get_filter_matchtype method.""" self.fs.addfilter( @@ -298,6 +309,21 @@ if anyof (not envelope :is ["From"] ["hello"]) { } """) + def test_add_currentdate_filter(self): + """Add a currentdate filter.""" + self.fs.addfilter( + "test", + [("currentdate", ":zone", "+0100", ":is", "date", "2019-02-26")], + [("fileinto", "INBOX")] + ) + self.assertEqual("{}".format(self.fs), """require ["date", "fileinto"]; + +# Filter: test +if anyof (currentdate :zone "+0100" :is "date" ["2019-02-26"]) { + fileinto "INBOX"; +} +""") + if __name__ == "__main__": unittest.main()
Factory: add support for currentdate test Make the factory module understand the currendate test.
0.0
a8c63b395ac67830d65670dde026775f1742c6bb
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_add_currentdate_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_conditions" ]
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_add_body_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_envelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_filter_unicode", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notbody_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notenvelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_size_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_disablefilter", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_actions", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_matchtype", "sievelib/tests/test_factory.py::FactoryTestCase::test_remove_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_use_action_with_tag" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-02-28 10:45:28+00:00
mit
6,048
tonioo__sievelib-84
diff --git a/sievelib/commands.py b/sievelib/commands.py index 5a9bf2f..acb4535 100644 --- a/sievelib/commands.py +++ b/sievelib/commands.py @@ -550,10 +550,6 @@ class RequireCommand(ControlCommand): RequireCommand.loaded_extensions += [ext] -class StopCommand(ControlCommand): - args_definition = [] - - class IfCommand(ControlCommand): accept_children = True @@ -614,6 +610,10 @@ class ActionCommand(Command): return (self.name, ) + tuple(args) +class StopCommand(ActionCommand): + args_definition = [] + + class FileintoCommand(ActionCommand): extension = "fileinto" args_definition = [
tonioo/sievelib
37463faa2019c4856620473231d3ad3a8a57858d
diff --git a/sievelib/tests/test_factory.py b/sievelib/tests/test_factory.py index 1da42aa..f425363 100644 --- a/sievelib/tests/test_factory.py +++ b/sievelib/tests/test_factory.py @@ -111,6 +111,14 @@ class FactoryTestCase(unittest.TestCase): self.assertIn(":copy", actions[0]) self.assertIn("Toto", actions[0]) + self.fs.addfilter( + "ruleY", + [("Subject", ":contains", "aaa")], + [("stop",)] + ) + actions = self.fs.get_filter_actions("ruleY") + self.assertIn("stop", actions[0]) + def test_add_header_filter(self): output = six.StringIO() self.fs.addfilter( diff --git a/sievelib/tests/test_parser.py b/sievelib/tests/test_parser.py index d5fa697..8890eac 100644 --- a/sievelib/tests/test_parser.py +++ b/sievelib/tests/test_parser.py @@ -189,7 +189,7 @@ noreply Your email has been canceled ============================ . - stop (type: control) + stop (type: action) else (type: control) reject (type: action) text: @@ -399,7 +399,7 @@ if (type: control) not (type: test) not (type: test) true (type: test) - stop (type: control) + stop (type: action) """) def test_just_one_command(self):
stop action is wrongly implemented It is currently declared as a control command.
0.0
37463faa2019c4856620473231d3ad3a8a57858d
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_actions", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiline_string", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiple_not" ]
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_add_body_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_currentdate_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_envelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_filter_unicode", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notbody_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notenvelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_size_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_disablefilter", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_conditions", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_matchtype", "sievelib/tests/test_factory.py::FactoryTestCase::test_remove_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_use_action_with_tag", "sievelib/tests/test_parser.py::AdditionalCommands::test_add_command", "sievelib/tests/test_parser.py::AdditionalCommands::test_quota_notification", "sievelib/tests/test_parser.py::ValidEncodings::test_utf8_file", "sievelib/tests/test_parser.py::ValidSyntaxes::test_body_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_complex_allof_with_not", "sievelib/tests/test_parser.py::ValidSyntaxes::test_explicit_comparator", "sievelib/tests/test_parser.py::ValidSyntaxes::test_fileinto_create", "sievelib/tests/test_parser.py::ValidSyntaxes::test_hash_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_hasflag", "sievelib/tests/test_parser.py::ValidSyntaxes::test_just_one_command", "sievelib/tests/test_parser.py::ValidSyntaxes::test_nested_blocks", "sievelib/tests/test_parser.py::ValidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::ValidSyntaxes::test_reject_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_rfc5228_extended", "sievelib/tests/test_parser.py::ValidSyntaxes::test_singletest_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_string_with_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_true_test", "sievelib/tests/test_parser.py::ValidSyntaxes::test_truefalse_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_basic", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_medium", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_limit", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_multiline", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_single_mail_address", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_comma_inside_arguments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_not", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_extra_arg", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_parenthesis", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon_in_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nested_comments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list2", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unclosed_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unknown_token", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_comparator_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_exists_get_string_or_list", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_fileinto", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_mailbox", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_nested_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_not_included_extension", "sievelib/tests/test_parser.py::LanguageRestrictions::test_test_outside_control", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unexpected_argument", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unknown_control", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command_timezone", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_extension_not_loaded", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_norel", "sievelib/tests/test_parser.py::DateCommands::test_date_command", "sievelib/tests/test_parser.py::VariablesCommands::test_set_command", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_fileinto_with_copy", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_redirect_with_copy" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-03-18 09:11:44+00:00
mit
6,049
tonioo__sievelib-86
diff --git a/sievelib/commands.py b/sievelib/commands.py index acb4535..fa133d5 100644 --- a/sievelib/commands.py +++ b/sievelib/commands.py @@ -798,7 +798,16 @@ class ExistsCommand(TestCommand): ] def args_as_tuple(self): + """FIXME: en fonction de la manière dont la commande a été générée + (factory ou parser), le type des arguments est différent : + string quand ça vient de la factory ou type normal depuis le + parser. Il faut uniformiser tout ça !! + + """ value = self.arguments["header-names"] + if isinstance(value, list): + value = "[{}]".format( + ",".join('"{}"'.format(item) for item in value)) if not value.startswith("["): return ('exists', value.strip('"')) return ("exists", ) + tuple(tools.to_list(value))
tonioo/sievelib
df786d65f3279ee3e28d2565f4b843b0939c304e
diff --git a/sievelib/tests/test_factory.py b/sievelib/tests/test_factory.py index f425363..7787e5c 100644 --- a/sievelib/tests/test_factory.py +++ b/sievelib/tests/test_factory.py @@ -5,6 +5,7 @@ import unittest import six from sievelib.factory import FiltersSet +from .. import parser class FactoryTestCase(unittest.TestCase): @@ -91,6 +92,21 @@ class FactoryTestCase(unittest.TestCase): conditions = self.fs.get_filter_conditions("ruleE") self.assertEqual(orig_conditions, conditions) + def test_get_filter_conditions_from_parser_result(self): + res = """require ["fileinto"]; + +# rule:[test] +if anyof (exists ["Subject"]) { + fileinto "INBOX"; +} +""" + p = parser.Parser() + p.parse(res) + fs = FiltersSet("test", '# rule:') + fs.from_parser_result(p) + c = fs.get_filter_conditions('[test]') + self.assertEqual(c, [("exists", "Subject")]) + def test_get_filter_matchtype(self): """Test get_filter_matchtype method.""" self.fs.addfilter(
factory: problem while exporting exists command When we try to export an exists command, previously parsed, through the factory module, it fails with the following stack: ```python >>> c = fs.get_filter_conditions('[test]') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/matteo/src/webmail/be/qbservice/sievelib/factory.py", line 387, in get_filter_conditions args = node.args_as_tuple() File "/home/matteo/src/webmail/be/qbservice/sievelib/commands.py", line 802, in args_as_tuple if not value.startswith("["): AttributeError: 'list' object has no attribute 'startswith' ```
0.0
df786d65f3279ee3e28d2565f4b843b0939c304e
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_conditions_from_parser_result" ]
[ "sievelib/tests/test_factory.py::FactoryTestCase::test_add_body_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_currentdate_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_envelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_exists_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_filter_unicode", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_header_filter_with_not", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notbody_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_notenvelope_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_add_size_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_disablefilter", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_actions", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_conditions", "sievelib/tests/test_factory.py::FactoryTestCase::test_get_filter_matchtype", "sievelib/tests/test_factory.py::FactoryTestCase::test_remove_filter", "sievelib/tests/test_factory.py::FactoryTestCase::test_use_action_with_tag" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-03-21 08:53:34+00:00
mit
6,050
tonioo__sievelib-97
diff --git a/sievelib/parser.py b/sievelib/parser.py index a92f5f1..219ca94 100755 --- a/sievelib/parser.py +++ b/sievelib/parser.py @@ -142,7 +142,7 @@ class Parser(object): self.__curcommand = None self.__curstringlist = None self.__expected = None - self.__opened_blocks = 0 + self.__expected_brackets = [] RequireCommand.loaded_extensions = [] def __set_expected(self, *args, **kwargs): @@ -153,6 +153,28 @@ class Parser(object): """ self.__expected = args + def __push_expected_bracket(self, ttype, tvalue): + """Append a new expected bracket. + + Next time a bracket is closed, it must match the one provided here. + """ + self.__expected_brackets.append((ttype, tvalue)) + + def __pop_expected_bracket(self, ttype, tvalue): + """Drop the last expected bracket. + + If the given bracket doesn't match the dropped expected bracket, + or if no bracket is expected at all, a ParseError will be raised. + """ + try: + etype, evalue = self.__expected_brackets.pop() + except IndexError: + raise ParseError("unexpected closing bracket %s (none opened)" % + (tvalue,)) + if ttype != etype: + raise ParseError("unexpected closing bracket %s (expected %s)" % + (tvalue, evalue)) + def __up(self, onlyrecord=False): """Return to the current command's parent @@ -251,6 +273,7 @@ class Parser(object): self.__set_expected("string") return True if ttype == "right_bracket": + self.__pop_expected_bracket(ttype, tvalue) self.__curcommand.check_next_arg("stringlist", self.__curstringlist) self.__cstate = self.__arguments return self.__check_command_completion() @@ -275,6 +298,7 @@ class Parser(object): return self.__curcommand.check_next_arg(ttype, tvalue.decode("ascii")) if ttype == "left_bracket": + self.__push_expected_bracket("right_bracket", b'}') self.__cstate = self.__stringlist self.__curstringlist = [] self.__set_expected("string") @@ -314,6 +338,7 @@ class Parser(object): return self.__check_command_completion(testsemicolon=False) if ttype == "left_parenthesis": + self.__push_expected_bracket("right_parenthesis", b')') self.__set_expected("identifier") return True @@ -322,6 +347,7 @@ class Parser(object): return True if ttype == "right_parenthesis": + self.__pop_expected_bracket(ttype, tvalue) self.__up() return True @@ -348,8 +374,8 @@ class Parser(object): """ if self.__cstate is None: if ttype == "right_cbracket": + self.__pop_expected_bracket(ttype, tvalue) self.__up() - self.__opened_blocks -= 1 self.__cstate = None return True @@ -376,7 +402,7 @@ class Parser(object): return True if ttype == "left_cbracket": - self.__opened_blocks += 1 + self.__push_expected_bracket("right_cbracket", b'}') self.__cstate = None return True @@ -438,8 +464,8 @@ class Parser(object): % (tvalue.decode(), text.decode()[self.lexer.pos]) ) raise ParseError(msg) - if self.__opened_blocks: - self.__set_expected("right_cbracket") + if self.__expected_brackets: + self.__set_expected(self.__expected_brackets[-1][0]) if self.__expected is not None: raise ParseError("end of script reached while %s expected" % "|".join(self.__expected))
tonioo/sievelib
2603aa2a24fb32132e40b006a73d2aadc5f66355
diff --git a/sievelib/tests/test_parser.py b/sievelib/tests/test_parser.py index 8890eac..f41cf86 100644 --- a/sievelib/tests/test_parser.py +++ b/sievelib/tests/test_parser.py @@ -589,6 +589,16 @@ if header :is "Sender" "[email protected]" { """) + def test_nonopened_parenthesis(self): + self.compilation_ko(b""" +if header :is "Sender" "[email protected]") { + discard; +} +""") + + def test_nonopened_block2(self): + self.compilation_ko(b"""}""") + def test_unknown_token(self): self.compilation_ko(b""" if header :is "Sender" "Toto" & header :contains "Cc" "Tata" { @@ -599,6 +609,9 @@ if header :is "Sender" "Toto" & header :contains "Cc" "Tata" { def test_empty_string_list(self): self.compilation_ko(b"require [];") + def test_unopened_string_list(self): + self.compilation_ko(b'require "fileinto"];') + def test_unclosed_string_list(self): self.compilation_ko(b'require ["toto", "tata";') @@ -834,7 +847,7 @@ class VariablesCommands(SieveTest): self.compilation_ok(b"""require ["variables"]; set "matchsub" "testsubject"; - + if allof ( header :contains ["Subject"] "${header}" )
Parser does insufficient bracket matching The following script crashes the parser instead of generating a parse error: ```}``` Upon investigation, the problem seems to be that the parser doesn't always check if the current context allows for closing a bracket (either of `)]}`), and often just assumes we're in the right context when one of them is encountered. A solution could be for the parser to maintain a stack of open brackets (e.g. a list `['(', '{', '[']`) and `push` to it on each opening bracket, and when closing one, `pop`s the last bracket and confirm it's the same as the one we're closing, otherwise issuing a parse error. I shall try to implement such a solution and file it as a PR. But maybe another solution would be preferred? Cf. derula/strainer#15
0.0
2603aa2a24fb32132e40b006a73d2aadc5f66355
[ "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_block2", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_parenthesis" ]
[ "sievelib/tests/test_parser.py::AdditionalCommands::test_add_command", "sievelib/tests/test_parser.py::AdditionalCommands::test_quota_notification", "sievelib/tests/test_parser.py::ValidEncodings::test_utf8_file", "sievelib/tests/test_parser.py::ValidSyntaxes::test_body_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_complex_allof_with_not", "sievelib/tests/test_parser.py::ValidSyntaxes::test_explicit_comparator", "sievelib/tests/test_parser.py::ValidSyntaxes::test_fileinto_create", "sievelib/tests/test_parser.py::ValidSyntaxes::test_hash_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_imap4flags_hasflag", "sievelib/tests/test_parser.py::ValidSyntaxes::test_just_one_command", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiline_string", "sievelib/tests/test_parser.py::ValidSyntaxes::test_multiple_not", "sievelib/tests/test_parser.py::ValidSyntaxes::test_nested_blocks", "sievelib/tests/test_parser.py::ValidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::ValidSyntaxes::test_reject_extension", "sievelib/tests/test_parser.py::ValidSyntaxes::test_rfc5228_extended", "sievelib/tests/test_parser.py::ValidSyntaxes::test_singletest_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_string_with_bracket_comment", "sievelib/tests/test_parser.py::ValidSyntaxes::test_true_test", "sievelib/tests/test_parser.py::ValidSyntaxes::test_truefalse_testlist", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_basic", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_medium", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_limit", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_multiline", "sievelib/tests/test_parser.py::ValidSyntaxes::test_vacationext_with_single_mail_address", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_comma_inside_arguments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_not", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_empty_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_extra_arg", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_comma_in_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_misplaced_parenthesis", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_missing_semicolon_in_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nested_comments", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_non_ordered_args", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonclosed_tests_list2", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_block", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_nonopened_tests_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unclosed_string_list", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unknown_token", "sievelib/tests/test_parser.py::InvalidSyntaxes::test_unopened_string_list", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_arg_value2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_bad_comparator_value", "sievelib/tests/test_parser.py::LanguageRestrictions::test_exists_get_string_or_list", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_fileinto", "sievelib/tests/test_parser.py::LanguageRestrictions::test_fileinto_create_without_mailbox", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_elsif2", "sievelib/tests/test_parser.py::LanguageRestrictions::test_misplaced_nested_elsif", "sievelib/tests/test_parser.py::LanguageRestrictions::test_not_included_extension", "sievelib/tests/test_parser.py::LanguageRestrictions::test_test_outside_control", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unexpected_argument", "sievelib/tests/test_parser.py::LanguageRestrictions::test_unknown_control", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_command_timezone", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_extension_not_loaded", "sievelib/tests/test_parser.py::DateCommands::test_currentdate_norel", "sievelib/tests/test_parser.py::DateCommands::test_date_command", "sievelib/tests/test_parser.py::VariablesCommands::test_set_command", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_fileinto_with_copy", "sievelib/tests/test_parser.py::CopyWithoutSideEffectsTestCase::test_redirect_with_copy" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-14 13:50:47+00:00
mit
6,051
tonybaloney__wily-200
diff --git a/src/wily/__main__.py b/src/wily/__main__.py index 1b4c7ef..617aefe 100644 --- a/src/wily/__main__.py +++ b/src/wily/__main__.py @@ -11,6 +11,7 @@ from wily.archivers import resolve_archiver from wily.cache import exists, get_default_metrics from wily.config import DEFAULT_CONFIG_PATH, DEFAULT_GRID_STYLE from wily.config import load as load_config +from wily.helper import get_style from wily.helper.custom_enums import ReportFormat from wily.lang import _ from wily.operators import resolve_operators @@ -279,6 +280,8 @@ def report( else: new_output = new_output / "wily_report" / "index.html" + style = get_style(console_format) + from wily.commands.report import report logger.debug(f"Running report on {file} for metric {metrics}") @@ -292,7 +295,7 @@ def report( output=new_output, include_message=message, format=ReportFormat[format], - console_format=console_format, + console_format=style, changes_only=changes, ) diff --git a/src/wily/commands/diff.py b/src/wily/commands/diff.py index fd05c91..fc19c6f 100644 --- a/src/wily/commands/diff.py +++ b/src/wily/commands/diff.py @@ -14,7 +14,8 @@ import tabulate from wily import format_date, format_revision, logger from wily.archivers import resolve_archiver from wily.commands.build import run_operator -from wily.config import DEFAULT_GRID_STYLE, DEFAULT_PATH +from wily.config import DEFAULT_PATH +from wily.helper import get_style from wily.operators import ( BAD_COLORS, GOOD_COLORS, @@ -160,9 +161,8 @@ def diff(config, files, metrics, changes_only=True, detail=True, revision=None): descriptions = [metric.description for operator, metric in metrics] headers = ("File", *descriptions) if len(results) > 0: + style = get_style() print( # But it still makes more sense to show the newest at the top, so reverse again - tabulate.tabulate( - headers=headers, tabular_data=results, tablefmt=DEFAULT_GRID_STYLE - ) + tabulate.tabulate(headers=headers, tabular_data=results, tablefmt=style) ) diff --git a/src/wily/commands/index.py b/src/wily/commands/index.py index 8150bdf..e7f1a55 100644 --- a/src/wily/commands/index.py +++ b/src/wily/commands/index.py @@ -6,7 +6,7 @@ Print information about the wily cache and what is in the index. import tabulate from wily import MAX_MESSAGE_WIDTH, format_date, format_revision, logger -from wily.config import DEFAULT_GRID_STYLE +from wily.helper import get_style from wily.state import State @@ -54,8 +54,6 @@ def index(config, include_message=False): headers = ("Revision", "Author", "Message", "Date") else: headers = ("Revision", "Author", "Date") - print( - tabulate.tabulate( - headers=headers, tabular_data=data, tablefmt=DEFAULT_GRID_STYLE - ) - ) + + style = get_style() + print(tabulate.tabulate(headers=headers, tabular_data=data, tablefmt=style)) diff --git a/src/wily/commands/list_metrics.py b/src/wily/commands/list_metrics.py index 6a8ef61..d9b81d1 100644 --- a/src/wily/commands/list_metrics.py +++ b/src/wily/commands/list_metrics.py @@ -5,12 +5,13 @@ TODO : Only show metrics for the operators that the cache has? """ import tabulate -from wily.config import DEFAULT_GRID_STYLE +from wily.helper import get_style from wily.operators import ALL_OPERATORS def list_metrics(): """List metrics available.""" + style = get_style() for name, operator in ALL_OPERATORS.items(): print(f"{name} operator:") if len(operator.cls.metrics) > 0: @@ -18,6 +19,6 @@ def list_metrics(): tabulate.tabulate( headers=("Name", "Description", "Type"), tabular_data=operator.cls.metrics, - tablefmt=DEFAULT_GRID_STYLE, + tablefmt=style, ) ) diff --git a/src/wily/commands/rank.py b/src/wily/commands/rank.py index 5600b81..32a3e86 100644 --- a/src/wily/commands/rank.py +++ b/src/wily/commands/rank.py @@ -17,7 +17,8 @@ import tabulate from wily import format_date, format_revision, logger from wily.archivers import resolve_archiver -from wily.config import DEFAULT_GRID_STYLE, DEFAULT_PATH +from wily.config import DEFAULT_PATH +from wily.helper import get_style from wily.operators import resolve_metric_as_tuple from wily.state import State @@ -117,11 +118,8 @@ def rank(config, path, metric, revision_index, limit, threshold, descending): data.append(["Total", total]) headers = ("File", metric.description) - print( - tabulate.tabulate( - headers=headers, tabular_data=data, tablefmt=DEFAULT_GRID_STYLE - ) - ) + style = get_style() + print(tabulate.tabulate(headers=headers, tabular_data=data, tablefmt=style)) if threshold and total < threshold: logger.error( diff --git a/src/wily/helper/__init__.py b/src/wily/helper/__init__.py index a1f80be..7c52235 100644 --- a/src/wily/helper/__init__.py +++ b/src/wily/helper/__init__.py @@ -1,1 +1,12 @@ """Helper package for wily.""" +import sys + +from wily.config import DEFAULT_GRID_STYLE + + +def get_style(style=DEFAULT_GRID_STYLE): + """Select the tablefmt style for tabulate according to what sys.stdout can handle.""" + if style == DEFAULT_GRID_STYLE: + if sys.stdout.encoding.lower() not in ("utf-8", "utf8"): + style = "grid" + return style
tonybaloney/wily
2f59f943d935b0fc4101608783178911dfddbba0
diff --git a/test/unit/test_helper.py b/test/unit/test_helper.py new file mode 100644 index 0000000..6b29d3a --- /dev/null +++ b/test/unit/test_helper.py @@ -0,0 +1,26 @@ +from io import BytesIO, TextIOWrapper +from unittest import mock + +from wily.config import DEFAULT_GRID_STYLE +from wily.helper import get_style + + +def test_get_style(): + output = TextIOWrapper(BytesIO(), encoding="utf-8") + with mock.patch("sys.stdout", output): + style = get_style() + assert style == DEFAULT_GRID_STYLE + + +def test_get_style_charmap(): + output = TextIOWrapper(BytesIO(), encoding="charmap") + with mock.patch("sys.stdout", output): + style = get_style() + assert style == "grid" + + +def test_get_style_charmap_not_default_grid_style(): + output = TextIOWrapper(BytesIO(), encoding="charmap") + with mock.patch("sys.stdout", output): + style = get_style("something_else") + assert style == "something_else"
Wily diff output Hi, I wanted to use wily as an external tool in Pycharm, in order to see the wily diff of a file. `wily.exe diff foobar.py` However this fails and I get this message: ` ... File "c:\programdata\anaconda3\envs\foobar\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-123: character maps to <undefined>` Same happens in the cmd when I wants to pipe the output to a file. `wily.exe diff foobar.py > wilydiff.txt` The output options are not valid for the diffs. Any idea? Thanks
0.0
2f59f943d935b0fc4101608783178911dfddbba0
[ "test/unit/test_helper.py::test_get_style", "test/unit/test_helper.py::test_get_style_charmap", "test/unit/test_helper.py::test_get_style_charmap_not_default_grid_style" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-15 19:16:04+00:00
apache-2.0
6,052
tonybaloney__wily-201
diff --git a/src/wily/__main__.py b/src/wily/__main__.py index 067f643..377c7c8 100644 --- a/src/wily/__main__.py +++ b/src/wily/__main__.py @@ -154,7 +154,13 @@ def build(ctx, max_revisions, targets, operators, archiver): @click.option( "-m", "--message/--no-message", default=False, help=_("Include revision message") ) -def index(ctx, message): [email protected]( + "-w", + "--wrap/--no-wrap", + default=True, + help=_("Wrap index text to fit in terminal"), +) +def index(ctx, message, wrap): """Show the history archive in the .wily/ folder.""" config = ctx.obj["CONFIG"] @@ -163,7 +169,7 @@ def index(ctx, message): from wily.commands.index import index - index(config=config, include_message=message) + index(config=config, include_message=message, wrap=wrap) @cli.command( @@ -206,8 +212,14 @@ def index(ctx, message): help=_("Return a non-zero exit code under the specified threshold"), type=click.INT, ) [email protected]( + "-w", + "--wrap/--no-wrap", + default=True, + help=_("Wrap rank text to fit in terminal"), +) @click.pass_context -def rank(ctx, path, metric, revision, limit, desc, threshold): +def rank(ctx, path, metric, revision, limit, desc, threshold, wrap): """Rank files, methods and functions in order of any metrics, e.g. complexity.""" config = ctx.obj["CONFIG"] @@ -225,6 +237,7 @@ def rank(ctx, path, metric, revision, limit, desc, threshold): limit=limit, threshold=threshold, descending=desc, + wrap=wrap, ) @@ -260,9 +273,15 @@ def rank(ctx, path, metric, revision, limit, desc, threshold): default=False, help=_("Only show revisions that have changes"), ) [email protected]( + "-w", + "--wrap/--no-wrap", + default=True, + help=_("Wrap report text to fit in terminal"), +) @click.pass_context def report( - ctx, file, metrics, number, message, format, console_format, output, changes + ctx, file, metrics, number, message, format, console_format, output, changes, wrap ): """Show metrics for a given file.""" config = ctx.obj["CONFIG"] @@ -297,6 +316,7 @@ def report( format=ReportFormat[format], console_format=style, changes_only=changes, + wrap=wrap, ) @@ -322,8 +342,14 @@ def report( @click.option( "-r", "--revision", help=_("Compare against specific revision"), type=click.STRING ) [email protected]( + "-w", + "--wrap/--no-wrap", + default=True, + help=_("Wrap diff text to fit in terminal"), +) @click.pass_context -def diff(ctx, files, metrics, all, detail, revision): +def diff(ctx, files, metrics, all, detail, revision, wrap): """Show the differences in metrics for each file.""" config = ctx.obj["CONFIG"] @@ -347,6 +373,7 @@ def diff(ctx, files, metrics, all, detail, revision): changes_only=not all, detail=detail, revision=revision, + wrap=wrap, ) @@ -432,8 +459,14 @@ def clean(ctx, yes): @cli.command("list-metrics", help=_("""List the available metrics.""")) [email protected]( + "-w", + "--wrap/--no-wrap", + default=True, + help=_("Wrap metrics text to fit in terminal"), +) @click.pass_context -def list_metrics(ctx): +def list_metrics(ctx, wrap): """List the available metrics.""" config = ctx.obj["CONFIG"] @@ -442,7 +475,7 @@ def list_metrics(ctx): from wily.commands.list_metrics import list_metrics - list_metrics() + list_metrics(wrap) @cli.command("setup", help=_("""Run a guided setup to build the wily cache.""")) diff --git a/src/wily/commands/diff.py b/src/wily/commands/diff.py index fc19c6f..ec0768b 100644 --- a/src/wily/commands/diff.py +++ b/src/wily/commands/diff.py @@ -15,7 +15,7 @@ from wily import format_date, format_revision, logger from wily.archivers import resolve_archiver from wily.commands.build import run_operator from wily.config import DEFAULT_PATH -from wily.helper import get_style +from wily.helper import get_maxcolwidth, get_style from wily.operators import ( BAD_COLORS, GOOD_COLORS, @@ -27,7 +27,9 @@ from wily.operators import ( from wily.state import State -def diff(config, files, metrics, changes_only=True, detail=True, revision=None): +def diff( + config, files, metrics, changes_only=True, detail=True, revision=None, wrap=False +): """ Show the differences in metrics for each of the files. @@ -161,8 +163,15 @@ def diff(config, files, metrics, changes_only=True, detail=True, revision=None): descriptions = [metric.description for operator, metric in metrics] headers = ("File", *descriptions) if len(results) > 0: + maxcolwidth = get_maxcolwidth(headers, wrap) style = get_style() print( # But it still makes more sense to show the newest at the top, so reverse again - tabulate.tabulate(headers=headers, tabular_data=results, tablefmt=style) + tabulate.tabulate( + headers=headers, + tabular_data=results, + tablefmt=style, + maxcolwidths=maxcolwidth, + maxheadercolwidths=maxcolwidth, + ) ) diff --git a/src/wily/commands/index.py b/src/wily/commands/index.py index e7f1a55..d8bebc9 100644 --- a/src/wily/commands/index.py +++ b/src/wily/commands/index.py @@ -6,11 +6,11 @@ Print information about the wily cache and what is in the index. import tabulate from wily import MAX_MESSAGE_WIDTH, format_date, format_revision, logger -from wily.helper import get_style +from wily.helper import get_maxcolwidth, get_style from wily.state import State -def index(config, include_message=False): +def index(config, include_message=False, wrap=False): """ Show information about the cache and runtime. @@ -54,6 +54,14 @@ def index(config, include_message=False): headers = ("Revision", "Author", "Message", "Date") else: headers = ("Revision", "Author", "Date") - + maxcolwidth = get_maxcolwidth(headers, wrap) style = get_style() - print(tabulate.tabulate(headers=headers, tabular_data=data, tablefmt=style)) + print( + tabulate.tabulate( + headers=headers, + tabular_data=data, + tablefmt=style, + maxcolwidths=maxcolwidth, + maxheadercolwidths=maxcolwidth, + ) + ) diff --git a/src/wily/commands/list_metrics.py b/src/wily/commands/list_metrics.py index d9b81d1..572b0ee 100644 --- a/src/wily/commands/list_metrics.py +++ b/src/wily/commands/list_metrics.py @@ -5,20 +5,24 @@ TODO : Only show metrics for the operators that the cache has? """ import tabulate -from wily.helper import get_style +from wily.helper import get_maxcolwidth, get_style from wily.operators import ALL_OPERATORS -def list_metrics(): +def list_metrics(wrap): """List metrics available.""" + headers = ("Name", "Description", "Type", "Measure", "Aggregate") + maxcolwidth = get_maxcolwidth(headers, wrap) style = get_style() for name, operator in ALL_OPERATORS.items(): print(f"{name} operator:") if len(operator.cls.metrics) > 0: print( tabulate.tabulate( - headers=("Name", "Description", "Type"), + headers=headers, tabular_data=operator.cls.metrics, tablefmt=style, + maxcolwidths=maxcolwidth, + maxheadercolwidths=maxcolwidth, ) ) diff --git a/src/wily/commands/rank.py b/src/wily/commands/rank.py index 29c63cf..8f11710 100644 --- a/src/wily/commands/rank.py +++ b/src/wily/commands/rank.py @@ -18,12 +18,12 @@ import tabulate from wily import format_date, format_revision, logger from wily.archivers import resolve_archiver from wily.config import DEFAULT_PATH -from wily.helper import get_style +from wily.helper import get_maxcolwidth, get_style from wily.operators import resolve_metric_as_tuple from wily.state import State -def rank(config, path, metric, revision_index, limit, threshold, descending): +def rank(config, path, metric, revision_index, limit, threshold, descending, wrap): """ Rank command ordering files, methods or functions using metrics. @@ -121,8 +121,17 @@ def rank(config, path, metric, revision_index, limit, threshold, descending): data.append(["Total", total]) headers = ("File", metric.description) + maxcolwidth = get_maxcolwidth(headers, wrap) style = get_style() - print(tabulate.tabulate(headers=headers, tabular_data=data, tablefmt=style)) + print( + tabulate.tabulate( + headers=headers, + tabular_data=data, + tablefmt=style, + maxcolwidths=maxcolwidth, + maxheadercolwidths=maxcolwidth, + ) + ) if threshold and total < threshold: logger.error( diff --git a/src/wily/commands/report.py b/src/wily/commands/report.py index 2dd0bfa..50a99ea 100644 --- a/src/wily/commands/report.py +++ b/src/wily/commands/report.py @@ -11,6 +11,7 @@ from string import Template import tabulate from wily import MAX_MESSAGE_WIDTH, format_date, format_revision, logger +from wily.helper import get_maxcolwidth from wily.helper.custom_enums import ReportFormat from wily.lang import _ from wily.operators import MetricType, resolve_metric_as_tuple @@ -31,6 +32,7 @@ def report( format=ReportFormat.CONSOLE, console_format=None, changes_only=False, + wrap=False, ): """ Show metrics for a given file. @@ -211,8 +213,13 @@ def report( logger.info(f"wily report was saved to {report_path}") else: + maxcolwidth = get_maxcolwidth(headers, wrap) print( tabulate.tabulate( - headers=headers, tabular_data=data[::-1], tablefmt=console_format + headers=headers, + tabular_data=data[::-1], + tablefmt=console_format, + maxcolwidths=maxcolwidth, + maxheadercolwidths=maxcolwidth, ) ) diff --git a/src/wily/helper/__init__.py b/src/wily/helper/__init__.py index 7c52235..d8c8347 100644 --- a/src/wily/helper/__init__.py +++ b/src/wily/helper/__init__.py @@ -1,9 +1,26 @@ """Helper package for wily.""" +import shutil import sys from wily.config import DEFAULT_GRID_STYLE +def get_maxcolwidth(headers, wrap=True): + """Calculate the maximum column width for a given terminal width.""" + if not wrap: + return + width = shutil.get_terminal_size()[0] + columns = len(headers) + if width < 80: + padding = columns + 2 + elif width < 120: + padding = columns - 2 + else: + padding = columns - 4 + maxcolwidth = (width // columns) - padding + return max(maxcolwidth, 1) + + def get_style(style=DEFAULT_GRID_STYLE): """Select the tablefmt style for tabulate according to what sys.stdout can handle.""" if style == DEFAULT_GRID_STYLE:
tonybaloney/wily
b0411ae861b8adc39422328abc6b159e64381715
diff --git a/test/integration/test_diff.py b/test/integration/test_diff.py index 102d31a..2d1760d 100644 --- a/test/integration/test_diff.py +++ b/test/integration/test_diff.py @@ -45,6 +45,18 @@ def test_diff_output_all(builddir): assert "test.py" in result.stdout +def test_diff_output_all_wrapped(builddir): + """Test the diff feature with wrapping""" + runner = CliRunner() + result = runner.invoke( + main.cli, + ["--debug", "--path", builddir, "diff", _path, "--all", "--wrap"], + catch_exceptions=False, + ) + assert result.exit_code == 0, result.stdout + assert "test.py" in result.stdout + + def test_diff_output_bad_path(builddir): """Test the diff feature with no changes""" runner = CliRunner() diff --git a/test/integration/test_index.py b/test/integration/test_index.py index 2d9cad8..1146565 100644 --- a/test/integration/test_index.py +++ b/test/integration/test_index.py @@ -34,3 +34,18 @@ def test_index_with_messages(builddir): assert "add line" in result.stdout assert "remove line" in result.stdout assert result.exit_code == 0, result.stdout + + +def test_index_with_messages_wrapped(builddir): + """ + Test that index works with a build with git commit messages and wrapping + """ + runner = CliRunner() + result = runner.invoke( + main.cli, ["--path", builddir, "index", "--message", "--wrap"] + ) + assert result.stdout.count("An author") == 3 + assert "basic test" in result.stdout + assert "add line" in result.stdout + assert "remove line" in result.stdout + assert result.exit_code == 0, result.stdout diff --git a/test/integration/test_list_metrics.py b/test/integration/test_list_metrics.py new file mode 100644 index 0000000..660b3ab --- /dev/null +++ b/test/integration/test_list_metrics.py @@ -0,0 +1,32 @@ +from click.testing import CliRunner + +import wily.__main__ as main + + +def test_list_metrics(builddir): + """ + Test that list-metrics works and is ordered + """ + runner = CliRunner() + result = runner.invoke(main.cli, ["list-metrics"]) + assert result.stdout.count("operator") == 4 + assert "cyclomatic" in result.stdout + assert "maintainability" in result.stdout + assert "raw" in result.stdout + assert "halstead" in result.stdout + # Test ordering + i = result.stdout.index + assert i("cyclomatic") < i("maintainability") < i("raw") < i("halstead") + + +def test_list_metrics_wrapped(builddir): + """ + Test that list-metrics works with wrapping + """ + runner = CliRunner() + result = runner.invoke(main.cli, ["list-metrics", "--wrap"]) + assert result.stdout.count("operator") == 4 + assert "cyclomatic" in result.stdout + assert "maintainability" in result.stdout + assert "raw" in result.stdout + assert "halstead" in result.stdout diff --git a/test/integration/test_rank.py b/test/integration/test_rank.py index fe62e13..5e852df 100644 --- a/test/integration/test_rank.py +++ b/test/integration/test_rank.py @@ -18,6 +18,15 @@ def test_rank_single_file_default_metric(builddir): assert result.exit_code == 0, result.stdout +def test_rank_single_file_default_metric_wrapped(builddir): + """Test the rank feature with default metric and wrapping""" + runner = CliRunner() + result = runner.invoke( + main.cli, ["--path", builddir, "rank", "--wrap", "src/test.py"] + ) + assert result.exit_code == 0, result.stdout + + def test_rank_directory_default_metric(builddir): """Test the rank feature with default (AimLow) metric on a directory""" runner = CliRunner() diff --git a/test/integration/test_report.py b/test/integration/test_report.py index c5fa049..082ca4d 100644 --- a/test/integration/test_report.py +++ b/test/integration/test_report.py @@ -139,6 +139,18 @@ def test_report_high_metric(builddir): assert "Not found" not in result.stdout +def test_report_wrapped(builddir): + """ + Test that report works with wrapping + """ + runner = CliRunner() + result = runner.invoke( + main.cli, ["--path", builddir, "report", "--wrap", _path, "raw.comments"] + ) + assert result.exit_code == 0, result.stdout + assert "Not found" not in result.stdout + + def test_report_short_metric(builddir): """ Test that report works with a build on shorthand metric diff --git a/test/unit/test_helper.py b/test/unit/test_helper.py index 6b29d3a..8e64f55 100644 --- a/test/unit/test_helper.py +++ b/test/unit/test_helper.py @@ -1,8 +1,133 @@ from io import BytesIO, TextIOWrapper from unittest import mock +import tabulate + from wily.config import DEFAULT_GRID_STYLE -from wily.helper import get_style +from wily.helper import get_maxcolwidth, get_style + +SHORT_DATA = [list("abcdefgh"), list("abcdefgh")] + +MEDIUM_DATA = [["medium_data"] * 2, ["medium_data"] * 2] + +LONG_DATA = [["long_data"] * 8, ["long_data"] * 8] + +HUGE_DATA = [["huge_data"] * 18, ["huge_data"] * 18] + +LONG_LINE_MEDIUM_DATA = [ + ["long_line_for_some_medium_data"] * 2, + ["long_line_for_some_medium_data"] * 2, +] + + +def test_get_maxcolwidth_no_wrap(): + result = get_maxcolwidth([], False) + assert result is None + + +def test_get_maxcolwidth_wrap_short(): + for width in range(35, 100): + mock_get_terminal_size = mock.Mock(return_value=(width, 24)) + mock_shutil = mock.Mock(get_terminal_size=mock_get_terminal_size) + + with mock.patch("wily.helper.shutil", mock_shutil): + result = get_maxcolwidth(SHORT_DATA[0], True) + as_table = tabulate.tabulate( + tabular_data=SHORT_DATA, + tablefmt="grid", + maxcolwidths=result, + maxheadercolwidths=result, + ) + + line = as_table.splitlines()[0] + assert len(line) < width + assert len(line) >= width / 3 + + +def test_get_maxcolwidth_wrap_medium(): + for width in range(35, 100): + mock_get_terminal_size = mock.Mock(return_value=(width, 24)) + mock_shutil = mock.Mock(get_terminal_size=mock_get_terminal_size) + + with mock.patch("wily.helper.shutil", mock_shutil): + result = get_maxcolwidth(MEDIUM_DATA[0], True) + as_table = tabulate.tabulate( + tabular_data=MEDIUM_DATA, + tablefmt="grid", + maxcolwidths=result, + maxheadercolwidths=result, + ) + + line = as_table.splitlines()[0] + print(line) + print(width, len(line)) + assert len(line) < width + if width < 85: + assert len(line) >= width / 3 + + +def test_get_maxcolwidth_wrap_long_line_medium(): + for width in range(35, 100): + mock_get_terminal_size = mock.Mock(return_value=(width, 24)) + mock_shutil = mock.Mock(get_terminal_size=mock_get_terminal_size) + + with mock.patch("wily.helper.shutil", mock_shutil): + result = get_maxcolwidth(LONG_LINE_MEDIUM_DATA[0], True) + as_table = tabulate.tabulate( + tabular_data=LONG_LINE_MEDIUM_DATA, + tablefmt="grid", + maxcolwidths=result, + maxheadercolwidths=result, + ) + + line = as_table.splitlines()[0] + print(line) + print(width, len(line)) + assert len(line) < width + if width < 85: + assert len(line) >= width / 3 + + +def test_get_maxcolwidth_wrap_long(): + for width in range(35, 290): + mock_get_terminal_size = mock.Mock(return_value=(width, 24)) + mock_shutil = mock.Mock(get_terminal_size=mock_get_terminal_size) + + with mock.patch("wily.helper.shutil", mock_shutil): + result = get_maxcolwidth(LONG_DATA[0], True) + as_table = tabulate.tabulate( + tabular_data=LONG_DATA, + tablefmt="grid", + maxcolwidths=result, + maxheadercolwidths=result, + ) + + line = as_table.splitlines()[0] + assert len(line) < width + if width < 290: + assert len(line) >= width / 3 + + +def test_get_maxcolwidth_wrap_huge(): + for width in range(75, 450): + mock_get_terminal_size = mock.Mock(return_value=(width, 24)) + mock_shutil = mock.Mock(get_terminal_size=mock_get_terminal_size) + + with mock.patch("wily.helper.shutil", mock_shutil): + result = get_maxcolwidth(HUGE_DATA[0], True) + as_table = tabulate.tabulate( + tabular_data=HUGE_DATA, + tablefmt="grid", + maxcolwidths=result, + maxheadercolwidths=result, + ) + + line = as_table.splitlines()[0] + assert len(line) < width + if width < 220: + assert len(line) >= width / 3 + else: + assert len(line) >= width / 4 def test_get_style():
running wily with more than 5 metrics cause problem with printing when running willy with multiple metrics it causes them to overlap
0.0
b0411ae861b8adc39422328abc6b159e64381715
[ "test/integration/test_diff.py::test_diff_no_cache", "test/integration/test_diff.py::test_diff_no_path", "test/integration/test_diff.py::test_diff_output", "test/integration/test_diff.py::test_diff_output_all", "test/integration/test_diff.py::test_diff_output_all_wrapped", "test/integration/test_diff.py::test_diff_output_bad_path", "test/integration/test_diff.py::test_diff_output_remove_all", "test/integration/test_diff.py::test_diff_output_more_complex", "test/integration/test_diff.py::test_diff_output_less_complex", "test/integration/test_diff.py::test_diff_output_loc", "test/integration/test_diff.py::test_diff_output_loc_and_revision", "test/integration/test_diff.py::test_diff_output_rank", "test/integration/test_index.py::test_index_no_cache", "test/integration/test_index.py::test_index", "test/integration/test_index.py::test_index_with_messages", "test/integration/test_index.py::test_index_with_messages_wrapped", "test/integration/test_list_metrics.py::test_list_metrics", "test/integration/test_list_metrics.py::test_list_metrics_wrapped", "test/integration/test_rank.py::test_rank_no_cache", "test/integration/test_rank.py::test_rank_single_file_default_metric", "test/integration/test_rank.py::test_rank_single_file_default_metric_wrapped", "test/integration/test_rank.py::test_rank_directory_default_metric", "test/integration/test_rank.py::test_rank_directory_default_metric_no_path", "test/integration/test_rank.py::test_rank_directory_default_metric_master", "test/integration/test_rank.py::test_rank_directory_default_invalid_revision", "test/integration/test_rank.py::test_rank_directory_default_unindexed_revision", "test/integration/test_rank.py::test_rank_single_file_informational", "test/integration/test_rank.py::test_rank_directory_custom_metric", "test/integration/test_rank.py::test_rank_directory_no_path_target", "test/integration/test_rank.py::test_rank_directory_limit", "test/integration/test_rank.py::test_rank_directory_desc", "test/integration/test_rank.py::test_rank_directory_invalid_key", "test/integration/test_rank.py::test_rank_directory_asc", "test/integration/test_rank.py::test_rank_total_above_threshold", "test/integration/test_rank.py::test_rank_total_below_threshold", "test/integration/test_report.py::test_report_no_cache", "test/integration/test_report.py::test_report", "test/integration/test_report.py::test_report_granular", "test/integration/test_report.py::test_report_not_found", "test/integration/test_report.py::test_report_default_metrics", "test/integration/test_report.py::test_report_path", "test/integration/test_report.py::test_report_with_message", "test/integration/test_report.py::test_report_with_message_and_n", "test/integration/test_report.py::test_report_changes_only", "test/integration/test_report.py::test_report_high_metric", "test/integration/test_report.py::test_report_wrapped", "test/integration/test_report.py::test_report_short_metric", "test/integration/test_report.py::test_report_low_metric", "test/integration/test_report.py::test_report_html_format", "test/integration/test_report.py::test_report_html_format_target_folder", "test/integration/test_report.py::test_report_html_format_target_file", "test/integration/test_report.py::test_report_console_format", "test/integration/test_report.py::test_report_not_existing_format", "test/unit/test_helper.py::test_get_maxcolwidth_no_wrap", "test/unit/test_helper.py::test_get_maxcolwidth_wrap_short", "test/unit/test_helper.py::test_get_maxcolwidth_wrap_medium", "test/unit/test_helper.py::test_get_maxcolwidth_wrap_long_line_medium", "test/unit/test_helper.py::test_get_maxcolwidth_wrap_long", "test/unit/test_helper.py::test_get_maxcolwidth_wrap_huge", "test/unit/test_helper.py::test_get_style", "test/unit/test_helper.py::test_get_style_charmap", "test/unit/test_helper.py::test_get_style_charmap_not_default_grid_style" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-16 15:15:03+00:00
apache-2.0
6,053
tonybaloney__wily-209
diff --git a/docs/source/commands/graph.rst b/docs/source/commands/graph.rst index a0cc9dd..70bdbfb 100644 --- a/docs/source/commands/graph.rst +++ b/docs/source/commands/graph.rst @@ -6,11 +6,11 @@ The graph command generates HTML graphs for metrics, trends and data in the wily Examples -------- -``wily graph`` will take 1 or 2 metrics as the 2nd and 3rd arguments. The first metric will be the Y-axis and the 3rd metric (if provided) will control the size of the bubble. +``wily graph`` will take 1 or 2 comma-separated metrics as the -m option. The first metric will be the Y-axis and the 2nd metric (if provided) will control the size of the bubble. .. code-block:: none - $ wily graph example.py loc + $ wily graph example.py -m loc .. image:: ../_static/single_metric_graph.png :align: center @@ -19,7 +19,7 @@ You can provide a second metric which will be used to control the size of the bu .. code-block:: none - $ wily graph example.py loc complexity + $ wily graph example.py loc,complexity .. image:: ../_static/two_metric_graph.png :align: center @@ -28,7 +28,7 @@ The x-axis will be the historic revisions (typically git commits) on a scale of .. code-block:: none - $ wily graph example.py loc complexity --x-axis sloc + $ wily graph example.py -m loc,complexity --x-axis sloc .. image:: ../_static/custom_x_axis_graph.png :align: center @@ -56,7 +56,15 @@ To save the output to a specific HTML file and not open it, provide the ``-o`` f .. code-block:: none - $ wily report example.py loc -o example.html + $ wily report example.py -m loc -o example.html + +By default, ``wily graph`` will create an HTML file containing all the JS necessary to render the graph. +To create a standalone plotly.min.js file in the same directory as the HTML file instead, pass the ``--shared-js`´ option. +To point the HTML file to a CDN hosted plotly.min.js instead, pass the ``--cdn-js`´ option. + +.. code-block:: none + + $ wily report example.py -m loc --shared=js Command Line Usage diff --git a/src/wily/__main__.py b/src/wily/__main__.py index 1c3b0cc..4489ae5 100644 --- a/src/wily/__main__.py +++ b/src/wily/__main__.py @@ -397,6 +397,10 @@ def diff(ctx, files, metrics, all, detail, revision, wrap): Graph test.py against raw.loc and raw.sloc on the x-axis $ wily graph src/test.py -m raw.loc --x-axis raw.sloc + + Graph test.py against raw.loc creating a standalone plotly.min.js file + + $ wily graph src/test.py -m raw.loc --shared-js """ ) ) @@ -422,14 +426,34 @@ def diff(ctx, files, metrics, all, detail, revision, wrap): default=False, help=_("Aggregate if path is directory"), ) [email protected]( + "--shared-js/--no-shared-js", + default=False, + type=click.BOOL, + help=_("Create standalone plotly.min.js in the graph directory."), +) [email protected]( + "--cdn-js/--no-cdn-js", + default=False, + type=click.BOOL, + help=_("Point to a CDN hosted plotly.min.js."), +) @click.pass_context -def graph(ctx, path, metrics, output, x_axis, changes, aggregate): +def graph(ctx, path, metrics, output, x_axis, changes, aggregate, shared_js, cdn_js): """Output report to specified HTML path, e.g. reports/out.html.""" config = ctx.obj["CONFIG"] if not exists(config): handle_no_cache(ctx) + # Embed plotly.min.js in the HTML file by default + plotlyjs = True + if shared_js: + plotlyjs = "directory" + # CDN takes precedence over directory + if cdn_js: + plotlyjs = "cdn" + from wily.commands.graph import graph logger.debug("Running report on %s for metrics %s", path, metrics) @@ -441,6 +465,7 @@ def graph(ctx, path, metrics, output, x_axis, changes, aggregate): x_axis=x_axis, changes=changes, aggregate=aggregate, + plotlyjs=plotlyjs, ) diff --git a/src/wily/commands/graph.py b/src/wily/commands/graph.py index 43bbdbd..b4dc99d 100644 --- a/src/wily/commands/graph.py +++ b/src/wily/commands/graph.py @@ -5,7 +5,7 @@ Draw graph in HTML for a specific metric. """ from pathlib import Path -from typing import Optional, Tuple +from typing import Optional, Tuple, Union import plotly.graph_objs as go import plotly.offline @@ -38,6 +38,7 @@ def graph( changes: bool = True, text: bool = False, aggregate: bool = False, + plotlyjs: Union[bool, str] = True, ) -> None: """ Graph information about the cache and runtime. @@ -50,6 +51,7 @@ def graph( :param changes: Only graph changes. :param text: Show commit message inline in graph. :param aggregate: Aggregate values for graph. + :param plotlyjs: How to include plotly.min.js. """ logger.debug("Running graph command") @@ -169,4 +171,5 @@ def graph( }, auto_open=auto_open, filename=filename, + include_plotlyjs=plotlyjs, # type: ignore )
tonybaloney/wily
ec495118115ca36706fc3f4e6a56842559fb1da1
diff --git a/test/integration/test_graph.py b/test/integration/test_graph.py index 7596f1b..78b576a 100644 --- a/test/integration/test_graph.py +++ b/test/integration/test_graph.py @@ -45,6 +45,36 @@ def test_graph(builddir): assert result.exit_code == 0, result.stdout +def test_graph_shared_js(builddir): + """Test the graph feature with --shared-js option""" + runner = CliRunner() + with patch.dict("os.environ", values=PATCHED_ENV, clear=True): + result = runner.invoke( + main.cli, + [ + "--path", + builddir, + "graph", + _path, + "-m", + "raw.loc", + "--shared-js", + ], + ) + assert result.exit_code == 0, result.stdout + + +def test_graph_plotlyjs_cdn_js(builddir): + """Test the graph feature with --cdn_js option""" + runner = CliRunner() + with patch.dict("os.environ", values=PATCHED_ENV, clear=True): + result = runner.invoke( + main.cli, + ["--path", builddir, "graph", _path, "-m", "raw.loc", " --cdn_js"], + ) + assert result.exit_code == 0, result.stdout + + def test_graph_all(builddir): """Test the graph feature""" runner = CliRunner()
Allow standalone plotly.min.js when creating graphs When creating graphs, wily currently inlines the contents of `plotly.min.js` in HTML files, making their size around 3.4MB each. When [creating a lot of graphs](https://gist.github.com/devdanzin/513dfb256686a5d33f727f8247a87184), this quickly adds up to a lot of space. For example, bulk creating graphs for every metric for every file that ever existed in wily's repository takes around 5GB in about 1500 HTML files. Plotly has an option to create `plotly.min.js` once, in the same directory, and reference it from the HTML file. It's enabled by calling `plotly.offline.plot` with `include_plotlyjs="directory"`. It reduces the size of the same 1500 graphs from 5GB to under 100MB. I'm not sure adding this feature would be in scope for wily, but I have it working locally and could contribute a PR if it's desirable. It would also add a new CLI option for graph to enable this behavior.
0.0
ec495118115ca36706fc3f4e6a56842559fb1da1
[ "test/integration/test_graph.py::test_graph_shared_js" ]
[ "test/integration/test_graph.py::test_graph_no_cache", "test/integration/test_graph.py::test_graph_no_path", "test/integration/test_graph.py::test_graph", "test/integration/test_graph.py::test_graph_plotlyjs_cdn_js", "test/integration/test_graph.py::test_graph_all", "test/integration/test_graph.py::test_graph_all_with_shorthand_metric", "test/integration/test_graph.py::test_graph_changes", "test/integration/test_graph.py::test_graph_custom_x", "test/integration/test_graph.py::test_graph_aggregate", "test/integration/test_graph.py::test_graph_individual", "test/integration/test_graph.py::test_graph_path", "test/integration/test_graph.py::test_graph_multiple", "test/integration/test_graph.py::test_graph_multiple_custom_x", "test/integration/test_graph.py::test_graph_multiple_path", "test/integration/test_graph.py::test_graph_output", "test/integration/test_graph.py::test_graph_output_granular", "test/integration/test_graph.py::test_graph_multiple_paths" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-08-16 20:01:44+00:00
apache-2.0
6,054
tophat__syrupy-607
diff --git a/src/syrupy/location.py b/src/syrupy/location.py index 31207e7..ca4aa26 100644 --- a/src/syrupy/location.py +++ b/src/syrupy/location.py @@ -114,4 +114,7 @@ class PyTestLocation: return self.__parse(self.snapshot_name) == self.__parse(snapshot_name) def matches_snapshot_location(self, snapshot_location: str) -> bool: - return self.filename in snapshot_location + loc = Path(snapshot_location) + # "test_file" should match_"test_file.ext" or "test_file/whatever.ext", but not + # "test_file_suffix.ext" + return self.filename == loc.stem or self.filename == loc.parent.name
tophat/syrupy
a472b447c15e4200693a6f6011a6ac07d6f8caa5
diff --git a/tests/integration/test_snapshot_similar_names_default.py b/tests/integration/test_snapshot_similar_names_default.py index abc06a6..5ba1e18 100644 --- a/tests/integration/test_snapshot_similar_names_default.py +++ b/tests/integration/test_snapshot_similar_names_default.py @@ -16,29 +16,37 @@ def testcases(): assert snapshot == 'b' """ ), + "a_suffix": ( + """ + def test_a_suffix(snapshot): + assert snapshot == 'a_suffix' + """ + ), } @pytest.fixture def run_testcases(testdir, testcases): pyfile_content = "\n\n".join(testcases.values()) - testdir.makepyfile(test_1=pyfile_content, test_2=pyfile_content) + testdir.makepyfile( + test_1=pyfile_content, test_2=pyfile_content, test_1_with_suffix=pyfile_content + ) result = testdir.runpytest("-v", "--snapshot-update") - result.stdout.re_match_lines((r"4 snapshots generated\.")) + result.stdout.re_match_lines((r"9 snapshots generated\.")) return testdir, testcases def test_run_all(run_testcases): testdir, testcases = run_testcases result = testdir.runpytest("-v") - result.stdout.re_match_lines("4 snapshots passed") + result.stdout.re_match_lines("9 snapshots passed") assert result.ret == 0 def test_run_single_file(run_testcases): testdir, testcases = run_testcases result = testdir.runpytest("-v", "test_1.py") - result.stdout.re_match_lines("2 snapshots passed") + result.stdout.re_match_lines("3 snapshots passed") assert result.ret == 0 @@ -54,7 +62,7 @@ def test_run_all_but_one(run_testcases): result = testdir.runpytest( "-v", "--snapshot-details", "test_1.py", "test_2.py::test_a" ) - result.stdout.re_match_lines("3 snapshots passed") + result.stdout.re_match_lines("4 snapshots passed") assert result.ret == 0 diff --git a/tests/integration/test_snapshot_similar_names_file_extension.py b/tests/integration/test_snapshot_similar_names_file_extension.py index 19d1131..458d407 100644 --- a/tests/integration/test_snapshot_similar_names_file_extension.py +++ b/tests/integration/test_snapshot_similar_names_file_extension.py @@ -16,20 +16,28 @@ def testcases(): assert snapshot == b"b" """ ), + "a_suffix": ( + """ + def test_a_suffix(snapshot): + assert snapshot == b"a_suffix" + """ + ), } @pytest.fixture def run_testcases(testdir, testcases): pyfile_content = "\n\n".join(testcases.values()) - testdir.makepyfile(test_1=pyfile_content, test_2=pyfile_content) + testdir.makepyfile( + test_1=pyfile_content, test_2=pyfile_content, test_1_suffix=pyfile_content + ) result = testdir.runpytest( "-v", "--snapshot-update", "--snapshot-default-extension", "syrupy.extensions.single_file.SingleFileSnapshotExtension", ) - result.stdout.re_match_lines((r"4 snapshots generated\.")) + result.stdout.re_match_lines((r"9 snapshots generated\.")) return testdir, testcases @@ -40,7 +48,7 @@ def test_run_all(run_testcases): "--snapshot-default-extension", "syrupy.extensions.single_file.SingleFileSnapshotExtension", ) - result.stdout.re_match_lines("4 snapshots passed") + result.stdout.re_match_lines("9 snapshots passed") assert result.ret == 0 @@ -52,7 +60,7 @@ def test_run_single_file(run_testcases): "syrupy.extensions.single_file.SingleFileSnapshotExtension", "test_1.py", ) - result.stdout.re_match_lines("2 snapshots passed") + result.stdout.re_match_lines("3 snapshots passed") assert result.ret == 0 @@ -78,7 +86,7 @@ def test_run_all_but_one(run_testcases): "test_1.py", "test_2.py::test_a", ) - result.stdout.re_match_lines("3 snapshots passed") + result.stdout.re_match_lines("4 snapshots passed") assert result.ret == 0 diff --git a/tests/syrupy/test_location.py b/tests/syrupy/test_location.py index 7162559..6da7f9a 100644 --- a/tests/syrupy/test_location.py +++ b/tests/syrupy/test_location.py @@ -67,7 +67,15 @@ def test_location_properties( "/tests/module/test_file.py::TestClass::method_name", "method_name", ("test_file.snap", "__snapshots__/test_file", "test_file/1.snap"), - ("test.snap", "__others__/test/file.snap"), + ( + "test.snap", + "__others__/test/file.snap", + "test_file_extra.snap", + "__snapshots__/test_file_extra", + "test_file_extra/1.snap", + "test_file/extra/1.snap", + "__snapshots__/test_file/extra/even/more/1.snap", + ), ( "TestClass.method_name", "TestClass.method_name[1]", @@ -79,7 +87,15 @@ def test_location_properties( "/tests/module/test_file.py::TestClass::method_name[1]", "method_name", ("test_file.snap", "__snapshots__/test_file", "test_file/1.snap"), - ("test.snap", "__others__/test/file.snap"), + ( + "test.snap", + "__others__/test/file.snap", + "test_file_extra.snap", + "__snapshots__/test_file_extra", + "test_file_extra/1.snap", + "test_file/extra/1.snap", + "__snapshots__/test_file/extra/even/more/1.snap", + ), ( "TestClass.method_name", "TestClass.method_name[1]",
Unused snapshots when running on filename (test_a.py) that's the prefix of another (test_abc.py) **Describe the bug** I have a project that has filenames where the non-`.py` part happens to be a prefix of another (e.g. `test_a.py` vs. `test_abc.py`). When running `test_a.py` in isolation, syrupy picks up the snapshots from `test_abc.py` and either warns/errors about them or deletes them (depending on if `--snapshot-update`) is specified. (Thanks for syrupy!) **To reproduce** ```python # test_a.py def test_foo(snapshot): assert snapshot == "a" ``` ```python # test_abc.py def test_bar(snapshot): assert snapshot == "abc" ``` ``` # requirements.txt attrs==21.4.0 colored==1.4.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.0.8 pytest==7.1.1 syrupy==1.7.4 tomli==2.0.1 ``` With the above code, if I run `pytest test_a.py`, the snapshot from `test_abc.py` is flagged as unused: ``` ================================= test session starts ================================= platform darwin -- Python 3.9.10, pytest-7.1.1, pluggy-1.0.0 rootdir: .../syrupy-file-prefix plugins: syrupy-1.7.4 collected 1 item test_a.py . [100%] ------------------------------- snapshot report summary ------------------------------- 1 snapshot passed. 1 snapshot unused. Unused test_bar (__snapshots__/test_abc.ambr) Re-run pytest with --snapshot-update to delete unused snapshots. ================================== 1 passed in 0.01s ================================== ``` Fully packaged: ```shell # set up virtualenv/deps/files python --version # Python 3.9.10 python -m venv venv . venv/bin/activate pip install attrs==21.4.0 colored==1.4.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.0.8 pytest==7.1.1 syrupy==1.7.4 tomli==2.0.1 echo 'def test_foo(snapshot): assert snapshot == "a"' > test_a.py echo 'def test_bar(snapshot): assert snapshot == "abc"' > test_abc.py # create snapshots pytest --snapshot-update # 2 snapshots generated. pytest # 2 snapshots passed. # running test_abc.py: all okay pytest test_abc.py --snapshot-details # 1 snapshot passed. # running test_a.py: unused snapshots (BUG) pytest test_a.py --snapshot-details # Unused test_bar (__snapshots__/test_abc.ambr) pytest test_a.py --snapshot-details --snapshot-update # Deleted test_bar (__snapshots__/test_abc.ambr) ``` **Expected behavior** When running pytest against a single/subset of files, snapshots from other files shouldn't be considered unused. **Screenshots** <!-- If applicable, add screenshots to help explain your problem. --> **Environment (please complete the following information):** - OS: macOS 12.3 - Syrupy Version: 1.7.4 - Python Version: 3.9.10 **Additional context** N/A
0.0
a472b447c15e4200693a6f6011a6ac07d6f8caa5
[ "tests/integration/test_snapshot_similar_names_default.py::test_run_single_file", "tests/integration/test_snapshot_similar_names_default.py::test_run_all_but_one", "tests/integration/test_snapshot_similar_names_default.py::test_run_both_files_by_node", "tests/integration/test_snapshot_similar_names_default.py::test_run_both_files_by_node_2", "tests/syrupy/test_location.py::test_location_matching[/tests/module/test_file.py::TestClass::method_name-method_name-expected_location_matches0-expected_location_misses0-expected_snapshot_matches0-expected_snapshot_misses0]", "tests/syrupy/test_location.py::test_location_matching[/tests/module/test_file.py::TestClass::method_name[1]-method_name-expected_location_matches1-expected_location_misses1-expected_snapshot_matches1-expected_snapshot_misses1]" ]
[ "tests/integration/test_snapshot_similar_names_default.py::test_run_all", "tests/integration/test_snapshot_similar_names_default.py::test_run_single_test_case_in_file", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_all", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_single_file", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_single_test_case_in_file", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_all_but_one", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_both_files_by_node", "tests/integration/test_snapshot_similar_names_file_extension.py::test_run_both_files_by_node_2", "tests/syrupy/test_location.py::test_location_properties[/tests/module/test_file.py::TestClass::method_name-method_name-test_file-TestClass-TestClass.method_name]", "tests/syrupy/test_location.py::test_location_properties[/tests/module/test_file.py::TestClass::method_name[1]-method_name-test_file-TestClass-TestClass.method_name[1]]", "tests/syrupy/test_location.py::test_location_properties[/tests/module/nest/test_file.py::TestClass::TestSubClass::method_name-method_name-test_file-TestClass.TestSubClass-TestClass.TestSubClass.method_name]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-07-05 04:43:18+00:00
apache-2.0
6,055
tophat__syrupy-621
diff --git a/src/syrupy/report.py b/src/syrupy/report.py index e642450..09b3991 100644 --- a/src/syrupy/report.py +++ b/src/syrupy/report.py @@ -299,7 +299,14 @@ class SnapshotReport: for snapshot_fossil in self.unused: filepath = snapshot_fossil.location snapshots = (snapshot.name for snapshot in snapshot_fossil) - path_to_file = str(Path(filepath).relative_to(self.base_dir)) + + try: + path_to_file = str(Path(filepath).relative_to(self.base_dir)) + except ValueError: + # this is just used for display, so better to fallback to + # something vaguely reasonable (the full path) than give up + path_to_file = filepath + unused_snapshots = ", ".join(map(bold, sorted(snapshots))) yield warning_style(gettext(base_message)) + " {} ({})".format( unused_snapshots, path_to_file
tophat/syrupy
f49678136d89efd1e8b929487e0a360720f4fc6b
diff --git a/tests/integration/test_snapshot_outside_directory.py b/tests/integration/test_snapshot_outside_directory.py new file mode 100644 index 0000000..b241c6f --- /dev/null +++ b/tests/integration/test_snapshot_outside_directory.py @@ -0,0 +1,81 @@ +import pytest + + [email protected] +def testcases(testdir, tmp_path): + dirname = tmp_path.joinpath("__snapshots__") + testdir.makeconftest( + f""" + import pytest + + from syrupy.extensions.amber import AmberSnapshotExtension + + class CustomSnapshotExtension(AmberSnapshotExtension): + @property + def _dirname(self): + return {str(dirname)!r} + + @pytest.fixture + def snapshot(snapshot): + return snapshot.use_extension(CustomSnapshotExtension) + """ + ) + return { + "zero": ( + """ + def test_do_it(snapshot): + pass + """ + ), + "one": ( + """ + def test_do_it(snapshot): + assert snapshot == 'passed1' + """ + ), + "two": ( + """ + def test_do_it(snapshot): + assert snapshot == 'passed1' + assert snapshot == 'passed2' + """ + ), + } + + [email protected] +def generate_snapshots(testdir, testcases): + testdir.makepyfile(test_file=testcases["two"]) + result = testdir.runpytest("-v", "--snapshot-update") + return result, testdir, testcases + + +def test_generated_snapshots(generate_snapshots): + result = generate_snapshots[0] + result.stdout.re_match_lines((r"2 snapshots generated\.")) + assert "snapshots unused" not in result.stdout.str() + assert result.ret == 0 + + +def test_unmatched_snapshots(generate_snapshots): + _, testdir, testcases = generate_snapshots + testdir.makepyfile(test_file=testcases["one"]) + result = testdir.runpytest("-v") + result.stdout.re_match_lines((r"1 snapshot passed. 1 snapshot unused\.")) + assert result.ret == 1 + + +def test_updated_snapshots_partial_delete(generate_snapshots): + _, testdir, testcases = generate_snapshots + testdir.makepyfile(test_file=testcases["one"]) + result = testdir.runpytest("-v", "--snapshot-update") + result.stdout.re_match_lines(r"1 snapshot passed. 1 unused snapshot deleted\.") + assert result.ret == 0 + + +def test_updated_snapshots_full_delete(generate_snapshots): + _, testdir, testcases = generate_snapshots + testdir.makepyfile(test_file=testcases["zero"]) + result = testdir.runpytest("-v", "--snapshot-update") + result.stdout.re_match_lines(r"2 unused snapshots deleted\.") + assert result.ret == 0
Custom extension with _dirname outside the pytest session directory results in crash during (detailed) reporting **Describe the bug** Currently a custom extension can write snapshots to a new directory by overriding the `_dirname` property, however, this directory has to be a child of pytest's root directory, or else syrupy's reporting crashes with an error like: ``` ValueError: '/tmp/example/__snapshots__/test_file.ambr' is not in the subpath of '/.../path/to/tests' OR one path is relative and the other is absolute. ``` (This is a very niche bug, sorry. Doing this directory hacking is designed to allow building a work-around for https://github.com/pantsbuild/pants/issues/11622.) **To reproduce** ```python import pytest from syrupy.extensions.amber import AmberSnapshotExtension class CustomSnapshotExtension(AmberSnapshotExtension): @property def _dirname(self): return '/tmp/example/__snapshots__' @pytest.fixture def snapshot(snapshot): return snapshot.use_extension(CustomSnapshotExtension) def test_do_it(snapshot): assert "one" == snapshot assert "two" == snapshot ``` 1. run the tests above with `--snapshot-update` 2. comment out the `"two"` line 3. run the tests again with `--snapshot-update` or `--snapshot-details` Output: ``` $ pytest test_file.py --snapshot-details ======================================================================================================================================================= test session starts ======================================================================================================================================================== platform darwin -- Python 3.10.4, pytest-7.1.3, pluggy-1.0.0 rootdir: /Users/huon/projects/tophat/syrupy, configfile: pyproject.toml plugins: syrupy-1.7.3 collected 1 item test_file.py . [100%] ----------------------------------------------------------------------------------------------------------------------------------------------------- snapshot report summary ------------------------------------------------------------------------------------------------------------------------------------------------------ 1 snapshot passed. 1 snapshot unused. Traceback (most recent call last): File "/Users/huon/projects/tophat/syrupy/test/bin/pytest", line 8, in <module> sys.exit(console_main()) ... File "/Users/huon/projects/tophat/syrupy/src/syrupy/report.py", line 304, in lines path_to_file = str(Path(filepath).relative_to(self.base_dir)) File "/Users/huon/.pyenv/versions/3.10.4/lib/python3.10/pathlib.py", line 816, in relative_to raise ValueError("{!r} is not in the subpath of {!r}" ``` **Expected behavior** Syrupy should behave as normal even with a 'weird' snapshot directory like this. **Screenshots** <!-- If applicable, add screenshots to help explain your problem. --> **Environment (please complete the following information):** - OS: macOS - Syrupy Version: 3.0.0 - Python Version: 3.10.4 **Additional context** Thanks for Syrupy!
0.0
f49678136d89efd1e8b929487e0a360720f4fc6b
[ "tests/integration/test_snapshot_outside_directory.py::test_updated_snapshots_partial_delete", "tests/integration/test_snapshot_outside_directory.py::test_updated_snapshots_full_delete" ]
[ "tests/integration/test_snapshot_outside_directory.py::test_generated_snapshots", "tests/integration/test_snapshot_outside_directory.py::test_unmatched_snapshots" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-09-20 05:47:02+00:00
apache-2.0
6,056
tophat__syrupy-634
diff --git a/src/syrupy/terminal.py b/src/syrupy/terminal.py index dec1532..f59d696 100644 --- a/src/syrupy/terminal.py +++ b/src/syrupy/terminal.py @@ -13,6 +13,24 @@ def _is_color_disabled() -> bool: return any(map(get_env_value, DISABLE_COLOR_ENV_VARS)) +def _attr(color: Any) -> str: + if _is_color_disabled(): + return "" + return colored.attr(color) + + +def _fg(color: Any) -> str: + if _is_color_disabled(): + return "" + return colored.fg(color) + + +def _bg(color: Any) -> str: + if _is_color_disabled(): + return "" + return colored.bg(color) + + def _stylize(text: Union[str, int], *args: Any) -> str: if _is_color_disabled(): return str(text) @@ -20,23 +38,23 @@ def _stylize(text: Union[str, int], *args: Any) -> str: def reset(text: Union[str, int]) -> str: - return _stylize(text, colored.attr("reset")) + return _stylize(text, _attr("reset")) def red(text: Union[str, int]) -> str: - return _stylize(text, colored.fg("red")) + return _stylize(text, _fg("red")) def yellow(text: Union[str, int]) -> str: - return _stylize(text, colored.fg("yellow")) + return _stylize(text, _fg("yellow")) def green(text: Union[str, int]) -> str: - return _stylize(text, colored.fg("green")) + return _stylize(text, _fg("green")) def bold(text: Union[str, int]) -> str: - return _stylize(text, colored.attr("bold")) + return _stylize(text, _attr("bold")) def error_style(text: Union[str, int]) -> str: @@ -52,20 +70,20 @@ def success_style(text: Union[str, int]) -> str: def snapshot_style(text: Union[str, int]) -> str: - return _stylize(text, colored.bg(225) + colored.fg(90)) + return _stylize(text, _bg(225) + _fg(90)) def snapshot_diff_style(text: Union[str, int]) -> str: - return _stylize(text, colored.bg(90) + colored.fg(225)) + return _stylize(text, _bg(90) + _fg(225)) def received_style(text: Union[str, int]) -> str: - return _stylize(text, colored.bg(195) + colored.fg(23)) + return _stylize(text, _bg(195) + _fg(23)) def received_diff_style(text: Union[str, int]) -> str: - return _stylize(text, colored.bg(23) + colored.fg(195)) + return _stylize(text, _bg(23) + _fg(195)) def context_style(text: Union[str, int]) -> str: - return _stylize(text, colored.attr("dim")) + return _stylize(text, _attr("dim"))
tophat/syrupy
dccc789522b96d6dc0a1608828e71b96fee8c215
diff --git a/tests/syrupy/test_terminal.py b/tests/syrupy/test_terminal.py new file mode 100644 index 0000000..cf9df9f --- /dev/null +++ b/tests/syrupy/test_terminal.py @@ -0,0 +1,58 @@ +from unittest.mock import ( + NonCallableMock, + patch, +) + +import pytest + +from syrupy.constants import DISABLE_COLOR_ENV_VAR +from syrupy.terminal import ( + bold, + context_style, + error_style, + green, + received_diff_style, + received_style, + red, + reset, + snapshot_diff_style, + snapshot_style, + success_style, + warning_style, + yellow, +) + + +def test_colors_off_does_not_call_colored(): + """ + Test that disabling colors prevents instantiating colored object. + Enables workarounds for when instantiating the colored object causes crashes, + see issue #633 + """ + + with patch( + "syrupy.terminal.colored.colored.__init__", new_callable=NonCallableMock + ): + with patch.dict("os.environ", {DISABLE_COLOR_ENV_VAR: "true"}): + for method in ( + reset, + red, + yellow, + green, + bold, + error_style, + warning_style, + success_style, + snapshot_style, + snapshot_diff_style, + received_style, + received_diff_style, + context_style, + ): + _ = method("foo") + + # Prevent test from accidentally passing by patching wrong object + with pytest.raises(TypeError) as excinfo: + _ = red("foo") + + assert "NonCallableMock" in str(excinfo.value)
Report summary crashes on Windows 10 **Describe the bug** When printing a summary of snapshots, syrupy formats the text using `colored.fg`. This triggers a crash, as `colored.fg` uses incorrect types when interfacing with the kernel32 dll. An [issue](https://gitlab.com/dslackw/colored/-/issues/25) and corresponding [merge request](https://gitlab.com/dslackw/colored/-/merge_requests/19) has been created on colored's repository. Unfortunately, this can not be bypassed via `--snapshot-no-colors` or other environment variables, as the call to `colored.fg` occurs _before_ we check for those. **To reproduce** Run any snapshot test on (the above version of) Windows. Result: ``` -------------- snapshot report summary --------------- Traceback (most recent call last): File "...\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "...\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "...\Scripts\pytest.exe\__main__.py", line 7, in <module> File "...\lib\site-packages\_pytest\config\__init__.py", line 185, in console_main code = main() File "...\lib\site-packages\_pytest\config\__init__.py", line 162, in main ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main( File "...\lib\site-packages\pluggy\_hooks.py", line 265, in __call__ return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult) File "...\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) File "...\lib\site-packages\pluggy\_callers.py", line 60, in _multicall return outcome.get_result() File "...\lib\site-packages\pluggy\_result.py", line 60, in get_result raise ex[1].with_traceback(ex[2]) File "...\lib\site-packages\pluggy\_callers.py", line 39, in _multicall res = hook_impl.function(*args) File "...\lib\site-packages\_pytest\main.py", line 316, in pytest_cmdline_main return wrap_session(config, _main) File "...\lib\site-packages\_pytest\main.py", line 304, in wrap_session config.hook.pytest_sessionfinish( File "...\lib\site-packages\pluggy\_hooks.py", line 265, in __call__ return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult) File "...\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) File "...\lib\site-packages\pluggy\_callers.py", line 55, in _multicall gen.send(outcome) File "...\lib\site-packages\_pytest\terminal.py", line 813, in pytest_sessionfinish self.config.hook.pytest_terminal_summary( File "...\lib\site-packages\pluggy\_hooks.py", line 265, in __call__ return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult) File "...\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) File "...\lib\site-packages\pluggy\_callers.py", line 60, in _multicall return outcome.get_result() File "...\lib\site-packages\pluggy\_result.py", line 60, in get_result raise ex[1].with_traceback(ex[2]) File "...\lib\site-packages\pluggy\_callers.py", line 39, in _multicall res = hook_impl.function(*args) File "...\lib\site-packages\syrupy\__init__.py", line 170, in pytest_terminal_summary for line in terminalreporter.config._syrupy.report.lines: File "...\lib\site-packages\syrupy\report.py", line 277, in lines ).format(green(self.num_updated)) File "...\lib\site-packages\syrupy\terminal.py", line 34, in green return _stylize(text, colored.fg("green")) File "...\lib\site-packages\colored\colored.py", line 431, in fg return colored(color).foreground() File "...\lib\site-packages\colored\colored.py", line 23, in __init__ self.enable_windows_terminal_mode() File "...\lib\site-packages\colored\colored.py", line 374, in enable_windows_terminal_mode hStdout = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type ``` **Expected behavior** No crash **Environment (please complete the following information):** - OS: Windows 10 Enterprise 21H2 19044.2130 - Syrupy Version: 3.0.4 - Python Version: Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32 - (Colored Version: 1.4.3) **Additional context** It would be helpful if specifying `NO_COLOR` et al. would pre-empt calling `colored.fg` - that way, we would be able to bypass the issue without any nasty hacks. In lieu of that, the following nasty hack acts as a workaround: In the test module (or possibly conftest.py, haven't checked), add: ``` import colored colored.colored.enable_windows_terminal_mode = lambda self: None ``` Then run the tests as normal ( possibly with `--snapshot-no-colors`, although I didn't notice any difference).
0.0
dccc789522b96d6dc0a1608828e71b96fee8c215
[ "tests/syrupy/test_terminal.py::test_colors_off_does_not_call_colored" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-11-08 08:46:12+00:00
apache-2.0
6,057
tophat__syrupy-672
diff --git a/src/syrupy/extensions/json/__init__.py b/src/syrupy/extensions/json/__init__.py index 0b9a954..d35a1ef 100644 --- a/src/syrupy/extensions/json/__init__.py +++ b/src/syrupy/extensions/json/__init__.py @@ -64,7 +64,7 @@ class JSONSnapshotExtension(SingleFileSnapshotExtension): elif matcher: data = matcher(data=data, path=path) - if isinstance(data, (int, float, str)): + if isinstance(data, (int, float, str)) or data is None: return data filtered_dct: Dict[Any, Any]
tophat/syrupy
f9c6abaa30b5ffb3e9e5beaa9f74d73539ab6c1f
diff --git a/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_exclude_in_json_with_empty_values.json b/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_exclude_in_json_with_empty_values.json index 2e8f310..71d5f1e 100644 --- a/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_exclude_in_json_with_empty_values.json +++ b/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_exclude_in_json_with_empty_values.json @@ -1,5 +1,5 @@ { "empty_dict": {}, "empty_list": [], - "none": "None" + "none": null } diff --git a/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_serializer[content2].json b/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_serializer[content2].json index f518b00..990521b 100644 --- a/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_serializer[content2].json +++ b/tests/syrupy/extensions/json/__snapshots__/test_json_filters/test_serializer[content2].json @@ -7,6 +7,6 @@ "datetime": "2021-01-31T23:59:00.000000", "float": 4.2, "int": -1, - "null": "None", + "null": null, "str": "foo" } diff --git a/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_dict[actual2].json b/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_dict[actual2].json index 658b260..48e8cd1 100644 --- a/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_dict[actual2].json +++ b/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_dict[actual2].json @@ -1,4 +1,5 @@ { "a": "Some ttext.", + "key": null, "multi\nline\nkey": "Some morre text." } diff --git a/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_empty_snapshot.json b/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_empty_snapshot.json index 68cab94..19765bd 100644 --- a/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_empty_snapshot.json +++ b/tests/syrupy/extensions/json/__snapshots__/test_json_serializer/test_empty_snapshot.json @@ -1,1 +1,1 @@ -"None" +null diff --git a/tests/syrupy/extensions/json/test_json_serializer.py b/tests/syrupy/extensions/json/test_json_serializer.py index 7a6a2c1..9c1e359 100644 --- a/tests/syrupy/extensions/json/test_json_serializer.py +++ b/tests/syrupy/extensions/json/test_json_serializer.py @@ -124,6 +124,7 @@ def test_set(snapshot_json, actual): "multi\nline\nkey": "Some morre text.", frozenset({"1", "2"}): ["1", 2], ExampleTuple(a=1, b=2, c=3, d=4): {"e": False}, + "key": None, }, {}, {"key": ["line1\nline2"]},
JSONSnapshotExtension None is serialized as "None" instead of null Is it intended behaviour that `None` is not translated to `null` with the JSONSnapshotExtension? ```python @pytest.fixture def snapshot_json(snapshot): return snapshot.use_extension(JSONSnapshotExtension) def test_output(snapshot_json): assert {"x": None} == snapshot_json() ``` Actual Output: ```json { "x": "None" } ``` Expected Output: ```json { "x": null } ``` Digging into the code, it looks like there's no handling of None in _filter, and it eventually reaches `return repr(None)` line. I can wrap the existing class with the following code: ```python import pytest from syrupy.extensions.json import JSONSnapshotExtension @pytest.fixture def snapshot_json(snapshot): class CustomJSONExtension(JSONSnapshotExtension): @classmethod def _filter( cls, data, **kwargs ): if data is None: return data else: return super()._filter(data, **kwargs) return snapshot.use_extension(CustomJSONExtension) ``` Was wondering if there's a different way to get this behaviour?
0.0
f9c6abaa30b5ffb3e9e5beaa9f74d73539ab6c1f
[ "tests/syrupy/extensions/json/test_json_serializer.py::test_empty_snapshot", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual2]" ]
[ "tests/syrupy/extensions/json/test_json_serializer.py::test_non_snapshots", "tests/syrupy/extensions/json/test_json_serializer.py::test_reflection", "tests/syrupy/extensions/json/test_json_serializer.py::test_snapshot_markers", "tests/syrupy/extensions/json/test_json_serializer.py::test_newline_control_characters", "tests/syrupy/extensions/json/test_json_serializer.py::test_multiline_string_in_dict", "tests/syrupy/extensions/json/test_json_serializer.py::test_deeply_nested_multiline_string_in_dict", "tests/syrupy/extensions/json/test_json_serializer.py::test_bool[False]", "tests/syrupy/extensions/json/test_json_serializer.py::test_bool[True]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[0]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[1]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[2]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[3]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[4]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[5]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[6]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[7]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[8]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[9]", "tests/syrupy/extensions/json/test_json_serializer.py::test_string[10]", "tests/syrupy/extensions/json/test_json_serializer.py::test_multiple_snapshots", "tests/syrupy/extensions/json/test_json_serializer.py::test_tuple", "tests/syrupy/extensions/json/test_json_serializer.py::test_set[actual0]", "tests/syrupy/extensions/json/test_json_serializer.py::test_set[actual1]", "tests/syrupy/extensions/json/test_json_serializer.py::test_set[actual2]", "tests/syrupy/extensions/json/test_json_serializer.py::test_set[actual3]", "tests/syrupy/extensions/json/test_json_serializer.py::test_set[actual4]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual0]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual1]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual3]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual4]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual5]", "tests/syrupy/extensions/json/test_json_serializer.py::test_dict[actual6]", "tests/syrupy/extensions/json/test_json_serializer.py::test_numbers", "tests/syrupy/extensions/json/test_json_serializer.py::test_list[actual0]", "tests/syrupy/extensions/json/test_json_serializer.py::test_list[actual1]", "tests/syrupy/extensions/json/test_json_serializer.py::test_list[actual2]", "tests/syrupy/extensions/json/test_json_serializer.py::test_list[actual3]", "tests/syrupy/extensions/json/test_json_serializer.py::test_cycle[cyclic0]", "tests/syrupy/extensions/json/test_json_serializer.py::test_cycle[cyclic1]", "tests/syrupy/extensions/json/test_json_serializer.py::test_custom_object_repr", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::test_class_method_name", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::test_class_method_parametrized[a]", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::test_class_method_parametrized[b]", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::test_class_method_parametrized[c]", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::TestNestedClass::test_nested_class_method[x]", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::TestNestedClass::test_nested_class_method[y]", "tests/syrupy/extensions/json/test_json_serializer.py::TestClass::TestNestedClass::test_nested_class_method[z]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::test_class_method_name", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::test_class_method_parametrized[a]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::test_class_method_parametrized[b]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::test_class_method_parametrized[c]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::TestNestedClass::test_nested_class_method[x]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::TestNestedClass::test_nested_class_method[y]", "tests/syrupy/extensions/json/test_json_serializer.py::TestSubClass::TestNestedClass::test_nested_class_method[z]", "tests/syrupy/extensions/json/test_json_serializer.py::test_parameter_with_dot[value.with.dot]", "tests/syrupy/extensions/json/test_json_serializer.py::test_doubly_parametrized[bar-foo]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-12-30 18:35:59+00:00
apache-2.0
6,058
tophat__syrupy-710
diff --git a/src/syrupy/extensions/single_file.py b/src/syrupy/extensions/single_file.py index af53ea4..8e1a7c5 100644 --- a/src/syrupy/extensions/single_file.py +++ b/src/syrupy/extensions/single_file.py @@ -80,8 +80,11 @@ class SingleFileSnapshotExtension(AbstractSyrupyExtension): def _read_snapshot_collection( self, *, snapshot_location: str ) -> "SnapshotCollection": + file_ext_len = len(self._file_extension) + 1 if self._file_extension else 0 + filename_wo_ext = snapshot_location[:-file_ext_len] + snapshot_collection = SnapshotCollection(location=snapshot_location) - snapshot_collection.add(Snapshot(name=Path(snapshot_location).stem)) + snapshot_collection.add(Snapshot(name=Path(filename_wo_ext).stem)) return snapshot_collection def _read_snapshot_data_from_location(
tophat/syrupy
b831ee21b54f0b0dd287a7a0c6e138d6b553f26b
diff --git a/tests/integration/test_single_file_multiple_extensions.py b/tests/integration/test_single_file_multiple_extensions.py new file mode 100644 index 0000000..b93f287 --- /dev/null +++ b/tests/integration/test_single_file_multiple_extensions.py @@ -0,0 +1,40 @@ +from pathlib import Path + + +def test_multiple_file_extensions(testdir): + file_extension = "ext2.ext1" + + testcase = f""" + import pytest + from syrupy.extensions.single_file import SingleFileSnapshotExtension + + class DotInFileExtension(SingleFileSnapshotExtension): + _file_extension = "{file_extension}" + + @pytest.fixture + def snapshot(snapshot): + return snapshot.use_extension(DotInFileExtension) + + def test_dot_in_filename(snapshot): + assert b"expected_data" == snapshot + """ + + test_file: Path = testdir.makepyfile(test_file=testcase) + + result = testdir.runpytest("-v", "--snapshot-update") + result.stdout.re_match_lines((r"1 snapshot generated\.")) + assert "snapshots unused" not in result.stdout.str() + assert result.ret == 0 + + snapshot_file = ( + Path(test_file).parent + / "__snapshots__" + / "test_file" + / f"test_dot_in_filename.{file_extension}" + ) + assert snapshot_file.exists() + + result = testdir.runpytest("-v") + result.stdout.re_match_lines((r"1 snapshot passed\.")) + assert "snapshots unused" not in result.stdout.str() + assert result.ret == 0
having a dot in the file extension causes unexpected behavior **Describe the bug** Hello, Thanks for syrupy! We ran into a small issue when customizing the file extension. As mentioned in the title, I ran into an issue when trying to use an file extension like `png.zip`. I'm thinking, it's related to having and extra `.` in the file extension. ```console $ pytest tests/syrupy/extensions/image/test_dot_in_extension.py --snapshot-update =============================================================== test session starts ================================================================ platform darwin -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0 benchmark: 4.0.0 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000) rootdir: /Users/tolga.eren/work/syrupy, configfile: pyproject.toml plugins: syrupy-4.0.0, xdist-3.1.0, benchmark-4.0.0 collected 1 item tests/syrupy/extensions/image/test_dot_in_extension.py . [100%] ------------------------------------------------------------- snapshot report summary -------------------------------------------------------------- 1 snapshot passed. 1 unused snapshot deleted. Deleted test_dot_in_file_extension.png (tests/syrupy/extensions/image/__snapshots__/test_dot_in_extension/test_dot_in_file_extension.png.zip) ================================================================ 1 passed in 0.01s ================================================================= ``` The unexpected part is here: 1. Reporting says `1 snapshot passed. 1 unused snapshot deleted.`: There wasn't an unused snapshot and it wasn't deleted 2. If I run the `--snapshot--update` again, now it deletes the snapshot file, which it shoudn't. **To reproduce** I've modified one of the existing tests to reproduce: ```python # tests/syrupy/extensions/image/test_dot_in_extension.py import base64 import pytest from syrupy.extensions.single_file import SingleFileSnapshotExtension class DotInFileExtension(SingleFileSnapshotExtension): _file_extension = "png.zip" actual_png = base64.b64decode( b"iVBORw0KGgoAAAANSUhEUgAAADIAAAAyBAMAAADsEZWCAAAAG1BMVEXMzMy" b"Wlpaqqqq3t7exsbGcnJy+vr6jo6PFxcUFpPI/AAAACXBIWXMAAA7EAAAOxA" b"GVKw4bAAAAQUlEQVQ4jWNgGAWjgP6ASdncAEaiAhaGiACmFhCJLsMaIiDAE" b"QEi0WXYEiMCOCJAJIY9KuYGTC0gknpuHwXDGwAA5fsIZw0iYWYAAAAASUVO" b"RK5CYII=" ) @pytest.fixture def snapshot_dot_in_file_extension(snapshot): return snapshot.use_extension(DotInFileExtension) def test_dot_in_file_extension(snapshot_dot_in_file_extension): assert actual_png == snapshot_dot_in_file_extension ``` Run `pytest tests/syrupy/extensions/image/test_dot_in_extension.py --snapshot-update` twice to observe the unexpected behavior. **Expected behavior** 1. Correct reporting as in : `1 snapshot generated.` 2. and not deleting the generated snapshot in the second update run. **Environment (please complete the following information):** I've tested in the main branch
0.0
b831ee21b54f0b0dd287a7a0c6e138d6b553f26b
[ "tests/integration/test_single_file_multiple_extensions.py::test_multiple_file_extensions" ]
[]
{ "failed_lite_validators": [ "has_media" ], "has_test_patch": true, "is_lite": false }
2023-02-16 11:14:42+00:00
apache-2.0
6,059
tophat__syrupy-734
diff --git a/poetry.lock b/poetry.lock index 069852d..79bedb2 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1173,14 +1173,14 @@ jeepney = ">=0.6" [[package]] name = "semver" -version = "2.13.0" -description = "Python helper for Semantic Versioning (http://semver.org/)" +version = "3.0.0" +description = "Python helper for Semantic Versioning (https://semver.org)" category = "dev" optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +python-versions = ">=3.7" files = [ - {file = "semver-2.13.0-py2.py3-none-any.whl", hash = "sha256:ced8b23dceb22134307c1b8abfa523da14198793d9787ac838e70e29e77458d4"}, - {file = "semver-2.13.0.tar.gz", hash = "sha256:fa0fe2722ee1c3f57eac478820c3a5ae2f624af8264cbdf9000c980ff7f75e3f"}, + {file = "semver-3.0.0-py3-none-any.whl", hash = "sha256:ab4f69fb1d1ecfb5d81f96411403d7a611fa788c45d252cf5b408025df3ab6ce"}, + {file = "semver-3.0.0.tar.gz", hash = "sha256:94df43924c4521ec7d307fc86da1531db6c2c33d9d5cdc3e64cca0eb68569269"}, ] [[package]] @@ -1329,4 +1329,4 @@ testing = ["big-O", "flake8 (<5)", "jaraco.functools", "jaraco.itertools", "more [metadata] lock-version = "2.0" python-versions = '>=3.8.1,<4' -content-hash = "20ccfa73b2257c72d63a634b9381c9210f0c961511558b679caa42e3bd7558ee" +content-hash = "b1de5497b88df972689ae2b2a96f6cfc61d5270b5839b66a98cc12a261d9473d" diff --git a/pyproject.toml b/pyproject.toml index 1cc9512..8c9ded1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ flake8-bugbear = '^23.2.13' flake8-builtins = '^2.1.0' flake8-comprehensions = '^3.10.1' twine = '^4.0.2' -semver = '^2.13.0' +semver = '^3.0.0' setuptools-scm = '^7.1.0' debugpy = '^1.6.6' diff --git a/src/syrupy/__init__.py b/src/syrupy/__init__.py index 5f1a646..560ddb0 100644 --- a/src/syrupy/__init__.py +++ b/src/syrupy/__init__.py @@ -41,11 +41,6 @@ def __import_extension(value: Optional[str]) -> Any: raise argparse.ArgumentTypeError(e) -def __default_extension_option(value: Optional[str]) -> Any: - __import_extension(value) - return value - - def pytest_addoption(parser: Any) -> None: """ Exposes snapshot plugin configuration to pytest. @@ -78,7 +73,6 @@ def pytest_addoption(parser: Any) -> None: # all pytest options to be serializable. group.addoption( "--snapshot-default-extension", - type=__default_extension_option, default=None, dest="default_extension", help="Specify the default snapshot extension", diff --git a/src/syrupy/utils.py b/src/syrupy/utils.py index c086173..4dd08cd 100644 --- a/src/syrupy/utils.py +++ b/src/syrupy/utils.py @@ -48,11 +48,14 @@ def import_module_member(path: str) -> Any: ) ) try: - return getattr(import_module(module_name), module_member_name) + module = import_module(module_name) except ModuleNotFoundError: raise FailedToLoadModuleMember( gettext("Module '{}' does not exist.").format(module_name) ) + + try: + return getattr(module, module_member_name) except AttributeError: raise FailedToLoadModuleMember( gettext("Member '{}' not found in module '{}'.").format( diff --git a/tasks/build.py b/tasks/build.py index ef05530..e66f769 100644 --- a/tasks/build.py +++ b/tasks/build.py @@ -58,7 +58,7 @@ def release(ctx, dry_run=True, version=None): """ Build and publish package to pypi index based on scm version """ - from semver import parse_version_info + from semver.version import Version if not dry_run and not os.environ.get("CI"): print("This is a CI only command") @@ -72,7 +72,8 @@ def release(ctx, dry_run=True, version=None): exit(1) try: - should_publish_to_pypi = not dry_run and parse_version_info(version) + Version.parse(version) + should_publish_to_pypi = not dry_run except ValueError: should_publish_to_pypi = False
tophat/syrupy
028cb8f0c100f6be118d5aacf80974e7503980e2
diff --git a/tests/integration/test_snapshot_option_extension.py b/tests/integration/test_snapshot_option_extension.py index 546da3f..884f92a 100644 --- a/tests/integration/test_snapshot_option_extension.py +++ b/tests/integration/test_snapshot_option_extension.py @@ -37,12 +37,7 @@ def test_snapshot_default_extension_option_failure(testfile): "--snapshot-default-extension", "syrupy.extensions.amber.DoesNotExistExtension", ) - result.stderr.re_match_lines( - ( - r".*error: argument --snapshot-default-extension" - r": Member 'DoesNotExistExtension' not found.*", - ) - ) + result.stdout.re_match_lines((r".*: Member 'DoesNotExistExtension' not found.*",)) assert not Path( testfile.tmpdir, "__snapshots__", "test_file", "test_default.raw" ).exists() diff --git a/tests/integration/test_snapshot_option_extension_pythonpath.py b/tests/integration/test_snapshot_option_extension_pythonpath.py new file mode 100644 index 0000000..3570154 --- /dev/null +++ b/tests/integration/test_snapshot_option_extension_pythonpath.py @@ -0,0 +1,101 @@ +import textwrap +from pathlib import Path + +import pytest + +import syrupy + +SUBDIR = "subdir_not_on_default_path" + + [email protected](autouse=True) +def cache_clear(): + syrupy.__import_extension.cache_clear() + + [email protected] +def testfile(pytester): + subdir = pytester.mkpydir(SUBDIR) + + Path( + subdir, + "extension_file.py", + ).write_text( + data=textwrap.dedent( + """ + from syrupy.extensions.single_file import SingleFileSnapshotExtension + class MySingleFileExtension(SingleFileSnapshotExtension): + pass + """ + ), + encoding="utf-8", + ) + + pytester.makepyfile( + test_file=( + """ + def test_default(snapshot): + assert b"default extension serializer" == snapshot + """ + ) + ) + + return pytester + + +def test_snapshot_default_extension_option_success(testfile): + testfile.makeini( + f""" + [pytest] + pythonpath = + {Path(testfile.path, SUBDIR).as_posix()} + """ + ) + + result = testfile.runpytest( + "-v", + "--snapshot-update", + "--snapshot-default-extension", + "extension_file.MySingleFileExtension", + ) + result.stdout.re_match_lines((r"1 snapshot generated\.")) + assert Path( + testfile.path, "__snapshots__", "test_file", "test_default.raw" + ).exists() + assert not result.ret + + +def test_snapshot_default_extension_option_module_not_found(testfile): + result = testfile.runpytest( + "-v", + "--snapshot-update", + "--snapshot-default-extension", + "extension_file.MySingleFileExtension", + ) + result.stdout.re_match_lines((r".*: Module 'extension_file' does not exist.*",)) + assert not Path( + testfile.path, "__snapshots__", "test_file", "test_default.raw" + ).exists() + assert result.ret + + +def test_snapshot_default_extension_option_failure(testfile): + testfile.makeini( + f""" + [pytest] + pythonpath = + {Path(testfile.path, SUBDIR).as_posix()} + """ + ) + + result = testfile.runpytest( + "-v", + "--snapshot-update", + "--snapshot-default-extension", + "extension_file.DoesNotExistExtension", + ) + result.stdout.re_match_lines((r".*: Member 'DoesNotExistExtension' not found.*",)) + assert not Path( + testfile.path, "__snapshots__", "test_file", "test_default.raw" + ).exists() + assert result.ret
`--snapshot-default-extension` doesn't support pytest 7 `pythonpath` **Describe the bug** `--snapshot-default-extension` doesn't support pytest 7's `pythonpath` configuration option, for pytest-only additions to the Python path. For my project, I'm using `--snapshot-default-extension` so the right extension and serializer are in place, before Syrupy begins its reporting. My Syrupy extensions are for tests only, so they live outside of my src/ folder. Only the src/ folder of my project seems to be on the default Python path. So when running tests, I need to tell Syrupy about my extensions, somehow. I'd love to use the vanilla `pytest` command directly, configured in pyproject.toml, without having to pass a custom `PYTHONPATH` to `pytest` every time. **To reproduce** See my branch, [john-kurkowski/syrupy#default-extension-pythonpath](https://github.com/john-kurkowski/syrupy/compare/main..default-extension-pythonpath). In the final commit, https://github.com/john-kurkowski/syrupy/commit/ea9779371583253c03b0bdf47c09ca6f5526d909, switching from modifying `sys.path` to setting pytest's `--pythonpath` breaks 2/3 of the branch's test cases. **EDIT:** pytest's `pythonpath` an INI configuration option, not CLI. ```diff diff --git a/tests/integration/test_snapshot_option_extension.py b/tests/integration/test_snapshot_option_extension.py index de8e807..42b2eec 100644 --- a/tests/integration/test_snapshot_option_extension.py +++ b/tests/integration/test_snapshot_option_extension.py @@ -26,11 +26,11 @@ def testfile(testdir): return testdir -def test_snapshot_default_extension_option_success(monkeypatch, testfile): - monkeypatch.syspath_prepend(testfile.tmpdir) - +def test_snapshot_default_extension_option_success(testfile): result = testfile.runpytest( "-v", + "--pythonpath", + testfile.tmpdir, "--snapshot-update", "--snapshot-default-extension", "extension_file.MySingleFileExtension", @@ -63,11 +63,11 @@ def test_snapshot_default_extension_option_module_not_found(testfile): assert result.ret -def test_snapshot_default_extension_option_member_not_found(monkeypatch, testfile): - monkeypatch.syspath_prepend(testfile.tmpdir) - +def test_snapshot_default_extension_option_member_not_found(testfile): result = testfile.runpytest( "-v", + "--pythonpath", + testfile.tmpdir, "--snapshot-update", "--snapshot-default-extension", "extension_file.DoesNotExistExtension", ``` **Expected behavior** Tests in my branch should pass. **Environment:** - OS: macOS - Syrupy Version: 4.0.1 - Python Version: 3.11.1 **Workaround** Set `PYTHONPATH` prior to invoking the pytest CLI. ```sh PYTHONPATH=path/to/my/extensions/folder pytest --snapshot-default-extension some_module.SomeExtension ```
0.0
028cb8f0c100f6be118d5aacf80974e7503980e2
[ "tests/integration/test_snapshot_option_extension.py::test_snapshot_default_extension_option_failure", "tests/integration/test_snapshot_option_extension_pythonpath.py::test_snapshot_default_extension_option_success", "tests/integration/test_snapshot_option_extension_pythonpath.py::test_snapshot_default_extension_option_module_not_found", "tests/integration/test_snapshot_option_extension_pythonpath.py::test_snapshot_default_extension_option_failure" ]
[ "tests/integration/test_snapshot_option_extension.py::test_snapshot_default_extension_option_success" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-04-06 23:57:55+00:00
apache-2.0
6,060
tophat__syrupy-761
diff --git a/src/syrupy/extensions/single_file.py b/src/syrupy/extensions/single_file.py index 8e1a7c5..19b9838 100644 --- a/src/syrupy/extensions/single_file.py +++ b/src/syrupy/extensions/single_file.py @@ -82,9 +82,10 @@ class SingleFileSnapshotExtension(AbstractSyrupyExtension): ) -> "SnapshotCollection": file_ext_len = len(self._file_extension) + 1 if self._file_extension else 0 filename_wo_ext = snapshot_location[:-file_ext_len] + basename = Path(filename_wo_ext).parts[-1] snapshot_collection = SnapshotCollection(location=snapshot_location) - snapshot_collection.add(Snapshot(name=Path(filename_wo_ext).stem)) + snapshot_collection.add(Snapshot(name=basename)) return snapshot_collection def _read_snapshot_data_from_location(
tophat/syrupy
eb3183d3fc0da739d8909272a400fdaa722c2faa
diff --git a/tests/integration/test_single_file_multiple_extensions.py b/tests/integration/test_single_file_multiple_extensions.py index b93f287..bcee53d 100644 --- a/tests/integration/test_single_file_multiple_extensions.py +++ b/tests/integration/test_single_file_multiple_extensions.py @@ -38,3 +38,39 @@ def test_multiple_file_extensions(testdir): result.stdout.re_match_lines((r"1 snapshot passed\.")) assert "snapshots unused" not in result.stdout.str() assert result.ret == 0 + + +def test_class_style(testdir): + """ + Regression test for https://github.com/tophat/syrupy/issues/717 + """ + + testcase = """ + import pytest + from syrupy.extensions.json import JSONSnapshotExtension + + @pytest.fixture + def snapshot(snapshot): + return snapshot.use_extension(JSONSnapshotExtension) + + class TestFoo: + def test_foo(self, snapshot): + assert { 'key': 'value' } == snapshot + """ + + test_file: Path = testdir.makepyfile(test_file=testcase) + + result = testdir.runpytest("-v", "--snapshot-update") + result.stdout.re_match_lines((r"1 snapshot generated\.")) + assert "deleted" not in result.stdout.str() + assert result.ret == 0 + + snapshot_file = ( + Path(test_file).parent / "__snapshots__" / "test_file" / "TestFoo.test_foo.json" + ) + assert snapshot_file.exists() + + result = testdir.runpytest("-v") + result.stdout.re_match_lines((r"1 snapshot passed\.")) + assert "snapshots unused" not in result.stdout.str() + assert result.ret == 0
Syrupy is recognizing snapshot as not being used (4.0.1) **Describe the bug** This is probably a regression in the latest release. I didn't observe the behavior in 4.0.0: 1. On a new test with no snapshot (using the `json` extension), I get the expected behaviour: > 1 snapshot failed > Snapshot 'TestFoo.test_foo' does not exist! 2. With the first `pytest --snapshot-update` (this is where the first signs of the bug is): > 1 snapshot generated. 1 unused snapshot deleted. Deleted TestFoo (tests/foo/__snapshots__/test_foo/TestFoo.test_foo.json) Why does it output `Deleted ....`, that isn't the expected behaviour (the deletion doesn't happen though) 3. Another follow up when running `pytest`: > 1 snapshot passed. 1 snapshot unused. Re-run pytest with --snapshot-update to delete unused snapshots. Again, that isn't correct. It gets worse though: 4. `pytest --snapshot-update`: This time the deletion *will* happen hence the next run of `pytest` will fail since it won't find a snapshot. # Env: Syrupy 4.0.1 Python 3.10 Going back to 4.0.0 solved the issue.
0.0
eb3183d3fc0da739d8909272a400fdaa722c2faa
[ "tests/integration/test_single_file_multiple_extensions.py::test_class_style" ]
[ "tests/integration/test_single_file_multiple_extensions.py::test_multiple_file_extensions" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-06-19 03:43:28+00:00
apache-2.0
6,061
tophat__syrupy-769
diff --git a/src/syrupy/assertion.py b/src/syrupy/assertion.py index 35c301d..328afb4 100644 --- a/src/syrupy/assertion.py +++ b/src/syrupy/assertion.py @@ -45,6 +45,7 @@ class AssertionResult: updated: bool success: bool exception: Optional[Exception] + test_location: "PyTestLocation" @property def final_data(self) -> Optional["SerializedData"]: @@ -303,14 +304,15 @@ class SnapshotAssertion: snapshot_updated = matches is False and assertion_success self._execution_name_index[self.index] = self._executions self._execution_results[self._executions] = AssertionResult( + asserted_data=serialized_data, + created=snapshot_created, + exception=assertion_exception, + recalled_data=snapshot_data, snapshot_location=snapshot_location, snapshot_name=snapshot_name, - recalled_data=snapshot_data, - asserted_data=serialized_data, success=assertion_success, - created=snapshot_created, + test_location=self.test_location, updated=snapshot_updated, - exception=assertion_exception, ) self._executions += 1 self._post_assert() diff --git a/src/syrupy/location.py b/src/syrupy/location.py index 3d8fe2d..0f955bb 100644 --- a/src/syrupy/location.py +++ b/src/syrupy/location.py @@ -15,7 +15,7 @@ from syrupy.constants import PYTEST_NODE_SEP @dataclass class PyTestLocation: - _node: "pytest.Item" + item: "pytest.Item" nodename: Optional[str] = field(init=False) testname: str = field(init=False) methodname: str = field(init=False) @@ -28,16 +28,16 @@ class PyTestLocation: self.__attrs_post_init_def__() def __attrs_post_init_def__(self) -> None: - node_path: Path = getattr(self._node, "path") # noqa: B009 + node_path: Path = getattr(self.item, "path") # noqa: B009 self.filepath = str(node_path.absolute()) - obj = getattr(self._node, "obj") # noqa: B009 + obj = getattr(self.item, "obj") # noqa: B009 self.modulename = obj.__module__ self.methodname = obj.__name__ - self.nodename = getattr(self._node, "name", None) + self.nodename = getattr(self.item, "name", None) self.testname = self.nodename or self.methodname def __attrs_post_init_doc__(self) -> None: - doctest = getattr(self._node, "dtest") # noqa: B009 + doctest = getattr(self.item, "dtest") # noqa: B009 self.filepath = doctest.filename test_relfile, test_node = self.nodeid.split(PYTEST_NODE_SEP) test_relpath = Path(test_relfile) @@ -64,7 +64,7 @@ class PyTestLocation: :raises: `AttributeError` if node has no node id :return: test node id """ - return str(getattr(self._node, "nodeid")) # noqa: B009 + return str(getattr(self.item, "nodeid")) # noqa: B009 @property def basename(self) -> str: @@ -78,7 +78,7 @@ class PyTestLocation: @property def is_doctest(self) -> bool: - return self.__is_doctest(self._node) + return self.__is_doctest(self.item) def __is_doctest(self, node: "pytest.Item") -> bool: return hasattr(node, "dtest") diff --git a/src/syrupy/report.py b/src/syrupy/report.py index 4088be4..5eaa4b6 100644 --- a/src/syrupy/report.py +++ b/src/syrupy/report.py @@ -22,6 +22,8 @@ from typing import ( Set, ) +from _pytest.skipping import xfailed_key + from .constants import PYTEST_NODE_SEP from .data import ( Snapshot, @@ -70,6 +72,7 @@ class SnapshotReport: used: "SnapshotCollections" = field(default_factory=SnapshotCollections) _provided_test_paths: Dict[str, List[str]] = field(default_factory=dict) _keyword_expressions: Set["Expression"] = field(default_factory=set) + _num_xfails: int = field(default=0) @property def update_snapshots(self) -> bool: @@ -89,6 +92,14 @@ class SnapshotReport: getattr(item, "nodeid"): item for item in self.collected_items # noqa: B009 } + def _has_xfail(self, item: "pytest.Item") -> bool: + # xfailed_key is 'private'. I'm open to a better way to do this: + if xfailed_key in item.stash: + result = item.stash[xfailed_key] + if result: + return result.run + return False + def __post_init__(self) -> None: self.__parse_invocation_args() @@ -113,6 +124,7 @@ class SnapshotReport: Snapshot(name=result.snapshot_name, data=result.final_data) ) self.used.update(snapshot_collection) + if result.created: self.created.update(snapshot_collection) elif result.updated: @@ -120,6 +132,9 @@ class SnapshotReport: elif result.success: self.matched.update(snapshot_collection) else: + has_xfail = self._has_xfail(item=result.test_location.item) + if has_xfail: + self._num_xfails += 1 self.failed.update(snapshot_collection) def __parse_invocation_args(self) -> None: @@ -161,7 +176,7 @@ class SnapshotReport: def num_created(self) -> int: return self._count_snapshots(self.created) - @property + @cached_property def num_failed(self) -> int: return self._count_snapshots(self.failed) @@ -256,14 +271,22 @@ class SnapshotReport: ``` """ summary_lines: List[str] = [] - if self.num_failed: + if self.num_failed and self._num_xfails < self.num_failed: summary_lines.append( ngettext( "{} snapshot failed.", "{} snapshots failed.", - self.num_failed, - ).format(error_style(self.num_failed)) + self.num_failed - self._num_xfails, + ).format(error_style(self.num_failed - self._num_xfails)), ) + if self._num_xfails: + summary_lines.append( + ngettext( + "{} snapshot xfailed.", + "{} snapshots xfailed.", + self._num_xfails, + ).format(warning_style(self._num_xfails)), + ) if self.num_matched: summary_lines.append( ngettext(
tophat/syrupy
6a93c87229b2091d16a4190bd5f6a8c36a71ecad
diff --git a/tests/integration/test_xfail.py b/tests/integration/test_xfail.py new file mode 100644 index 0000000..5113717 --- /dev/null +++ b/tests/integration/test_xfail.py @@ -0,0 +1,54 @@ +def test_no_failure_printed_if_all_failures_xfailed(testdir): + testdir.makepyfile( + test_file=( + """ + import pytest + + @pytest.mark.xfail(reason="Failure expected.") + def test_a(snapshot): + assert snapshot == 'does-not-exist' + """ + ) + ) + result = testdir.runpytest("-v") + result.stdout.no_re_match_line((r".*snapshot failed*")) + assert result.ret == 0 + + +def test_failures_printed_if_only_some_failures_xfailed(testdir): + testdir.makepyfile( + test_file=( + """ + import pytest + + @pytest.mark.xfail(reason="Failure expected.") + def test_a(snapshot): + assert snapshot == 'does-not-exist' + + def test_b(snapshot): + assert snapshot == 'other' + """ + ) + ) + result = testdir.runpytest("-v") + result.stdout.re_match_lines((r".*1 snapshot failed*")) + result.stdout.re_match_lines((r".*1 snapshot xfailed*")) + assert result.ret == 1 + + +def test_failure_printed_if_xfail_does_not_run(testdir): + testdir.makepyfile( + test_file=( + """ + import pytest + + @pytest.mark.xfail(False, reason="Failure expected.") + def test_a(snapshot): + assert snapshot == 'does-not-exist' + """ + ) + ) + result = testdir.runpytest("-v") + result.stdout.re_match_lines((r".*1 snapshot failed*")) + result.stdout.no_re_match_line((r".*1 snapshot xfailed*")) + assert result.ret == 1 diff --git a/tests/syrupy/extensions/amber/test_amber_snapshot_diff.py b/tests/syrupy/extensions/amber/test_amber_snapshot_diff.py index 71cef86..9dcff61 100644 --- a/tests/syrupy/extensions/amber/test_amber_snapshot_diff.py +++ b/tests/syrupy/extensions/amber/test_amber_snapshot_diff.py @@ -51,9 +51,9 @@ def test_snapshot_diff_id(snapshot): assert dictCase3 == snapshot(name="case3", diff="large snapshot") [email protected](reason="Asserting snapshot does not exist") def test_snapshot_no_diff_raises_exception(snapshot): my_dict = { "field_0": "value_0", } - with pytest.raises(AssertionError, match="SnapshotDoesNotExist"): - assert my_dict == snapshot(diff="does not exist index") + assert my_dict == snapshot(diff="does not exist index")
Tests marked `xfail` are reported as failures Hey there, thanks for your work on `syrupy`! I'm wondering if the fact that XFAIL tests are reported as failures is an intended design decision, a bug, or something you haven't contemplated yet. The full context is from https://github.com/Textualize/textual/issues/2282 but, in short, I have a snapshot test that is marked with `xfail`: ![](https://user-images.githubusercontent.com/5621605/231783110-cb2fd213-8fbe-4746-b9fe-8e16368c256a.png) However, at the end, I get a report saying that one snapshot test failed: ![](https://user-images.githubusercontent.com/5621605/231783032-733059ee-9ddd-429d-bba6-34bd39facfcc.png) I expected to see a yellow warning saying that one snapshot test gave an expected failure instead of the red warning saying that the test failed, especially taking into account the confusing contrast with pytest, which happily reports that the tests passed.
0.0
6a93c87229b2091d16a4190bd5f6a8c36a71ecad
[ "tests/integration/test_xfail.py::test_no_failure_printed_if_all_failures_xfailed", "tests/integration/test_xfail.py::test_failures_printed_if_only_some_failures_xfailed" ]
[ "tests/integration/test_xfail.py::test_failure_printed_if_xfail_does_not_run", "tests/syrupy/extensions/amber/test_amber_snapshot_diff.py::test_snapshot_diff", "tests/syrupy/extensions/amber/test_amber_snapshot_diff.py::test_snapshot_diff_id" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-07-11 21:02:14+00:00
apache-2.0
6,062
tornadoweb__tornado-2393
diff --git a/tornado/autoreload.py b/tornado/autoreload.py index 2f911270..7d69474a 100644 --- a/tornado/autoreload.py +++ b/tornado/autoreload.py @@ -107,6 +107,9 @@ _watched_files = set() _reload_hooks = [] _reload_attempted = False _io_loops = weakref.WeakKeyDictionary() # type: ignore +_autoreload_is_main = False +_original_argv = None +_original_spec = None def start(check_time=500): @@ -214,11 +217,15 @@ def _reload(): # __spec__ is not available (Python < 3.4), check instead if # sys.path[0] is an empty string and add the current directory to # $PYTHONPATH. - spec = getattr(sys.modules['__main__'], '__spec__', None) - if spec: - argv = ['-m', spec.name] + sys.argv[1:] + if _autoreload_is_main: + spec = _original_spec + argv = _original_argv else: + spec = getattr(sys.modules['__main__'], '__spec__', None) argv = sys.argv + if spec: + argv = ['-m', spec.name] + argv[1:] + else: path_prefix = '.' + os.pathsep if (sys.path[0] == '' and not os.environ.get("PYTHONPATH", "").startswith(path_prefix)): @@ -226,7 +233,7 @@ def _reload(): os.environ.get("PYTHONPATH", "")) if not _has_execv: subprocess.Popen([sys.executable] + argv) - sys.exit(0) + os._exit(0) else: try: os.execv(sys.executable, [sys.executable] + argv) @@ -269,7 +276,17 @@ def main(): can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ + # Remember that we were launched with autoreload as main. + # The main module can be tricky; set the variables both in our globals + # (which may be __main__) and the real importable version. + import tornado.autoreload + global _autoreload_is_main + global _original_argv, _original_spec + tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv + tornado.autoreload._original_argv = _original_argv = original_argv + original_spec = getattr(sys.modules['__main__'], '__spec__', None) + tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module"
tornadoweb/tornado
eb487cac3d829292ecca6e5124b1da5ae6bba407
diff --git a/tornado/test/autoreload_test.py b/tornado/test/autoreload_test.py index 6a9729db..1ea53167 100644 --- a/tornado/test/autoreload_test.py +++ b/tornado/test/autoreload_test.py @@ -1,14 +1,19 @@ from __future__ import absolute_import, division, print_function import os +import shutil import subprocess from subprocess import Popen import sys from tempfile import mkdtemp +import time from tornado.test.util import unittest -MAIN = """\ +class AutoreloadTest(unittest.TestCase): + + def test_reload_module(self): + main = """\ import os import sys @@ -24,15 +29,13 @@ if 'TESTAPP_STARTED' not in os.environ: autoreload._reload() """ - -class AutoreloadTest(unittest.TestCase): - def test_reload_module(self): # Create temporary test application path = mkdtemp() + self.addCleanup(shutil.rmtree, path) os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: - f.write(MAIN) + f.write(main) # Make sure the tornado module under test is available to the test # application @@ -46,3 +49,64 @@ class AutoreloadTest(unittest.TestCase): universal_newlines=True) out = p.communicate()[0] self.assertEqual(out, 'Starting\nStarting\n') + + def test_reload_wrapper_preservation(self): + # This test verifies that when `python -m tornado.autoreload` + # is used on an application that also has an internal + # autoreload, the reload wrapper is preserved on restart. + main = """\ +import os +import sys + +# This import will fail if path is not set up correctly +import testapp + +if 'tornado.autoreload' not in sys.modules: + raise Exception('started without autoreload wrapper') + +import tornado.autoreload + +print('Starting') +sys.stdout.flush() +if 'TESTAPP_STARTED' not in os.environ: + os.environ['TESTAPP_STARTED'] = '1' + # Simulate an internal autoreload (one not caused + # by the wrapper). + tornado.autoreload._reload() +else: + # Exit directly so autoreload doesn't catch it. + os._exit(0) +""" + + # Create temporary test application + path = mkdtemp() + os.mkdir(os.path.join(path, 'testapp')) + self.addCleanup(shutil.rmtree, path) + init_file = os.path.join(path, 'testapp', '__init__.py') + open(init_file, 'w').close() + main_file = os.path.join(path, 'testapp', '__main__.py') + with open(main_file, 'w') as f: + f.write(main) + + # Make sure the tornado module under test is available to the test + # application + pythonpath = os.getcwd() + if 'PYTHONPATH' in os.environ: + pythonpath += os.pathsep + os.environ['PYTHONPATH'] + + autoreload_proc = Popen( + [sys.executable, '-m', 'tornado.autoreload', '-m', 'testapp'], + stdout=subprocess.PIPE, cwd=path, + env=dict(os.environ, PYTHONPATH=pythonpath), + universal_newlines=True) + + for i in range(20): + if autoreload_proc.poll() is not None: + break + time.sleep(0.1) + else: + autoreload_proc.kill() + raise Exception("subprocess failed to terminate") + + out = autoreload_proc.communicate()[0] + self.assertEqual(out, 'Starting\n' * 2)
autoreload: Fix argv preservation `autoreload` currently has a wrapper mode (e.g. `python -m tornado.autoreload -m tornado.test`) for scripts, and an in-process mode (enabled by `Application(..., debug=True)`). It's useful to combine these, since the wrapper can catch syntax errors that cause the process to abort before entering its IOLoop. However, this doesn't work as well as it should, because the `main` wrapper only restores `sys.argv` if the process exits, meaning the `-m tornado.autoreload` flags are lost if the inner autoreload fires. The original argv needs to be stored in a global when `autoreload` is `__main__`, so that it can be used in `_reload()`.
0.0
eb487cac3d829292ecca6e5124b1da5ae6bba407
[ "tornado/test/autoreload_test.py::AutoreloadTest::test_reload_wrapper_preservation" ]
[ "tornado/test/autoreload_test.py::AutoreloadTest::test_reload_module" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-19 23:59:17+00:00
apache-2.0
6,063
torrua__keyboa-15
diff --git a/keyboa/button.py b/keyboa/button.py index 6280ba8..9b70703 100644 --- a/keyboa/button.py +++ b/keyboa/button.py @@ -46,6 +46,9 @@ class Button(ButtonCheck): back_marker: CallbackDataMarker = str() copy_text_to_callback: Optional[bool] = None + def __call__(self, *args, **kwargs): + return self.generate() + def generate(self) -> InlineKeyboardButton: """ This function creates an InlineKeyboardButton object from various data types,
torrua/keyboa
f70ec7162e4352726922d60088f2bce9e88fc96f
diff --git a/tests/test_base.py b/tests/test_base.py index 78dc2cb..1c77e28 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -17,7 +17,7 @@ def test_items_is_none_or_empty(): :return: """ with pytest.raises(ValueError) as _: - Keyboa(items=list()) + Keyboa(items=[]) with pytest.raises(ValueError) as _: Keyboa(items=None) diff --git a/tests/test_button.py b/tests/test_button.py index b0a8ad1..435183a 100644 --- a/tests/test_button.py +++ b/tests/test_button.py @@ -37,7 +37,7 @@ UNACCEPTABLE_BUTTON_SOURCE_TYPES = ( {2, "a"}, {"a", 2}, [2, "a"], - (2, dict()), + (2, {}), ["a", 2], (None, 2), (None, None), @@ -284,3 +284,8 @@ def test_none_as_markers(): def test_button_property(): btn = Button(button_data="button_text", copy_text_to_callback=True).button assert isinstance(btn, InlineKeyboardButton) + + +def test_button_call_method(): + btn = Button(button_data="button_text", copy_text_to_callback=True) + assert isinstance(btn(), InlineKeyboardButton) diff --git a/tests/test_keyboard.py b/tests/test_keyboard.py index 41627fb..0709297 100644 --- a/tests/test_keyboard.py +++ b/tests/test_keyboard.py @@ -667,3 +667,22 @@ def test_kb_with_items_in_row_and_last_buttons(): items_in_row=2, ).keyboard assert len(keyboa.keyboard) == 4 + + +def test_kb_is_callable(): + keyboa = Keyboa( + items=[ + (1, "a"), + (2, "b"), + (3, "c"), + (4, "d"), + (5, "e"), + (6, "f"), + ], + back_marker="_is_callable", + items_in_row=2, + ) + assert type(keyboa.keyboard) == type(keyboa()) + assert keyboa.keyboard.to_json() == keyboa().to_json() == keyboa.slice().to_json() + assert keyboa.slice(slice(3)).to_json() == keyboa(slice(3)).to_json() + assert keyboa.slice(slice(2, 4, 2)).to_json() == keyboa(slice(2, 4, 2)).to_json()
(PTC-W0019) Consider using literal syntax to create the data structure ## Description Using the literal syntax can give minor performance bumps compared to using function calls to create `dict`, `list` and `tuple`. ## Occurrences There are 2 occurrences of this issue in the repository. See all occurrences on DeepSource &rarr; [deepsource.io/gh/torrua/keyboa/issue/PTC-W0019/occurrences/](https://deepsource.io/gh/torrua/keyboa/issue/PTC-W0019/occurrences/)
0.0
f70ec7162e4352726922d60088f2bce9e88fc96f
[ "tests/test_button.py::test_button_call_method" ]
[ "tests/test_base.py::test_items_is_none_or_empty", "tests/test_base.py::test_copy_text_to_callback_is_not_bool", "tests/test_base.py::test_number_of_items_out_of_limits", "tests/test_base.py::test_number_of_items_in_row_out_of_limits", "tests/test_button.py::test_acceptable_button_source_types[2_0]", "tests/test_button.py::test_acceptable_button_source_types[a]", "tests/test_button.py::test_acceptable_button_source_types[2_1]", "tests/test_button.py::test_acceptable_button_source_types[button_data3]", "tests/test_button.py::test_acceptable_button_source_types[button_data4]", "tests/test_button.py::test_acceptable_button_source_types[button_data5]", "tests/test_button.py::test_acceptable_button_source_types[button_data6]", "tests/test_button.py::test_acceptable_button_source_types[button_data7]", "tests/test_button.py::test_unacceptable_button_source_types_without_callback[2_0]", "tests/test_button.py::test_unacceptable_button_source_types_without_callback[a]", "tests/test_button.py::test_unacceptable_button_source_types_without_callback[2_1]", "tests/test_button.py::test_unacceptable_button_source_types_without_callback[button_data3]", "tests/test_button.py::test_unacceptable_button_source_types[button_data0]", "tests/test_button.py::test_unacceptable_button_source_types[button_data1]", "tests/test_button.py::test_unacceptable_button_source_types[button_data2]", "tests/test_button.py::test_unacceptable_button_source_types[button_data3]", "tests/test_button.py::test_unacceptable_button_source_types[button_data4]", "tests/test_button.py::test_unacceptable_button_source_types[button_data5]", "tests/test_button.py::test_unacceptable_button_source_types[button_data6]", "tests/test_button.py::test_unacceptable_button_source_types[None]", "tests/test_button.py::test_unacceptable_front_marker_type", "tests/test_button.py::test_unacceptable_back_marker_type", "tests/test_button.py::test_unacceptable_callback_data_type", "tests/test_button.py::test_unacceptable_text_type[button_data0]", "tests/test_button.py::test_unacceptable_text_type[button_data1]", "tests/test_button.py::test_unacceptable_text_type[button_data2]", "tests/test_button.py::test_create_button_from_dict_tuple_list[button_data0]", "tests/test_button.py::test_create_button_from_dict_tuple_list[button_data1]", "tests/test_button.py::test_create_button_from_int_or_str_with_copy_option[12345_0]", "tests/test_button.py::test_create_button_from_int_or_str_with_copy_option[12345_1]", "tests/test_button.py::test_create_button_from_int_or_str_without_copy_option[12345_0]", "tests/test_button.py::test_create_button_from_int_or_str_without_copy_option[12345_1]", "tests/test_button.py::test_create_button_from_int_or_str_without_callback[12345_0]", "tests/test_button.py::test_create_button_from_int_or_str_without_callback[12345_1]", "tests/test_button.py::test_create_button_from_button", "tests/test_button.py::test_empty_text", "tests/test_button.py::test_empty_callback_data", "tests/test_button.py::test_big_callback_data", "tests/test_button.py::test_none_as_markers", "tests/test_button.py::test_button_property", "tests/test_keyboard.py::test_keyboards_is_none", "tests/test_keyboard.py::test_keyboards_is_single_keyboard", "tests/test_keyboard.py::test_keyboards_is_multi_keyboards", "tests/test_keyboard.py::test_not_keyboard_for_merge", "tests/test_keyboard.py::test_merge_two_keyboard_into_one_out_of_limits", "tests/test_keyboard.py::test_pass_string_with_copy_to_callback", "tests/test_keyboard.py::test_pass_string_without_copy_to_callback", "tests/test_keyboard.py::test_pass_one_button", "tests/test_keyboard.py::test_pass_one_item_dict_with_text_field", "tests/test_keyboard.py::test_pass_one_item_dict_without_text_field", "tests/test_keyboard.py::test_pass_multi_item_dict_without_text_field", "tests/test_keyboard.py::test_pass_one_row", "tests/test_keyboard.py::test_pass_structure", "tests/test_keyboard.py::test_auto_keyboa_maker_alignment", "tests/test_keyboard.py::test_auto_keyboa_maker_items_in_row", "tests/test_keyboard.py::test_slice", "tests/test_keyboard.py::test_minimal_kb_with_copy_text_to_callback_specified_none", "tests/test_keyboard.py::test_minimal_kb_with_items_out_of_limits", "tests/test_keyboard.py::test_minimal_kb_with_copy_text_to_callback_specified_true", "tests/test_keyboard.py::test_minimal_kb_with_copy_text_to_callback_specified_false", "tests/test_keyboard.py::test_minimal_kb_with_fixed_items_in_row[2]", "tests/test_keyboard.py::test_minimal_kb_with_fixed_items_in_row[3]", "tests/test_keyboard.py::test_minimal_kb_with_fixed_items_in_row[4]", "tests/test_keyboard.py::test_minimal_kb_with_fixed_items_in_row[6]", "tests/test_keyboard.py::test_minimal_kb_with_front_marker", "tests/test_keyboard.py::test_minimal_kb_with_front_marker_and_copy_text_to_callback", "tests/test_keyboard.py::test_minimal_kb_with_back_marker", "tests/test_keyboard.py::test_minimal_kb_with_back_marker_out_of_limits", "tests/test_keyboard.py::test_minimal_kb_with_back_marker_out_of_limits_with_text", "tests/test_keyboard.py::test_minimal_kb_with_empty_back_marker", "tests/test_keyboard.py::test_minimal_kb_with_back_marker_and_copy_text_to_callback", "tests/test_keyboard.py::test_minimal_kb_with_front_and_back_markers", "tests/test_keyboard.py::test_minimal_kb_with_front_and_back_markers_and_copy_text_to_callback", "tests/test_keyboard.py::test_minimal_kb_with_front_and_back_markers_and_copy_text_to_callback_is_false", "tests/test_keyboard.py::test_minimal_kb_with_alignment_true", "tests/test_keyboard.py::test_minimal_kb_with_items_in_row", "tests/test_keyboard.py::test_minimal_kb_with_items_in_row_out_of_limits", "tests/test_keyboard.py::test_minimal_kb_with_alignment_true_slice", "tests/test_keyboard.py::test_minimal_kb_with_alignment_true_and_reversed_alignment_true", "tests/test_keyboard.py::test_minimal_kb_with_alignment_specified", "tests/test_keyboard.py::test_minimal_kb_with_alignment_specified_out_of_limits", "tests/test_keyboard.py::test_minimal_kb_with_alignment_specified_and_reversed_alignment_true", "tests/test_keyboard.py::test_minimal_kb_with_reversed_alignment_true", "tests/test_keyboard.py::test_minimal_kb_with_all_parameters_specified_reversed_range_true", "tests/test_keyboard.py::test_minimal_kb_with_all_parameters_specified_reversed_range_false", "tests/test_keyboard.py::test_structured_kb", "tests/test_keyboard.py::test_structured_kb_with_alignment", "tests/test_keyboard.py::test_structured_kb_with_items_in_row", "tests/test_keyboard.py::test_structured_kb_with_front_marker", "tests/test_keyboard.py::test_structured_kb_with_front_marker_no_copy_text_to_callback", "tests/test_keyboard.py::test_kb_from_tuples", "tests/test_keyboard.py::test_kb_from_tuples_with_front_marker", "tests/test_keyboard.py::test_kb_from_tuples_with_back_marker_and_items_in_row", "tests/test_keyboard.py::test_kb_with_items_in_row_and_last_buttons", "tests/test_keyboard.py::test_kb_is_callable" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-10-01 04:11:39+00:00
mit
6,064
tortoise__tortoise-orm-1104
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2ffaf9d..47116a8 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,9 @@ Changelog ==== 0.19.1 ------ +Added +^^^^^ +- Added `Postgres` partial indexes support. (#1103) Fixed ^^^^^ - `TimeField` for `MySQL` will return `datetime.timedelta` object instead of `datetime.time` object. diff --git a/tortoise/contrib/postgres/indexes.py b/tortoise/contrib/postgres/indexes.py index 0992357..c536464 100644 --- a/tortoise/contrib/postgres/indexes.py +++ b/tortoise/contrib/postgres/indexes.py @@ -1,13 +1,31 @@ -from abc import ABCMeta +from typing import Optional, Set + +from pypika.terms import Term, ValueWrapper from tortoise.indexes import Index -class PostgreSQLIndex(Index, metaclass=ABCMeta): +class PostgreSQLIndex(Index): INDEX_CREATE_TEMPLATE = ( - "CREATE INDEX {exists}{index_name} ON {table_name} USING{index_type}({fields});" + "CREATE INDEX {exists}{index_name} ON {table_name} USING{index_type}({fields}){extra};" ) + def __init__( + self, + *expressions: Term, + fields: Optional[Set[str]] = None, + name: Optional[str] = None, + condition: Optional[dict] = None, + ): + super().__init__(*expressions, fields=fields, name=name) + if condition: + cond = " WHERE " + items = [] + for k, v in condition.items(): + items.append(f"{k} = {ValueWrapper(v)}") + cond += " AND ".join(items) + self.extra = cond + class BloomIndex(PostgreSQLIndex): INDEX_TYPE = "BLOOM"
tortoise/tortoise-orm
e023166781bed2c485b43d1e862c455fa7c3e872
diff --git a/tests/schema/models_postgres_index.py b/tests/schema/models_postgres_index.py index edc7ab2..e2d0fa9 100644 --- a/tests/schema/models_postgres_index.py +++ b/tests/schema/models_postgres_index.py @@ -6,6 +6,7 @@ from tortoise.contrib.postgres.indexes import ( GinIndex, GistIndex, HashIndex, + PostgreSQLIndex, SpGistIndex, ) @@ -17,6 +18,7 @@ class Index(Model): gist = TSVectorField() sp_gist = fields.CharField(max_length=200) hash = fields.CharField(max_length=200) + partial = fields.CharField(max_length=200) class Meta: indexes = [ @@ -26,4 +28,5 @@ class Index(Model): GistIndex(fields={"gist"}), SpGistIndex(fields={"sp_gist"}), HashIndex(fields={"hash"}), + PostgreSQLIndex(fields={"partial"}, condition={"id": 1}), ] diff --git a/tests/schema/test_generate_schema.py b/tests/schema/test_generate_schema.py index 141cf55..76444c2 100644 --- a/tests/schema/test_generate_schema.py +++ b/tests/schema/test_generate_schema.py @@ -1061,19 +1061,22 @@ COMMENT ON TABLE "teamevents" IS 'How participants relate'; "gin" TSVECTOR NOT NULL, "gist" TSVECTOR NOT NULL, "sp_gist" VARCHAR(200) NOT NULL, - "hash" VARCHAR(200) NOT NULL + "hash" VARCHAR(200) NOT NULL, + "partial" VARCHAR(200) NOT NULL ); CREATE INDEX "idx_index_bloom_280137" ON "index" USING BLOOM ("bloom"); CREATE INDEX "idx_index_brin_a54a00" ON "index" USING BRIN ("brin"); CREATE INDEX "idx_index_gin_a403ee" ON "index" USING GIN ("gin"); CREATE INDEX "idx_index_gist_c807bf" ON "index" USING GIST ("gist"); CREATE INDEX "idx_index_sp_gist_2c0bad" ON "index" USING SPGIST ("sp_gist"); -CREATE INDEX "idx_index_hash_cfe6b5" ON "index" USING HASH ("hash");""", +CREATE INDEX "idx_index_hash_cfe6b5" ON "index" USING HASH ("hash"); +CREATE INDEX "idx_index_partial_c5be6a" ON "index" USING ("partial") WHERE id = 1;""", ) async def test_index_safe(self): await self.init_for("tests.schema.models_postgres_index") sql = get_schema_sql(connections.get("default"), safe=True) + print(sql) self.assertEqual( sql, """CREATE TABLE IF NOT EXISTS "index" ( @@ -1083,14 +1086,16 @@ CREATE INDEX "idx_index_hash_cfe6b5" ON "index" USING HASH ("hash");""", "gin" TSVECTOR NOT NULL, "gist" TSVECTOR NOT NULL, "sp_gist" VARCHAR(200) NOT NULL, - "hash" VARCHAR(200) NOT NULL + "hash" VARCHAR(200) NOT NULL, + "partial" VARCHAR(200) NOT NULL ); CREATE INDEX IF NOT EXISTS "idx_index_bloom_280137" ON "index" USING BLOOM ("bloom"); CREATE INDEX IF NOT EXISTS "idx_index_brin_a54a00" ON "index" USING BRIN ("brin"); CREATE INDEX IF NOT EXISTS "idx_index_gin_a403ee" ON "index" USING GIN ("gin"); CREATE INDEX IF NOT EXISTS "idx_index_gist_c807bf" ON "index" USING GIST ("gist"); CREATE INDEX IF NOT EXISTS "idx_index_sp_gist_2c0bad" ON "index" USING SPGIST ("sp_gist"); -CREATE INDEX IF NOT EXISTS "idx_index_hash_cfe6b5" ON "index" USING HASH ("hash");""", +CREATE INDEX IF NOT EXISTS "idx_index_hash_cfe6b5" ON "index" USING HASH ("hash"); +CREATE INDEX IF NOT EXISTS "idx_index_partial_c5be6a" ON "index" USING ("partial") WHERE id = 1;""", ) async def test_m2m_no_auto_create(self):
Postgress partial indexes support Are there any plans for supporting postgress [partial indexes](https://www.postgresql.org/docs/current/indexes-partial.html)? Especially a unique one. It will be really helpful
0.0
e023166781bed2c485b43d1e862c455fa7c3e872
[ "tests/schema/test_generate_schema.py::TestGenerateSchema::test_create_index", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_cyclic", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_fk_bad_model_name", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_fk_bad_null", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_fk_bad_on_delete", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_m2m_bad_model_name", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_m2m_no_auto_create", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_minrelation", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_noid", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_o2o_bad_null", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_o2o_bad_on_delete", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_safe_generation", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_schema", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_schema_no_db_constraint", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_schema_safe", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_table_and_row_comment_generation", "tests/schema/test_generate_schema.py::TestGenerateSchema::test_unsafe_generation" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-04-13 02:03:30+00:00
apache-2.0
6,065
tortoise__tortoise-orm-1123
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 4cf9422..a2bab96 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -18,6 +18,7 @@ Added Fixed ^^^^^ - `TimeField` for `MySQL` will return `datetime.timedelta` object instead of `datetime.time` object. +- Fix on conflict do nothing. (#1122) 0.19.0 ------ diff --git a/tortoise/backends/base/executor.py b/tortoise/backends/base/executor.py index 9dc7590..3cfdec0 100644 --- a/tortoise/backends/base/executor.py +++ b/tortoise/backends/base/executor.py @@ -208,7 +208,7 @@ class BaseExecutor: .insert(*[self.parameter(i) for i in range(len(columns))]) ) if ignore_conflicts: - query = query.do_nothing() + query = query.on_conflict().do_nothing() return query async def _process_insert_result(self, instance: "Model", results: Any) -> None: diff --git a/tortoise/backends/base_postgres/executor.py b/tortoise/backends/base_postgres/executor.py index 39dab14..db34a37 100644 --- a/tortoise/backends/base_postgres/executor.py +++ b/tortoise/backends/base_postgres/executor.py @@ -46,7 +46,7 @@ class BasePostgresExecutor(BaseExecutor): if generated_fields: query = query.returning(*generated_fields) if ignore_conflicts: - query = query.do_nothing() + query = query.on_conflict().do_nothing() return query async def _process_insert_result(self, instance: Model, results: Optional[dict]) -> None:
tortoise/tortoise-orm
aa3d51126065f352e21f7e1531b09547e54aee97
diff --git a/tests/test_bulk.py b/tests/test_bulk.py index 0af5eea..a0875db 100644 --- a/tests/test_bulk.py +++ b/tests/test_bulk.py @@ -132,6 +132,7 @@ class TestBulk(test.TruncationTestCase): async def test_bulk_create_ignore_conflicts(self): name1 = UniqueName(name="name1") name2 = UniqueName(name="name2") + await UniqueName.bulk_create([name1, name2]) await UniqueName.bulk_create([name1, name2], ignore_conflicts=True) with self.assertRaises(IntegrityError): await UniqueName.bulk_create([name1, name2])
bulk_create ignore_conflicts param does not change query **Describe the bug** The ignore_conflicts in the bulk_create function does not change the sql query. It does not add ON CONFLICT DO NOTHING **To Reproduce* Using version 0.19.0 and postgres executor ``` print(SomeModel.bulk_create(objects=objects, ignore_conflicts=True).sql() ``` **Expected behavior** Add "ON CONFLICT DO NOTHING" at the of insert query
0.0
aa3d51126065f352e21f7e1531b09547e54aee97
[ "tests/test_bulk.py::TestBulk::test_bulk_create_ignore_conflicts" ]
[ "tests/test_bulk.py::TestBulk::test_bulk_create", "tests/test_bulk.py::TestBulk::test_bulk_create_fail", "tests/test_bulk.py::TestBulk::test_bulk_create_in_transaction", "tests/test_bulk.py::TestBulk::test_bulk_create_in_transaction_fail", "tests/test_bulk.py::TestBulk::test_bulk_create_mix_specified", "tests/test_bulk.py::TestBulk::test_bulk_create_more_that_one_update_fields", "tests/test_bulk.py::TestBulk::test_bulk_create_update_fields", "tests/test_bulk.py::TestBulk::test_bulk_create_uuidpk", "tests/test_bulk.py::TestBulk::test_bulk_create_uuidpk_fail", "tests/test_bulk.py::TestBulk::test_bulk_create_uuidpk_in_transaction", "tests/test_bulk.py::TestBulk::test_bulk_create_uuidpk_in_transaction_fail", "tests/test_bulk.py::TestBulk::test_bulk_create_with_batch_size", "tests/test_bulk.py::TestBulk::test_bulk_create_with_specified" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-05-08 14:18:55+00:00
apache-2.0
6,066
toumorokoshi__deepmerge-22
diff --git a/Makefile b/Makefile index 9a611ee..75ba49c 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ build: .venv/deps # only works with python 3+ lint: .venv/deps - .venv/bin/python -m pip install black==21.12b0 + .venv/bin/python -m pip install black==22.3.0 .venv/bin/python -m black --check . test: .venv/deps diff --git a/deepmerge/extended_set.py b/deepmerge/extended_set.py new file mode 100644 index 0000000..1d51b43 --- /dev/null +++ b/deepmerge/extended_set.py @@ -0,0 +1,25 @@ +class ExtendedSet(set): + """ + ExtendedSet is an extension of set, which allows for usage + of types that are typically not allowed in a set + (e.g. unhashable). + + The following types that cannot be used in a set are supported: + + - unhashable types + """ + + def __init__(self, elements): + self._values_by_hash = {self._hash(e): e for e in elements} + + def _insert(self, element): + self._values_by_hash[self._hash(element)] = element + + def _hash(self, element): + if getattr(element, "__hash__") is not None: + return hash(element) + else: + return hash(str(element)) + + def __contains__(self, obj): + return self._hash(obj) in self._values_by_hash diff --git a/deepmerge/strategy/list.py b/deepmerge/strategy/list.py index ca42828..2e42519 100644 --- a/deepmerge/strategy/list.py +++ b/deepmerge/strategy/list.py @@ -1,4 +1,5 @@ from .core import StrategyList +from ..extended_set import ExtendedSet class ListStrategies(StrategyList): @@ -26,5 +27,5 @@ class ListStrategies(StrategyList): @staticmethod def strategy_append_unique(config, path, base, nxt): """append items without duplicates in nxt to base.""" - base_as_set = set(base) + base_as_set = ExtendedSet(base) return base + [n for n in nxt if n not in base_as_set] diff --git a/docs/conf.py b/docs/conf.py index ee1edbc..df0dc4d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -52,18 +52,18 @@ source_suffix = ".rst" master_doc = "index" # General information about the project. -project = u"deepmerge" -copyright = u"2016, Yusuke Tsutsumi" -author = u"Yusuke Tsutsumi" +project = "deepmerge" +copyright = "2016, Yusuke Tsutsumi" +author = "Yusuke Tsutsumi" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u"0.1" +version = "0.1" # The full version, including alpha/beta/rc tags. -release = u"0.1" +release = "0.1" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -271,8 +271,8 @@ latex_documents = [ ( master_doc, "deepmerge.tex", - u"deepmerge Documentation", - u"Yusuke Tsutsumi", + "deepmerge Documentation", + "Yusuke Tsutsumi", "manual", ), ] @@ -308,7 +308,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [(master_doc, "deepmerge", u"deepmerge Documentation", [author], 1)] +man_pages = [(master_doc, "deepmerge", "deepmerge Documentation", [author], 1)] # If true, show URL addresses after external links. # @@ -324,7 +324,7 @@ texinfo_documents = [ ( master_doc, "deepmerge", - u"deepmerge Documentation", + "deepmerge Documentation", author, "deepmerge", "One line description of project.", diff --git a/docs/guide.rst b/docs/guide.rst index 39f414a..a13bb01 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -10,7 +10,7 @@ it's recommended to choose your own strategies, deepmerge does provided some preconfigured mergers for a common situations: * deepmerge.always_merger: always try to merge. in the case of mismatches, the value from the second object overrides the first o ne. -* deepmerge.merge_or_raise: try to merge, raise an exception if an unmergable situation is encountered. +* deepmerge.merge_or_raise: try to merge, raise an exception if an unmergable situation is encountered. * deepmerge.conservative_merger: similar to always_merger, but in the case of a conflict, use the existing value. Once a merger is constructed, it then has a merge() method that can be called: @@ -33,7 +33,6 @@ Once a merger is constructed, it then has a merge() method that can be called: Merges are Destructive ====================== - You may have noticed from the example, but merging is a destructive behavior: it will modify the first argument passed in (the base) as part of the merge. This is intentional, as an implicit copy would result in a significant performance slowdown for deep data structures. If you need to keep the original objects unmodified, you can use the deepcopy method: @@ -96,3 +95,13 @@ Example: If a strategy fails, an exception should not be raised. This is to ensure it can be chained with other strategies, or the fall-back. +Uniqueness of elements when merging +=================================== + +Some strategies require determining the uniqueness +of the elements. Since deepmerge primarily deals with nested +types, this includes structures that are not hashable such as +dictionaries. + +In those cases, built-in deepmerge strategies will call repr() +on the object and hash that value instead. \ No newline at end of file
toumorokoshi/deepmerge
4ac5ff666d06cb072ff200ff4255d86d950b71a4
diff --git a/deepmerge/tests/strategy/test_list.py b/deepmerge/tests/strategy/test_list.py index 39215a9..7eb2d3b 100644 --- a/deepmerge/tests/strategy/test_list.py +++ b/deepmerge/tests/strategy/test_list.py @@ -19,3 +19,15 @@ def test_strategy_append_unique(custom_merger): expected = [1, 3, 2, 5, 4] actual = custom_merger.merge(base, nxt) assert actual == expected + + +def test_strategy_append_unique_nested_dict(custom_merger): + """append_unique should work even with unhashable objects + Like dicts. + """ + base = [{"bar": ["bob"]}] + nxt = [{"bar": ["baz"]}] + + result = custom_merger.merge(base, nxt) + + assert result == [{"bar": ["bob"]}, {"bar": ["baz"]}]
list merge strategy append_unique does not work for lists of dicts Hi developers, especially @morph027 , I get an error when trying to apply list merge strategy `append_unique` for lists of dictionaries. I am using deepmerge 1.0.1 and python 3.7.7. When I am running the following code ```python from deepmerge import Merger my_merger = Merger( # pass in a list of tuple, with the # strategies you are looking to apply # to each type. [ (list, ["append_unique"]), (dict, ["merge"]), (set, ["union"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) base = {"foo": ["bar"]} next = {"foo": ["bar","baz"]} result = my_merger.merge(base, next) assert result == {'foo': ['bar', 'baz']} base = {"foo": [{"bar": ["bob"]}]} next = {"foo": [{"bar": ["baz"]}]} result = my_merger.merge(base, next) assert result == {'foo': [{'bar', ["bob"]}, {"bar": ["baz"]}]} ``` I get the following exception ```bash python3 test_merge.py Traceback (most recent call last): File "test_merge.py", line 29, in <module> result = my_merger.merge(base, next) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/merger.py", line 33, in merge return self.value_strategy([], base, nxt) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/merger.py", line 43, in value_strategy return strategy(self, path, base, nxt) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/strategy/core.py", line 35, in __call__ ret_val = s(*args, **kwargs) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/strategy/dict.py", line 23, in strategy_merge base[k] = config.value_strategy(path + [k], base[k], v) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/merger.py", line 43, in value_strategy return strategy(self, path, base, nxt) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/strategy/core.py", line 35, in __call__ ret_val = s(*args, **kwargs) File "/home/horst/venv/lib64/python3.7/site-packages/deepmerge/strategy/list.py", line 29, in strategy_append_unique base_as_set = set(base) TypeError: unhashable type: 'dict' ``` Best, Oliver
0.0
4ac5ff666d06cb072ff200ff4255d86d950b71a4
[ "deepmerge/tests/strategy/test_list.py::test_strategy_append_unique_nested_dict" ]
[ "deepmerge/tests/strategy/test_list.py::test_strategy_append_unique" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-21 06:00:20+00:00
mit
6,067
tox-dev__tox-1614
diff --git a/docs/changelog/1575.feature.rst b/docs/changelog/1575.feature.rst new file mode 100644 index 00000000..7a36ab20 --- /dev/null +++ b/docs/changelog/1575.feature.rst @@ -0,0 +1,3 @@ +Implement support for building projects +having :pep:`517#in-tree-build-backends` ``backend-path`` setting - +by :user:`webknjaz` diff --git a/src/tox/helper/build_isolated.py b/src/tox/helper/build_isolated.py index 55ea41b8..3d897097 100644 --- a/src/tox/helper/build_isolated.py +++ b/src/tox/helper/build_isolated.py @@ -1,10 +1,40 @@ +"""PEP 517 build backend invocation script. + +It accepts externally parsed build configuration from `[build-system]` +in `pyproject.toml` and invokes an API endpoint for building an sdist +tarball. +""" + +import os import sys + +def _ensure_module_in_paths(module, paths): + """Verify that the imported backend belongs in-tree.""" + if not paths: + return + + module_path = os.path.normcase(os.path.abspath(module.__file__)) + normalized_paths = (os.path.normcase(os.path.abspath(path)) for path in paths) + + if any(os.path.commonprefix((module_path, path)) == path for path in normalized_paths): + return + + raise SystemExit( + "build-backend ({!r}) must exist in one of the paths " + "specified by backend-path ({!r})".format(module, paths), + ) + + dist_folder = sys.argv[1] backend_spec = sys.argv[2] backend_obj = sys.argv[3] if len(sys.argv) >= 4 else None +backend_paths = sys.argv[4].split(os.path.pathsep) if sys.argv[4] else [] + +sys.path[:0] = backend_paths backend = __import__(backend_spec, fromlist=["_trash"]) +_ensure_module_in_paths(backend, backend_paths) if backend_obj: backend = getattr(backend, backend_obj) diff --git a/src/tox/package/builder/isolated.py b/src/tox/package/builder/isolated.py index c02aa109..38ebe8ea 100644 --- a/src/tox/package/builder/isolated.py +++ b/src/tox/package/builder/isolated.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals import json +import os from collections import namedtuple import six @@ -11,7 +12,9 @@ from tox import reporter from tox.config import DepConfig, get_py_project_toml from tox.constants import BUILD_ISOLATED, BUILD_REQUIRE_SCRIPT -BuildInfo = namedtuple("BuildInfo", ["requires", "backend_module", "backend_object"]) +BuildInfo = namedtuple( + "BuildInfo", ["requires", "backend_module", "backend_object", "backend_paths"], +) def build(config, session): @@ -84,7 +87,12 @@ def get_build_info(folder): module = args[0] obj = args[1] if len(args) > 1 else "" - return BuildInfo(requires, module, obj) + backend_paths = build_system.get("backend-path", []) + if not isinstance(backend_paths, list): + abort("backend-path key at build-system section must be a list, if specified") + backend_paths = [folder.join(p) for p in backend_paths] + + return BuildInfo(requires, module, obj, backend_paths) def perform_isolated_build(build_info, package_venv, dist_dir, setup_dir): @@ -103,6 +111,7 @@ def perform_isolated_build(build_info, package_venv, dist_dir, setup_dir): str(dist_dir), build_info.backend_module, build_info.backend_object, + os.path.pathsep.join(str(p) for p in build_info.backend_paths), ], returnout=True, action=action,
tox-dev/tox
268ca020ef8bf1600123add72eb4984cba970a4d
diff --git a/tests/unit/package/builder/test_package_builder_isolated.py b/tests/unit/package/builder/test_package_builder_isolated.py index d43ed5f1..63e0685a 100644 --- a/tests/unit/package/builder/test_package_builder_isolated.py +++ b/tests/unit/package/builder/test_package_builder_isolated.py @@ -138,3 +138,18 @@ def test_package_isolated_toml_bad_backend(initproj): build-backend = [] """, ) + + +def test_package_isolated_toml_bad_backend_path(initproj): + """Verify that a non-list 'backend-path' is forbidden.""" + toml_file_check( + initproj, + 6, + "backend-path key at build-system section must be a list, if specified", + """ + [build-system] + requires = [] + build-backend = 'setuptools.build_meta' + backend-path = 42 + """, + )
Support PEP517 in-tree build backend I'm getting ```python-traceback ERROR: invocation failed (exit code 1), logfile: ~/src/github/ansible/pylibssh/.tox/.package/log/.package-2.log =================================== log start ==================================== Traceback (most recent call last): File "~/.pyenv/versions/3.7.1/lib/python3.7/site-packages/tox/helper/build_requires.py", line 7, in <module> backend = __import__(backend_spec, fromlist=[None]) ModuleNotFoundError: No module named 'pep517_backend' ``` because of ```console $ cat pyproject.toml [build-system] ... backend-path = ["bin"] # requires 'Pip>=20' or 'pep517>=0.6.0' build-backend = "pep517_backend" ``` and ```console $ ls -l bin/pep517_backend.py -rw-r--r-- 1 me me 6.2K May 5 00:43 bin/pep517_backend.py ``` I think this should be considered a bug. Pip supports it starting v20 and pep517 supports it with v0.7 or so.
0.0
268ca020ef8bf1600123add72eb4984cba970a4d
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend_path" ]
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_requires", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_requires", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_build_system" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-13 22:47:10+00:00
mit
6,068
tox-dev__tox-1655
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 8eac46c9..1c57f659 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -78,6 +78,7 @@ Morgan Fainberg Naveen S R Nick Douma Nick Prendergast +Nicolas Vivet Oliver Bestwalter Pablo Galindo Paul Moore diff --git a/docs/changelog/1654.bugfix.rst b/docs/changelog/1654.bugfix.rst new file mode 100644 index 00000000..0d20d48a --- /dev/null +++ b/docs/changelog/1654.bugfix.rst @@ -0,0 +1,1 @@ +Support for PEP517 in-tree build backend-path key in ``get-build-requires``. - by :user:`nizox` diff --git a/src/tox/helper/build_requires.py b/src/tox/helper/build_requires.py index cd074f97..aafb258c 100644 --- a/src/tox/helper/build_requires.py +++ b/src/tox/helper/build_requires.py @@ -1,8 +1,12 @@ import json +import os import sys backend_spec = sys.argv[1] backend_obj = sys.argv[2] if len(sys.argv) >= 3 else None +backend_paths = sys.argv[3].split(os.path.pathsep) if len(sys.argv) >= 4 else [] + +sys.path[:0] = backend_paths backend = __import__(backend_spec, fromlist=["_trash"]) if backend_obj: diff --git a/src/tox/package/builder/isolated.py b/src/tox/package/builder/isolated.py index 38ebe8ea..998ce25f 100644 --- a/src/tox/package/builder/isolated.py +++ b/src/tox/package/builder/isolated.py @@ -92,6 +92,15 @@ def get_build_info(folder): abort("backend-path key at build-system section must be a list, if specified") backend_paths = [folder.join(p) for p in backend_paths] + normalized_folder = os.path.normcase(str(folder.realpath())) + normalized_paths = (os.path.normcase(str(path.realpath())) for path in backend_paths) + + if not all( + os.path.commonprefix((normalized_folder, path)) == normalized_folder + for path in normalized_paths + ): + abort("backend-path must exist in the project root") + return BuildInfo(requires, module, obj, backend_paths) @@ -129,6 +138,7 @@ def get_build_requires(build_info, package_venv, setup_dir): BUILD_REQUIRE_SCRIPT, build_info.backend_module, build_info.backend_object, + os.path.pathsep.join(str(p) for p in build_info.backend_paths), ], returnout=True, action=action,
tox-dev/tox
23dd96f5a6891fb13e298ea941bd457931421ffd
diff --git a/tests/unit/package/builder/test_package_builder_isolated.py b/tests/unit/package/builder/test_package_builder_isolated.py index 63e0685a..458e43bb 100644 --- a/tests/unit/package/builder/test_package_builder_isolated.py +++ b/tests/unit/package/builder/test_package_builder_isolated.py @@ -153,3 +153,43 @@ def test_package_isolated_toml_bad_backend_path(initproj): backend-path = 42 """, ) + + +def test_package_isolated_toml_backend_path_outside_root(initproj): + """Verify that a 'backend-path' outside the project root is forbidden.""" + toml_file_check( + initproj, + 6, + "backend-path must exist in the project root", + """ + [build-system] + requires = [] + build-backend = 'setuptools.build_meta' + backend-path = ['..'] + """, + ) + + +def test_verbose_isolated_build_in_tree(initproj, mock_venv, cmd): + initproj( + "example123-0.5", + filedefs={ + "tox.ini": """ + [tox] + isolated_build = true + """, + "build.py": """ + from setuptools.build_meta import * + """, + "pyproject.toml": """ + [build-system] + requires = ["setuptools >= 35.0.2"] + build-backend = 'build' + backend-path = ['.'] + """, + }, + ) + result = cmd("--sdistonly", "-v", "-v", "-v", "-e", "py") + assert "running sdist" in result.out, result.out + assert "running egg_info" in result.out, result.out + assert "Writing example123-0.5{}setup.cfg".format(os.sep) in result.out, result.out
PEP517 in-tree build backend-path support in get-build-requires Using tox 3.19, in-tree build with `backend-path` fails with: ``` .package start: get-build-requires /Users/nicolas/Workspaces/proj/.tox/.package setting PATH=/Users/nicolas/Workspaces/proj/.tox/.package/bin:/Users/nicolas/.virtualenvs/proj-python3.8/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin [15159] /Users/nicolas/Workspaces/proj$ /Users/nicolas/Workspaces/proj/.tox/.package/bin/python /Users/nicolas/.virtualenvs/proj-python3.8/lib/python3.8/site-packages/tox/helper/build_requires.py build_package '' >.tox/.package/log/.package-0.log ERROR: invocation failed (exit code 1), logfile: /Users/nicolas/Workspaces/proj/.tox/.package/log/.package-0.log =================================================================================== log start ==================================================================================== Traceback (most recent call last): File "/Users/nicolas/.virtualenvs/proj-python3.8/lib/python3.8/site-packages/tox/helper/build_requires.py", line 7, in <module> backend = __import__(backend_spec, fromlist=["_trash"]) ModuleNotFoundError: No module named 'build_package' ``` `pyproject.toml` content is: ``` [build-system] requires = [ "setuptools >= 40.9.0", "wheel", ] build-backend = "build_package" backend-path = ["scripts"] ``` A quick patch of `tox/helper/build_requires.py` to use the backend paths similarly to `tox/helper/build_isolated.py` fixes the issue. I can do a PR but the patch duplicates the `_ensure_module_in_paths` function.
0.0
23dd96f5a6891fb13e298ea941bd457931421ffd
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_backend_path_outside_root" ]
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_build_system", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_requires", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend_path", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_requires" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-19 12:45:02+00:00
mit
6,069
tox-dev__tox-1860
diff --git a/docs/changelog/1772.bugfix.rst b/docs/changelog/1772.bugfix.rst new file mode 100644 index 00000000..c96ba979 --- /dev/null +++ b/docs/changelog/1772.bugfix.rst @@ -0,0 +1,2 @@ +Fix a killed tox (via SIGTERM) leaving the commands subprocesses running +by handling it as if it were a KeyboardInterrupt - by :user:`dajose` diff --git a/docs/config.rst b/docs/config.rst index f3bb1b12..01bc9b7d 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -607,9 +607,9 @@ Complete list of settings that you can put into ``testenv*`` sections: .. versionadded:: 3.15.2 - When an interrupt is sent via Ctrl+C, the SIGINT is sent to all foreground - processes. The :conf:``suicide_timeout`` gives the running process time to - cleanup and exit before receiving (in some cases, a duplicate) SIGINT from + When an interrupt is sent via Ctrl+C or the tox process is killed with a SIGTERM, + a SIGINT is sent to all foreground processes. The :conf:``suicide_timeout`` gives + the running process time to cleanup and exit before receiving (in some cases, a duplicate) SIGINT from tox. .. conf:: interrupt_timeout ^ float ^ 0.3 diff --git a/src/tox/action.py b/src/tox/action.py index b5381b83..e7f9b77b 100644 --- a/src/tox/action.py +++ b/src/tox/action.py @@ -49,6 +49,10 @@ class Action(object): self.suicide_timeout = suicide_timeout self.interrupt_timeout = interrupt_timeout self.terminate_timeout = terminate_timeout + if is_main_thread(): + # python allows only main thread to install signal handlers + # see https://docs.python.org/3/library/signal.html#signals-and-threads + self._install_sigterm_handler() def __enter__(self): msg = "{} {}".format(self.msg, " ".join(map(str, self.args))) @@ -278,3 +282,12 @@ class Action(object): new_args.append(str(arg)) return new_args + + def _install_sigterm_handler(self): + """Handle sigterm as if it were a keyboardinterrupt""" + + def sigterm_handler(signum, frame): + reporter.error("Got SIGTERM, handling it as a KeyboardInterrupt") + raise KeyboardInterrupt() + + signal.signal(signal.SIGTERM, sigterm_handler)
tox-dev/tox
3d80588df8ba2e3a382b4345d2bf6cea44d3f901
diff --git a/tests/integration/test_provision_int.py b/tests/integration/test_provision_int.py index 0ae411b8..05fb1a66 100644 --- a/tests/integration/test_provision_int.py +++ b/tests/integration/test_provision_int.py @@ -73,7 +73,8 @@ def test_provision_from_pyvenv(initproj, cmd, monkeypatch): "sys.platform == 'win32'", reason="triggering SIGINT reliably on Windows is hard", ) -def test_provision_interrupt_child(initproj, monkeypatch, capfd): [email protected]("signal_type", [signal.SIGINT, signal.SIGTERM]) +def test_provision_interrupt_child(initproj, monkeypatch, capfd, signal_type): monkeypatch.delenv(str("PYTHONPATH"), raising=False) monkeypatch.setenv(str("TOX_REPORTER_TIMESTAMP"), str("1")) initproj( @@ -123,7 +124,7 @@ def test_provision_interrupt_child(initproj, monkeypatch, capfd): # 1 process for the host tox, 1 for the provisioned assert len(all_process) >= 2, all_process - process.send_signal(signal.CTRL_C_EVENT if sys.platform == "win32" else signal.SIGINT) + process.send_signal(signal.CTRL_C_EVENT if sys.platform == "win32" else signal_type) process.communicate() out, err = capfd.readouterr() assert ".tox KeyboardInterrupt: from" in out, out
kill tox process does not kill running commands Tox seems to not being sending the sigterm signal back to the subprocess it is driving. This can be reproduced with this configuration, and killing the tox process. `tox.ini` ```ini [tox] skipsdist = True [testenv:papa] commands = {envpython} {toxinidir}/papa.py ``` `papa.py` ```python from time import sleep while True: sleep(1) print('papa') ``` from a terminal run ``` tox -e papa ``` and on another, search the process and kill it, for example: ``` diazdavi@darker:/tmp$ ps -aux | grep tox diazdavi 779128 6.3 0.1 114196 22588 pts/0 S+ 17:00 0:00 /usr/bin/python3 /usr/local/bin/tox -e papa diazdavi 779140 0.5 0.0 26912 9500 pts/0 S+ 17:00 0:00 /tmp/.tox/papa/bin/python papa.py diazdavi 779178 0.0 0.0 17664 2700 pts/2 S+ 17:00 0:00 grep --color=auto tox diazdavi@darker:/tmp$ kill 779128 ``` The first terminal will keep showing the prints :(
0.0
3d80588df8ba2e3a382b4345d2bf6cea44d3f901
[ "tests/integration/test_provision_int.py::test_provision_interrupt_child[Signals.SIGTERM]" ]
[ "tests/integration/test_provision_int.py::test_provision_interrupt_child[Signals.SIGINT]" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-01-19 23:34:09+00:00
mit
6,070
tox-dev__tox-1869
diff --git a/docs/changelog/1868.feature.rst b/docs/changelog/1868.feature.rst new file mode 100644 index 00000000..8511d2f4 --- /dev/null +++ b/docs/changelog/1868.feature.rst @@ -0,0 +1,2 @@ +Not all package dependencies are installed when different tox environments in the same run use different set of +extras - by :user:`gaborbernat`. diff --git a/src/tox/tox_env/python/api.py b/src/tox/tox_env/python/api.py index 015ff16b..e5402a0f 100644 --- a/src/tox/tox_env/python/api.py +++ b/src/tox/tox_env/python/api.py @@ -222,8 +222,7 @@ class Python(ToxEnv, ABC): # bail out and force recreate logging.warning(f"recreate env because dependencies removed: {', '.join(str(i) for i in missing)}") raise Recreate - new_deps_str = set(conf_deps) - set(old) - new_deps = [PythonDep(Requirement(i)) for i in new_deps_str] + new_deps = [PythonDep(Requirement(i)) for i in conf_deps if i not in old] self.install_python_packages(packages=new_deps, of_type=of_type) return False diff --git a/src/tox/tox_env/python/virtual_env/package/api.py b/src/tox/tox_env/python/virtual_env/package/api.py index b3a0a11b..738af1e1 100644 --- a/src/tox/tox_env/python/virtual_env/package/api.py +++ b/src/tox/tox_env/python/virtual_env/package/api.py @@ -1,6 +1,7 @@ import os import sys from contextlib import contextmanager +from copy import deepcopy from enum import Enum from pathlib import Path from threading import RLock @@ -95,6 +96,7 @@ class Pep517VirtualEnvPackage(VirtualEnv, PythonPackage, Frontend): self._build_wheel_cache: Optional[WheelResult] = None self._backend_executor: Optional[LocalSubProcessPep517Executor] = None self._package_dependencies: Optional[List[Requirement]] = None + self._package_dev_dependencies: Optional[List[Requirement]] = None self._lock = RLock() # can build only one package at a time self._package: Dict[Tuple[PackageType, str], Any] = {} self._run_env_to_wheel_builder_env: Dict[str, PackageToxEnv] = {} @@ -203,27 +205,28 @@ class Pep517VirtualEnvPackage(VirtualEnv, PythonPackage, Frontend): def get_package_dependencies(self, for_env: EnvConfigSet) -> List[Requirement]: env_name = for_env.name - extras: Set[str] = for_env["extras"] with self._lock: if self._package_dependencies is None: # pragma: no branch self._ensure_meta_present() - dependencies: List[Requirement] = [] - of_type, _ = self._run_env_to_info[env_name] - if of_type == PackageType.dev: - dependencies.extend(self.requires()) - dependencies.extend(self.get_requires_for_build_sdist().requires) - dependencies.extend(self.discover_package_dependencies(self._distribution_meta, extras)) - self._package_dependencies = dependencies - return self._package_dependencies + requires: List[str] = cast(PathDistribution, self._distribution_meta).requires or [] + self._package_dependencies = [Requirement(i) for i in requires] + of_type, _ = self._run_env_to_info[env_name] + if of_type == PackageType.dev and self._package_dev_dependencies is None: + self._package_dev_dependencies = [*self.requires(), *self.get_requires_for_build_sdist().requires] + if of_type == PackageType.dev: + result: List[Requirement] = cast(List[Requirement], self._package_dev_dependencies).copy() + else: + result = [] + extras: Set[str] = for_env["extras"] + result.extend(self.dependencies_with_extras(self._package_dependencies, extras)) + return result @staticmethod - def discover_package_dependencies(meta: PathDistribution, extras: Set[str]) -> List[Requirement]: + def dependencies_with_extras(deps: List[Requirement], extras: Set[str]) -> List[Requirement]: result: List[Requirement] = [] - requires = meta.requires or [] - for req_str in requires: - req = Requirement(req_str) + for req in deps: + req = deepcopy(req) markers: List[Union[str, Tuple[Variable, Variable, Variable]]] = getattr(req.marker, "_markers", []) or [] - # find the extra marker (if has) _at: Optional[int] = None extra: Optional[str] = None @@ -241,7 +244,6 @@ class Pep517VirtualEnvPackage(VirtualEnv, PythonPackage, Frontend): if len(markers) == 0: req.marker = None break - # continue only if this extra should be included if not (extra is None or extra in extras): continue result.append(req)
tox-dev/tox
f17774fdd9fceea40564110bdeac7ce4b30ed677
diff --git a/tests/tox_env/python/virtual_env/test_package.py b/tests/tox_env/python/virtual_env/test_package.py index 9ba1f14e..d3ad4328 100644 --- a/tests/tox_env/python/virtual_env/test_package.py +++ b/tests/tox_env/python/virtual_env/test_package.py @@ -1,5 +1,6 @@ import sys from itertools import zip_longest +from pathlib import Path from textwrap import dedent import pytest @@ -37,7 +38,7 @@ def test_tox_ini_package_type_invalid(tox_project: ToxProjectCreator) -> None: @pytest.fixture(scope="session") -def pkg_with_extras(tmp_path_factory: TempPathFactory) -> PathDistribution: # type: ignore[no-any-unimported] +def pkg_with_extras_project(tmp_path_factory: TempPathFactory) -> Path: py_ver = ".".join(str(i) for i in sys.version_info[0:2]) setup_cfg = f""" [metadata] @@ -64,14 +65,19 @@ def pkg_with_extras(tmp_path_factory: TempPathFactory) -> PathDistribution: # t (tmp_path / "setup.py").write_text("from setuptools import setup; setup()") toml = '[build-system]\nrequires=["setuptools", "wheel"]\nbuild-backend = "setuptools.build_meta"' (tmp_path / "pyproject.toml").write_text(toml) - frontend = SubprocessFrontend(*SubprocessFrontend.create_args_from_folder(tmp_path)[:-1]) - meta = tmp_path / "meta" + return tmp_path + + [email protected](scope="session") +def pkg_with_extras(pkg_with_extras_project: Path) -> PathDistribution: # type: ignore[no-any-unimported] + frontend = SubprocessFrontend(*SubprocessFrontend.create_args_from_folder(pkg_with_extras_project)[:-1]) + meta = pkg_with_extras_project / "meta" result = frontend.prepare_metadata_for_build_wheel(meta) return Distribution.at(result.metadata) def test_load_dependency_no_extra(pkg_with_extras: PathDistribution) -> None: # type: ignore[no-any-unimported] - result = Pep517VirtualEnvPackage.discover_package_dependencies(pkg_with_extras, set()) + result = Pep517VirtualEnvPackage.dependencies_with_extras([Requirement(i) for i in pkg_with_extras.requires], set()) for left, right in zip_longest(result, (Requirement("appdirs>=1.4.3"), Requirement("colorama>=0.4.3"))): assert isinstance(right, Requirement) assert str(left) == str(right) @@ -79,7 +85,9 @@ def test_load_dependency_no_extra(pkg_with_extras: PathDistribution) -> None: # def test_load_dependency_many_extra(pkg_with_extras: PathDistribution) -> None: # type: ignore[no-any-unimported] py_ver = ".".join(str(i) for i in sys.version_info[0:2]) - result = Pep517VirtualEnvPackage.discover_package_dependencies(pkg_with_extras, {"docs", "testing"}) + result = Pep517VirtualEnvPackage.dependencies_with_extras( + [Requirement(i) for i in pkg_with_extras.requires], {"docs", "testing"} + ) exp = [ Requirement("appdirs>=1.4.3"), Requirement("colorama>=0.4.3"), @@ -91,3 +99,19 @@ def test_load_dependency_many_extra(pkg_with_extras: PathDistribution) -> None: for left, right in zip_longest(result, exp): assert isinstance(right, Requirement) assert str(left) == str(right) + + +def test_get_package_deps_different_extras(pkg_with_extras_project: Path, tox_project: ToxProjectCreator) -> None: + proj = tox_project({"tox.ini": "[testenv:a]\npackage=dev\nextras=docs\n[testenv:b]\npackage=sdist\nextras=format"}) + execute_calls = proj.patch_execute(lambda r: 0 if "install" in r.run_id else None) + result = proj.run("r", "--root", str(pkg_with_extras_project), "-e", "a,b") + result.assert_success() + installs = { + i[0][0].conf.name: i[0][3].cmd[5:] + for i in execute_calls.call_args_list + if i[0][3].run_id.startswith("install_package_deps") + } + assert installs == { + "a": ["setuptools", "wheel", "appdirs>=1.4.3", "colorama>=0.4.3", "sphinx>=3", "sphinx-rtd-theme<1,>=0.4.3"], + "b": ["appdirs>=1.4.3", "colorama>=0.4.3", "black>=3", "flake8"], + }
tox4: not all extras are evaluated I have a tox ini with a `testenv` incl `extras = test` and a `testenv:coverage` incl. `extras=test, coverage`. The coverage env fails with `pytest-cov` missing - only in `tox4`. # reproduce ``` git clone [email protected]:morepath/more.cerberus.git cd more.cerburus tox4 -r ``` This only happens when running all envs - the error does not show when running `coverage` in isolation. Tested both with current tox pre and tox head. ``` coverage: remove tox env folder /home/jugmac00/Projects/more.cerberus/.tox/4/coverage coverage: install_package_deps> .tox/4/coverage/bin/python -I -m pip install 'setuptools>=40.8.0' wheel 'cerberus<2.0.0,>=1.3.2' 'morepath>=0.19' 'pytest>=2.9.1' pytest-remove-stale-bytecode webtest coverage: install_package> .tox/4/coverage/bin/python -I -m pip install --no-deps --force-reinstall --no-build-isolation -e /home/jugmac00/Projects/more.cerberus coverage: commands[0]> pytest --cov --cov-fail-under=100 ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --cov --cov-fail-under=100 inifile: /home/jugmac00/Projects/more.cerberus/setup.cfg rootdir: /home/jugmac00/Projects/more.cerberus coverage: exit 4 (0.20 seconds) /home/jugmac00/Projects/more.cerberus> pytest --cov --cov-fail-under=100 .pkg: _exit> python /home/jugmac00/opt/tox4/lib/python3.8/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ coverage: FAIL ✖ in 4.42 seconds ```
0.0
f17774fdd9fceea40564110bdeac7ce4b30ed677
[ "tests/tox_env/python/virtual_env/test_package.py::test_load_dependency_many_extra", "tests/tox_env/python/virtual_env/test_package.py::test_get_package_deps_different_extras", "tests/tox_env/python/virtual_env/test_package.py::test_load_dependency_no_extra" ]
[ "tests/tox_env/python/virtual_env/test_package.py::test_tox_ini_package_type_valid[sdist]", "tests/tox_env/python/virtual_env/test_package.py::test_tox_ini_package_type_valid[dev]", "tests/tox_env/python/virtual_env/test_package.py::test_tox_ini_package_type_valid[wheel]", "tests/tox_env/python/virtual_env/test_package.py::test_tox_ini_package_type_invalid" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-23 16:03:22+00:00
mit
6,071
tox-dev__tox-1889
diff --git a/docs/changelog/1831.bugfix.rst b/docs/changelog/1831.bugfix.rst new file mode 100644 index 00000000..f5ef2133 --- /dev/null +++ b/docs/changelog/1831.bugfix.rst @@ -0,0 +1,1 @@ +Support aliases in show config key specification (will print with the primary key) - by :user:`gaborbernat`. diff --git a/docs/changelog/1831.feature.rst b/docs/changelog/1831.feature.rst new file mode 100644 index 00000000..c8baa606 --- /dev/null +++ b/docs/changelog/1831.feature.rst @@ -0,0 +1,2 @@ +Support comments via the ``#`` character within the ini configuration (to force a literal ``#`` use ``\#``) - +by :user:`gaborbernat`. diff --git a/src/tox/config/loader/ini/__init__.py b/src/tox/config/loader/ini/__init__.py index 54eb51fa..a8867c02 100644 --- a/src/tox/config/loader/ini/__init__.py +++ b/src/tox/config/loader/ini/__init__.py @@ -1,4 +1,5 @@ import inspect +import re from concurrent.futures import Future from configparser import ConfigParser, SectionProxy from contextlib import contextmanager @@ -30,11 +31,21 @@ class IniLoader(StrConvert, Loader[str]): def load_raw(self, key: str, conf: Optional[Config], env_name: Optional[str]) -> str: value = self._section[key] - collapsed_newlines = value.replace("\\\r\n", "").replace("\\\n", "") # collapse explicit new-line escape + collapsed_newlines = value.replace("\r", "").replace("\\\n", "") # collapse explicit new-line escape + # strip comments + strip_comments = "\n".join( + no_comment + for no_comment in ( + re.sub(r"(\s)*(?<!\\)#.*", "", line) + for line in collapsed_newlines.split("\n") + if not line.startswith("#") + ) + if no_comment.strip() + ) if conf is None: # conf is None when we're loading the global tox configuration file for the CLI - factor_filtered = collapsed_newlines # we don't support factor and replace functionality there + factor_filtered = strip_comments # we don't support factor and replace functionality there else: - factor_filtered = filter_for_env(collapsed_newlines, env_name) # select matching factors + factor_filtered = filter_for_env(strip_comments, env_name) # select matching factors return factor_filtered @contextmanager diff --git a/src/tox/config/sets.py b/src/tox/config/sets.py index 6e31a664..2cd735b9 100644 --- a/src/tox/config/sets.py +++ b/src/tox/config/sets.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from pathlib import Path from typing import ( TYPE_CHECKING, @@ -36,7 +35,8 @@ class ConfigSet: self._conf = conf self.loaders: List[Loader[Any]] = [] self._defined: Dict[str, ConfigDefinition[Any]] = {} - self._keys: Dict[str, None] = OrderedDict() + self._keys: Dict[str, None] = {} + self._alias: Dict[str, str] = {} def add_config( self, @@ -76,6 +76,8 @@ class ConfigSet: raise ValueError(f"config {key} already defined") else: self._keys[key] = None + for item in keys: + self._alias[item] = key for key in keys: self._defined[key] = definition return definition @@ -101,6 +103,9 @@ class ConfigSet: def __iter__(self) -> Iterator[str]: return iter(self._keys.keys()) + def __contains__(self, item: str) -> bool: + return item in self._alias + def unused(self) -> List[str]: """Return a list of keys present in the config source but not used""" found: Set[str] = set() @@ -109,6 +114,9 @@ class ConfigSet: found -= self._defined.keys() return list(sorted(found)) + def primary_key(self, key: str) -> str: + return self._alias[key] + class CoreConfigSet(ConfigSet): def __init__(self, conf: "Config", root: Path) -> None: diff --git a/src/tox/session/cmd/show_config.py b/src/tox/session/cmd/show_config.py index 3711866f..934b5038 100644 --- a/src/tox/session/cmd/show_config.py +++ b/src/tox/session/cmd/show_config.py @@ -99,6 +99,7 @@ def print_conf(is_colored: bool, conf: ConfigSet, keys: Iterable[str]) -> None: for key in keys if keys else conf: if key not in conf: continue + key = conf.primary_key(key) try: value = conf[key] as_str, multi_line = stringify(value)
tox-dev/tox
8cbce69895511e989ed3677c2fb953005701bcd0
diff --git a/tests/config/loader/ini/test_ini_loader.py b/tests/config/loader/ini/test_ini_loader.py index f2fb13d8..d75dfe75 100644 --- a/tests/config/loader/ini/test_ini_loader.py +++ b/tests/config/loader/ini/test_ini_loader.py @@ -38,3 +38,21 @@ def test_ini_loader_raw_strip_escaped_newline(mk_ini_conf: Callable[[str], Confi loader = IniLoader("tox", mk_ini_conf(f"[tox]{sep}a=b\\{sep} c"), []) result = loader.load(key="a", of_type=str, conf=None, env_name=None, chain=[], kwargs={}) assert result == "bc" + + [email protected]( + ["case", "result"], + [ + ("# a", ""), + ("#", ""), + ("a # w", "a"), + ("a\t# w", "a"), + ("a# w", "a"), + ("a\\# w", "a\\# w"), + ("#a\n b # w\n w", "b\nw"), + ], +) +def test_ini_loader_strip_comments(mk_ini_conf: Callable[[str], ConfigParser], case: str, result: str) -> None: + loader = IniLoader("tox", mk_ini_conf(f"[tox]\na={case}"), []) + outcome = loader.load(key="a", of_type=str, conf=None, env_name=None, chain=[], kwargs={}) + assert outcome == result diff --git a/tests/session/cmd/test_show_config.py b/tests/session/cmd/test_show_config.py index 1cd3fcda..c0232d40 100644 --- a/tests/session/cmd/test_show_config.py +++ b/tests/session/cmd/test_show_config.py @@ -141,3 +141,9 @@ def test_show_config_select_only(tox_project: ToxProjectCreator) -> None: parser.read_string(result.out) sections = set(parser.sections()) assert sections == {"testenv:.pkg", "testenv:b"} + + +def test_show_config_alias(tox_project: ToxProjectCreator) -> None: + outcome = tox_project({"tox.ini": ""}).run("c", "-e", "py", "-k", "setenv") + outcome.assert_success() + assert "set_env = " in outcome.out
pass_env does not support comments Comments can be used to comment reason for setting values, see example in ``tox4 c -e py39-core`` of ansible-lint. Perhaps within the ini file we should always remove trailing comments on every type of input.
0.0
8cbce69895511e989ed3677c2fb953005701bcd0
[ "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[#-]", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[a", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[a\\t#", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[#", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[#a\\n", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[a#", "tests/session/cmd/test_show_config.py::test_show_config_alias" ]
[ "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_raw_strip_escaped_newline[\\r\\n]", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_keys", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_has_section", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_strip_comments[a\\\\#", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_repr", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_raw", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_has_no_section", "tests/config/loader/ini/test_ini_loader.py::test_ini_loader_raw_strip_escaped_newline[\\n]", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[True]", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_skip", "tests/session/cmd/test_show_config.py::test_show_config_unused", "tests/session/cmd/test_show_config.py::test_show_config_commands", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[False]", "tests/session/cmd/test_show_config.py::test_show_config_filter_keys", "tests/session/cmd/test_show_config.py::test_show_config_default_run_env", "tests/session/cmd/test_show_config.py::test_show_config_select_only", "tests/session/cmd/test_show_config.py::test_show_config_exception" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-31 09:47:26+00:00
mit
6,072
tox-dev__tox-1940
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 1e085ba7..55dd6d1b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -4,6 +4,7 @@ Alexander Loechel Alexander Schepanovski Alexandre Conrad Allan Feldman +Andrey Bienkowski Andrii Soldatenko Andrzej Klajnert Anthon van der Neuth diff --git a/docs/changelog/1921.feature.rst b/docs/changelog/1921.feature.rst new file mode 100644 index 00000000..64ea8c15 --- /dev/null +++ b/docs/changelog/1921.feature.rst @@ -0,0 +1,6 @@ +tox can now be invoked with a new ``--no-provision`` flag that prevents provision, +if :conf:`requires` or :conf:`minversion` are not satisfied, +tox will fail; +if a path is specified as an argument to the flag +(e.g. as ``tox --no-provision missing.json``) and provision is prevented, +provision metadata are written as JSON to that path - by :user:`hroncok` diff --git a/docs/config.rst b/docs/config.rst index 01bc9b7d..31e96331 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -38,6 +38,11 @@ Global settings are defined under the ``tox`` section as: than this the tool will create an environment and provision it with a version of tox that satisfies this under :conf:`provision_tox_env`. + .. versionchanged:: 3.23.0 + + When tox is invoked with the ``--no-provision`` flag, + the provision won't be attempted, tox will fail instead. + .. conf:: requires ^ LIST of PEP-508 .. versionadded:: 3.2.0 @@ -54,6 +59,11 @@ Global settings are defined under the ``tox`` section as: requires = tox-pipenv setuptools >= 30.0.0 + .. versionchanged:: 3.23.0 + + When tox is invoked with the ``--no-provision`` flag, + the provision won't be attempted, tox will fail instead. + .. conf:: provision_tox_env ^ string ^ .tox .. versionadded:: 3.8.0 @@ -61,6 +71,11 @@ Global settings are defined under the ``tox`` section as: Name of the virtual environment used to provision a tox having all dependencies specified inside :conf:`requires` and :conf:`minversion`. + .. versionchanged:: 3.23.0 + + When tox is invoked with the ``--no-provision`` flag, + the provision won't be attempted, tox will fail instead. + .. conf:: toxworkdir ^ PATH ^ {toxinidir}/.tox Directory for tox to generate its environments into, will be created if it does not exist. diff --git a/src/tox/config/__init__.py b/src/tox/config/__init__.py index 10bc9bef..278d4b2b 100644 --- a/src/tox/config/__init__.py +++ b/src/tox/config/__init__.py @@ -1,7 +1,9 @@ from __future__ import print_function import argparse +import io import itertools +import json import os import random import re @@ -302,7 +304,7 @@ def parseconfig(args, plugins=()): def get_py_project_toml(path): - with open(str(path)) as file_handler: + with io.open(str(path), encoding="UTF-8") as file_handler: config_data = toml.load(file_handler) return config_data @@ -572,6 +574,16 @@ def tox_addoption(parser): action="store_true", help="override alwayscopy setting to True in all envs", ) + parser.add_argument( + "--no-provision", + action="store", + nargs="?", + default=False, + const=True, + metavar="REQUIRES_JSON", + help="do not perform provision, but fail and if a path was provided " + "write provision metadata as JSON to it", + ) cli_skip_missing_interpreter(parser) parser.add_argument("--workdir", metavar="PATH", help="tox working directory") @@ -1318,8 +1330,8 @@ class ParseIni(object): # raise on unknown args self.config._parser.parse_cli(args=self.config.args, strict=True) - @staticmethod - def ensure_requires_satisfied(config, requires, min_version): + @classmethod + def ensure_requires_satisfied(cls, config, requires, min_version): missing_requirements = [] failed_to_parse = False deps = [] @@ -1346,12 +1358,33 @@ class ParseIni(object): missing_requirements.append(str(requirements.Requirement(require))) if failed_to_parse: raise tox.exception.BadRequirement() + if config.option.no_provision and missing_requirements: + msg = "provisioning explicitly disabled within {}, but missing {}" + if config.option.no_provision is not True: # it's a path + msg += " and wrote to {}" + cls.write_requires_to_json_file(config) + raise tox.exception.Error( + msg.format(sys.executable, missing_requirements, config.option.no_provision) + ) if WITHIN_PROVISION and missing_requirements: msg = "break infinite loop provisioning within {} missing {}" raise tox.exception.Error(msg.format(sys.executable, missing_requirements)) config.run_provision = bool(len(missing_requirements)) return deps + @staticmethod + def write_requires_to_json_file(config): + requires_dict = { + "minversion": config.minversion, + "requires": config.requires, + } + try: + with open(config.option.no_provision, "w", encoding="utf-8") as outfile: + json.dump(requires_dict, outfile, indent=4) + except TypeError: # Python 2 + with open(config.option.no_provision, "w") as outfile: + json.dump(requires_dict, outfile, indent=4, encoding="utf-8") + def parse_build_isolation(self, config, reader): config.isolated_build = reader.getbool("isolated_build", False) config.isolated_build_env = reader.getstring("isolated_build_env", ".package")
tox-dev/tox
a586b2a9d26c08e4dcdf4171ebae8079f5707e45
diff --git a/src/tox/_pytestplugin.py b/src/tox/_pytestplugin.py index c9176348..d0c87033 100644 --- a/src/tox/_pytestplugin.py +++ b/src/tox/_pytestplugin.py @@ -491,7 +491,14 @@ def create_files(base, filedefs): create_files(base.ensure(key, dir=1), value) elif isinstance(value, six.string_types): s = textwrap.dedent(value) - base.join(key).write(s) + + if not isinstance(s, six.text_type): + if not isinstance(s, six.binary_type): + s = str(s) + else: + s = six.ensure_text(s) + + base.join(key).write_text(s, encoding="UTF-8") @pytest.fixture() diff --git a/tests/unit/config/test_config.py b/tests/unit/config/test_config.py index fe11224c..b4bd24fb 100644 --- a/tests/unit/config/test_config.py +++ b/tests/unit/config/test_config.py @@ -1,3 +1,4 @@ +# coding=utf-8 import os import re import sys @@ -3556,7 +3557,10 @@ def test_config_via_pyproject_legacy(initproj): initproj( "config_via_pyproject_legacy-0.5", filedefs={ - "pyproject.toml": ''' + "pyproject.toml": u''' + [project] + description = "Factory ⸻ A code generator 🏭" + authors = [{name = "Łukasz Langa"}] [tool.tox] legacy_tox_ini = """ [tox] diff --git a/tests/unit/config/test_config_parallel.py b/tests/unit/config/test_config_parallel.py index 785b7710..0e42a2c5 100644 --- a/tests/unit/config/test_config_parallel.py +++ b/tests/unit/config/test_config_parallel.py @@ -38,7 +38,7 @@ def test_parallel_number_negative(newconfig, capsys): assert "value must be positive" in err -def test_depends(newconfig, capsys): +def test_depends(newconfig): config = newconfig( """\ [tox] @@ -49,7 +49,7 @@ def test_depends(newconfig, capsys): assert config.envconfigs["py"].depends == ("py37", "py36") -def test_depends_multi_row_facotr(newconfig, capsys): +def test_depends_multi_row_facotr(newconfig): config = newconfig( """\ [tox] @@ -61,7 +61,7 @@ def test_depends_multi_row_facotr(newconfig, capsys): assert config.envconfigs["py"].depends == ("py37", "py36-a", "py36-b") -def test_depends_factor(newconfig, capsys): +def test_depends_factor(newconfig): config = newconfig( """\ [tox] diff --git a/tests/unit/session/test_provision.py b/tests/unit/session/test_provision.py index cb7bd9b5..cf2ded10 100644 --- a/tests/unit/session/test_provision.py +++ b/tests/unit/session/test_provision.py @@ -1,5 +1,6 @@ from __future__ import absolute_import, unicode_literals +import json import os import shutil import subprocess @@ -185,6 +186,99 @@ def test_provision_cli_args_not_ignored_if_provision_false(cmd, initproj): result.assert_fail(is_run_test_env=False) +parametrize_json_path = pytest.mark.parametrize("json_path", [None, "missing.json"]) + + +@parametrize_json_path +def test_provision_does_not_fail_with_no_provision_no_reason(cmd, initproj, json_path): + p = initproj("test-0.1", {"tox.ini": "[tox]"}) + result = cmd("--no-provision", *([json_path] if json_path else [])) + result.assert_success(is_run_test_env=True) + assert not (p / "missing.json").exists() + + +@parametrize_json_path +def test_provision_fails_with_no_provision_next_tox(cmd, initproj, next_tox_major, json_path): + p = initproj( + "test-0.1", + { + "tox.ini": """\ + [tox] + minversion = {} + """.format( + next_tox_major, + ) + }, + ) + result = cmd("--no-provision", *([json_path] if json_path else [])) + result.assert_fail(is_run_test_env=False) + if json_path: + missing = json.loads((p / json_path).read_text("utf-8")) + assert missing["minversion"] == next_tox_major + + +@parametrize_json_path +def test_provision_fails_with_no_provision_missing_requires(cmd, initproj, json_path): + p = initproj( + "test-0.1", + { + "tox.ini": """\ + [tox] + requires = + virtualenv > 99999999 + """ + }, + ) + result = cmd("--no-provision", *([json_path] if json_path else [])) + result.assert_fail(is_run_test_env=False) + if json_path: + missing = json.loads((p / json_path).read_text("utf-8")) + assert missing["requires"] == ["virtualenv > 99999999"] + + +@parametrize_json_path +def test_provision_does_not_fail_with_satisfied_requires(cmd, initproj, next_tox_major, json_path): + p = initproj( + "test-0.1", + { + "tox.ini": """\ + [tox] + minversion = 0 + requires = + setuptools > 2 + pip > 3 + """ + }, + ) + result = cmd("--no-provision", *([json_path] if json_path else [])) + result.assert_success(is_run_test_env=True) + assert not (p / "missing.json").exists() + + +@parametrize_json_path +def test_provision_fails_with_no_provision_combined(cmd, initproj, next_tox_major, json_path): + p = initproj( + "test-0.1", + { + "tox.ini": """\ + [tox] + minversion = {} + requires = + setuptools > 2 + pip > 3 + """.format( + next_tox_major, + ) + }, + ) + result = cmd("--no-provision", *([json_path] if json_path else [])) + result.assert_fail(is_run_test_env=False) + if json_path: + missing = json.loads((p / json_path).read_text("utf-8")) + assert missing["minversion"] == next_tox_major + assert missing["requires"] == ["setuptools > 2", "pip > 3"] + + @pytest.fixture(scope="session") def wheel(tmp_path_factory): """create a wheel for a project"""
Possible UnicodeError caused by missing encoding="utf-8" https://github.com/tox-dev/tox/blob/555f3f13b18da1470b6518be654e3e4e2fdec654/src/tox/config/__init__.py#L304-L306 toml must be encoded by UTF-8. Please add `encoding="utf-8"` here. It may cause UnicodeDecodeError when pyproject.toml contains non-ASCII character and locale encoding is not UTF-8 (e.g. Windows). https://github.com/tox-dev/tox/blob/555f3f13b18da1470b6518be654e3e4e2fdec654/src/tox/util/stdlib.py#L52-L55 On Windows, stdout is UTF-8 encoded when it is console (e.g. _WinConsoleIO), but the default encoding of TemporaryFile() is legacy encoding. So UTF-8 is better encoding for this purpose. This is not a real bug because this function is used only here: https://github.com/tox-dev/tox/blob/cfe38bb853ff8573817c640a158b87eaad5b6e01/src/tox/session/__init__.py#L54
0.0
a586b2a9d26c08e4dcdf4171ebae8079f5707e45
[ "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_combined[missing.json]", "tests/unit/session/test_provision.py::test_provision_does_not_fail_with_no_provision_no_reason[missing.json]", "tests/unit/session/test_provision.py::test_provision_does_not_fail_with_satisfied_requires[None]", "tests/unit/session/test_provision.py::test_provision_does_not_fail_with_no_provision_no_reason[None]", "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_missing_requires[missing.json]", "tests/unit/session/test_provision.py::test_provision_does_not_fail_with_satisfied_requires[missing.json]", "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_next_tox[missing.json]" ]
[ "tests/unit/config/test_config.py::TestGetcontextname::test_hudson_legacy", "tests/unit/config/test_config.py::TestGetcontextname::test_jenkins", "tests/unit/config/test_config.py::TestGetcontextname::test_blank", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults_changed_dir", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults_distshare", "tests/unit/config/test_config.py::TestConfigPackage::test_project_paths", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep[:]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep[;]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_regex", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_replace[\\\\\\\\]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_pathsep_regex", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_replace[\\\\]", "tests/unit/config/test_config.py::TestVenvConfig::test_force_dep_with_url", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually", "tests/unit/config/test_config.py::TestVenvConfig::test_suicide_interrupt_terminate_timeout_set_manually", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually_setup_cfg", "tests/unit/config/test_config.py::TestVenvConfig::test_process_deps", "tests/unit/config/test_config.py::TestVenvConfig::test_config_parsing_multienv", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually_with_substitutions", "tests/unit/config/test_config.py::TestVenvConfig::test_force_dep_version", "tests/unit/config/test_config.py::TestVenvConfig::test_config_parsing_minimal", "tests/unit/config/test_config.py::TestVenvConfig::test_is_same_dep", "tests/unit/config/test_config.py::TestGlobalOptions::test_no_implicit_venv_from_cli_with_envlist", "tests/unit/config/test_config.py::TestGlobalOptions::test_notest", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_false", "tests/unit/config/test_config.py::TestGlobalOptions::test_sdist_specification", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_overrides_true", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args2-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args0-0]", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_multiline", "tests/unit/config/test_config.py::TestGlobalOptions::test_env_selection_expanded_envlist", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_default", "tests/unit/config/test_config.py::TestGlobalOptions::test_py_venv", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args3-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_correct_basepython_chosen_from_default_factors", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_true", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args1-1]", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_not_specified", "tests/unit/config/test_config.py::TestGlobalOptions::test_defaultenv_commandline", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_expansion", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_context", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args2-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args0-0]", "tests/unit/config/test_config.py::TestGlobalOptions::test_defaultenv_partial_override", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_cross_product", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_no_arg", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args3-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args4-3]", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args4-3]", "tests/unit/config/test_config.py::TestGlobalOptions::test_env_selection_with_section_name", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_global", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_overrides_false", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args1-1]", "tests/unit/config/test_config.py::TestIniParserPrefix::test_other_section_substitution", "tests/unit/config/test_config.py::TestIniParserPrefix::test_fallback_sections", "tests/unit/config/test_config.py::TestIniParserPrefix::test_basic_section_access", "tests/unit/config/test_config.py::TestIniParserPrefix::test_value_matches_prefixed_section_substitution", "tests/unit/config/test_config.py::TestIniParserPrefix::test_value_doesn_match_prefixed_section_substitution", "tests/unit/config/test_config.py::TestConfigTestEnv::test_recursive_substitution_cycle_fails", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_section", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_in_boolean", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[linux2]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors_conflict_lying_name", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_ops", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_in_setenv", "tests/unit/config/test_config.py::TestConfigTestEnv::test_sitepackages_switch", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_setting", "tests/unit/config/test_config.py::TestConfigTestEnv::test_multilevel_substitution", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist1-deps1]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_rewrite_simple_posargs", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_positional", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_substitutions", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_noargs_issue240", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy3]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[jython]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_period_in_factor", "tests/unit/config/test_config.py::TestConfigTestEnv::test_ignore_errors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_specific_command_overrides", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_rewrite_posargs", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_groups_touch", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[win32]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_posargs_backslashed_or_quoted", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envconfigs_based_on_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_allowlist_externals", "tests/unit/config/test_config.py::TestConfigTestEnv::test_commentchars_issue33", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue515", "tests/unit/config/test_config.py::TestConfigTestEnv::test_regression_test_issue_706[envlist0]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_glob_from_global_env", "tests/unit/config/test_config.py::TestConfigTestEnv::test_changedir", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[linux2]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_no_spinner", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_nested_env_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir", "tests/unit/config/test_config.py::TestConfigTestEnv::test_do_not_substitute_more_than_needed", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue246", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_double", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_must_contain_packages", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_substitutions_other_section", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_from_global_env", "tests/unit/config/test_config.py::TestConfigTestEnv::test_installpkg_tops_develop", "tests/unit/config/test_config.py::TestConfigTestEnv::test_single_value_from_other_secton", "tests/unit/config/test_config.py::TestConfigTestEnv::test_changedir_override", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_use_not_checked", "tests/unit/config/test_config.py::TestConfigTestEnv::test_pip_pre_cmdline_override", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_support_curly_braces", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors_conflict", "tests/unit/config/test_config.py::TestConfigTestEnv::test_simple", "tests/unit/config/test_config.py::TestConfigTestEnv::test_pip_pre", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_expansion", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[win32]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_with_factor", "tests/unit/config/test_config.py::TestConfigTestEnv::test_ignore_outcome", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_error", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist0-deps0]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_curly_braces_in_setenv", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_substitution_with_spaces", "tests/unit/config/test_config.py::TestCommandParser::test_command_with_split_line_in_subst_arguments", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_with_complex_word_set", "tests/unit/config/test_config.py::TestCommandParser::test_command_parsing_for_issue_10", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_multiple_words", "tests/unit/config/test_config.py::TestCommandParser::test_commands_with_backslash", "tests/unit/config/test_config.py::TestCommandParser::test_command_with_runs_of_whitespace", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_word", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_posargs", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_command_contains_hash", "tests/unit/config/test_config.py::TestIniParser::test_missing_env_sub_populates_missing_subs", "tests/unit/config/test_config.py::TestIniParser::test_getbool", "tests/unit/config/test_config.py::TestIniParser::test_value_doesn_match_section_substitution", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_quoting_in_command", "tests/unit/config/test_config.py::TestIniParser::test_getpath", "tests/unit/config/test_config.py::TestIniParser::test_expand_section_name", "tests/unit/config/test_config.py::TestIniParser::test_substitution_empty", "tests/unit/config/test_config.py::TestIniParser::test_getstring_other_section_substitution", "tests/unit/config/test_config.py::TestIniParser::test_missing_env_sub_raises_config_error_in_non_testenv", "tests/unit/config/test_config.py::TestIniParser::test_getstring_single", "tests/unit/config/test_config.py::TestIniParser::test_substitution_with_multiple_words", "tests/unit/config/test_config.py::TestIniParser::test_getlist", "tests/unit/config/test_config.py::TestIniParser::test_positional_arguments_are_only_replaced_when_standing_alone", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_multiline", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_positional_substitution", "tests/unit/config/test_config.py::TestIniParser::test_value_matches_section_substitution", "tests/unit/config/test_config.py::TestIniParser::test_getargv", "tests/unit/config/test_config.py::TestIniParser::test_getdict", "tests/unit/config/test_config.py::TestIniParser::test_posargs_are_added_escaped_issue310", "tests/unit/config/test_config.py::TestIniParser::test_substitution_colon_prefix", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_posargs_with_quotes", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_quoted_posargs", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_windows_escaping", "tests/unit/config/test_config.py::TestIniParser::test_getstring_substitution", "tests/unit/config/test_config.py::TestIniParser::test_normal_env_sub_works", "tests/unit/config/test_config.py::TestIniParser::test_missing_substitution", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_comment_after_command", "tests/unit/config/test_config.py::TestIniParser::test_getstring_fallback_sections", "tests/unit/config/test_config.py::TestIniParser::test_argvlist", "tests/unit/config/test_config.py::TestIniParser::test_getstring_environment_substitution_with_default", "tests/unit/config/test_config.py::TestCmdInvocation::test_no_tox_ini", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_no_plugins", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_simple", "tests/unit/config/test_config.py::TestCmdInvocation::test_help", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_with_normal_plugin", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_with_fileless_module", "tests/unit/config/test_config.py::TestHashseedOption::test_setenv", "tests/unit/config/test_config.py::TestHashseedOption::test_noset", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_integer", "tests/unit/config/test_config.py::TestHashseedOption::test_noset_with_setenv", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_string", "tests/unit/config/test_config.py::TestHashseedOption::test_one_random_hashseed", "tests/unit/config/test_config.py::TestHashseedOption::test_default", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_empty_string", "tests/unit/config/test_config.py::TestHashseedOption::test_setenv_in_one_testenv", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_no_argument", "tests/unit/config/test_config.py::test_get_homedir", "tests/unit/config/test_config.py::test_env_spec[-e", "tests/unit/config/test_config.py::test_config_no_version_data_in__name", "tests/unit/config/test_config.py::test_config_bad_pyproject_specified", "tests/unit/config/test_config.py::test_interactive_available", "tests/unit/config/test_config.py::test_config_via_pyproject_legacy", "tests/unit/config/test_config.py::test_provision_tox_env_cannot_be_in_envlist", "tests/unit/config/test_config.py::test_posargs_relative_changedir", "tests/unit/config/test_config.py::test_overwrite_skip_install_override", "tests/unit/config/test_config.py::test_interactive", "tests/unit/config/test_config.py::test_config_bad_config_type_specified", "tests/unit/config/test_config.py::test_config_file_not_required_with_devenv", "tests/unit/config/test_config.py::test_config_current_py", "tests/unit/config/test_config.py::test_isolated_build_ignores[deps-crazy-default0]", "tests/unit/config/test_config.py::test_interactive_na", "tests/unit/config/test_config.py::test_isolated_build_overrides", "tests/unit/config/test_config.py::test_config_setup_cfg_no_tox_section", "tests/unit/config/test_config.py::test_isolated_build_env_cannot_be_in_envlist", "tests/unit/config/test_config.py::test_isolated_build_ignores[sitepackages-True-False]", "tests/unit/config/test_config.py::TestParseconfig::test_search_parents", "tests/unit/config/test_config.py::TestParseconfig::test_workdir_gets_resolved", "tests/unit/config/test_config.py::TestParseconfig::test_explicit_config_path", "tests/unit/config/test_config.py::TestParseEnv::test_parse_recreate", "tests/unit/config/test_config.py::TestIndexServer::test_indexserver", "tests/unit/config/test_config.py::TestIndexServer::test_multiple_homedir_relative_local_indexservers", "tests/unit/config/test_config.py::TestIndexServer::test_parse_indexserver", "tests/unit/config/test_config.py::TestConfigPlatform::test_platform_install_command", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[lin]", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[osx]", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_rex", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[win]", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_section_and_posargs_substitution", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs_with_spaced_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_multiline", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_global", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_multi_env", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_same_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_setenv", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_simple", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs_with_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_posargs", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_unnecessary", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_complex", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_regression_issue595", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_inherit", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_posargs_with_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_default_escape", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution", "tests/unit/config/test_config.py::TestSetenv::test_setenv_overrides", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_subst_twice", "tests/unit/config/test_config.py::TestSetenv::test_setenv_ordering_1", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_without_default", "tests/unit/config/test_config.py::TestSetenv::test_setenv_uses_os_environ", "tests/unit/config/test_config.py::TestSetenv::test_setenv_comment", "tests/unit/config/test_config.py::TestSetenv::test_getdict_lazy", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[None-False]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_with_default", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[\\nMAGIC", "tests/unit/config/test_config.py::TestSetenv::test_setenv_uses_other_setenv", "tests/unit/config/test_config.py::TestSetenv::test_setenv_default_os_environ", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_with_default_nested", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[MAGIC=yes-True]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[\\n-False]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[#MAGIC", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_mixed", "tests/unit/config/test_config.py::TestSetenv::test_setenv_with_envdir_and_basepython", "tests/unit/config/test_config.py::TestSetenv::test_getdict_lazy_update", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_subst_issue294", "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_missing_requires[None]", "tests/unit/session/test_provision.py::test_provision_basepython_local", "tests/unit/session/test_provision.py::test_provision_config_empty_minversion_and_requires", "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_next_tox[None]", "tests/unit/session/test_provision.py::test_provision_cli_args_not_ignored_if_provision_false", "tests/unit/session/test_provision.py::test_provision_requirement_with_environment_marker", "tests/unit/session/test_provision.py::test_provision_cli_args_ignore", "tests/unit/session/test_provision.py::test_provision_non_canonical_dep", "tests/unit/session/test_provision.py::test_provision_config_has_minversion_and_requires", "tests/unit/session/test_provision.py::test_provision_basepython_global_only", "tests/unit/session/test_provision.py::test_provision_tox_change_name", "tests/unit/session/test_provision.py::test_provision_bad_requires", "tests/unit/session/test_provision.py::test_provision_fails_with_no_provision_combined[None]", "tests/unit/session/test_provision.py::test_provision_min_version_is_requires", "tests/unit/config/test_config_parallel.py::test_parallel_number_negative", "tests/unit/config/test_config_parallel.py::test_depends", "tests/unit/config/test_config_parallel.py::test_parallel_all", "tests/unit/config/test_config_parallel.py::test_parallel_number", "tests/unit/config/test_config_parallel.py::test_depends_multi_row_facotr", "tests/unit/config/test_config_parallel.py::test_depends_factor", "tests/unit/config/test_config_parallel.py::test_parallel_live_on", "tests/unit/config/test_config_parallel.py::test_parallel_auto", "tests/unit/config/test_config_parallel.py::test_parallel_default" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-01 23:04:15+00:00
mit
6,073
tox-dev__tox-1954
diff --git a/docs/changelog/1928.feature.rst b/docs/changelog/1928.feature.rst new file mode 100644 index 00000000..1f53b09b --- /dev/null +++ b/docs/changelog/1928.feature.rst @@ -0,0 +1,2 @@ +Implemented ``[]`` substitution (alias for ``{posargs}``) - by +:user:`hexagonrecursion`. diff --git a/src/tox/config/loader/ini/replace.py b/src/tox/config/loader/ini/replace.py index 91d3c032..505519ce 100644 --- a/src/tox/config/loader/ini/replace.py +++ b/src/tox/config/loader/ini/replace.py @@ -26,10 +26,9 @@ def replace(conf: "Config", name: Optional[str], loader: "IniLoader", value: str # perform all non-escaped replaces start, end = 0, 0 while True: - start, end, match = find_replace_part(value, start, end) - if not match: + start, end, to_replace = find_replace_part(value, start, end) + if to_replace is None: break - to_replace = value[start + 1 : end] replaced = _replace_match(conf, name, loader, to_replace, chain.copy()) if replaced is None: # if we cannot replace, keep what was there, and continue looking for additional replaces following @@ -38,17 +37,39 @@ def replace(conf: "Config", name: Optional[str], loader: "IniLoader", value: str start = end = end + 1 continue new_value = value[:start] + replaced + value[end + 1 :] - start, end = 0, 0 # if we performed a replace start over + start, end = 0, 0 # if we performed a replacement start over if new_value == value: # if we're not making progress stop (circular reference?) break value = new_value # remove escape sequences value = value.replace("\\{", "{") value = value.replace("\\}", "}") + value = value.replace("\\[", "[") + value = value.replace("\\]", "]") return value -def find_replace_part(value: str, start: int, end: int) -> Tuple[int, int, bool]: +def find_replace_part(value: str, start: int, end: int) -> Tuple[int, int, Optional[str]]: + bracket_at = find_brackets(value, end) + if bracket_at != -1: + return bracket_at, bracket_at + 1, "posargs" # brackets is an alias for positional arguments + start, end, match = find_braces(value, start, end) + return start, end, (value[start + 1 : end] if match else None) + + +def find_brackets(value: str, end: int) -> int: + while True: + pos = value.find("[]", end) + if pos == -1: + break + if pos >= 1 and value[pos - 1] == "\\": # the opened bracket is escaped + end = pos + 1 + continue + break + return pos + + +def find_braces(value: str, start: int, end: int) -> Tuple[int, int, bool]: match = False while end != -1: end = value.find("}", end)
tox-dev/tox
11b150eaa0b43461910847092afa49a083851b98
diff --git a/tests/config/loader/ini/replace/test_replace_posargs.py b/tests/config/loader/ini/replace/test_replace_posargs.py index 20f4091f..d2ebed4b 100644 --- a/tests/config/loader/ini/replace/test_replace_posargs.py +++ b/tests/config/loader/ini/replace/test_replace_posargs.py @@ -5,23 +5,27 @@ import pytest from tests.config.loader.ini.replace.conftest import ReplaceOne -def test_replace_pos_args_none_sys_argv(replace_one: ReplaceOne) -> None: - result = replace_one("{posargs}", None) [email protected]("syntax", ["{posargs}", "[]"]) +def test_replace_pos_args_none_sys_argv(syntax: str, replace_one: ReplaceOne) -> None: + result = replace_one(syntax, None) assert result == "" -def test_replace_pos_args_empty_sys_argv(replace_one: ReplaceOne) -> None: - result = replace_one("{posargs}", []) [email protected]("syntax", ["{posargs}", "[]"]) +def test_replace_pos_args_empty_sys_argv(syntax: str, replace_one: ReplaceOne) -> None: + result = replace_one(syntax, []) assert result == "" -def test_replace_pos_args_extra_sys_argv(replace_one: ReplaceOne) -> None: - result = replace_one("{posargs}", [sys.executable, "magic"]) [email protected]("syntax", ["{posargs}", "[]"]) +def test_replace_pos_args_extra_sys_argv(syntax: str, replace_one: ReplaceOne) -> None: + result = replace_one(syntax, [sys.executable, "magic"]) assert result == f"{sys.executable} magic" -def test_replace_pos_args(replace_one: ReplaceOne) -> None: - result = replace_one("{posargs}", ["ok", "what", " yes "]) [email protected]("syntax", ["{posargs}", "[]"]) +def test_replace_pos_args(syntax: str, replace_one: ReplaceOne) -> None: + result = replace_one(syntax, ["ok", "what", " yes "]) quote = '"' if sys.platform == "win32" else "'" assert result == f"ok what {quote} yes {quote}" @@ -31,8 +35,8 @@ def test_replace_pos_args(replace_one: ReplaceOne) -> None: [ ("magic", "magic"), ("magic:colon", "magic:colon"), - ("magic\n b:c", "magic\nb:c"), # unescaped newline keeps the newline - ("magi\\\n c:d", "magic:d"), # escaped newline merges the lines + ("magic\n b:c", "magic\nb:c"), # an unescaped newline keeps the newline + ("magi\\\n c:d", "magic:d"), # an escaped newline merges the lines ("\\{a\\}", "{a}"), # escaped curly braces ], ) @@ -50,9 +54,24 @@ def test_replace_pos_args_default(replace_one: ReplaceOne, value: str, result: s "\\{posargs\\}", "{\\{posargs}", "{\\{posargs}{}", + "\\[]", + "[\\]", + "\\[\\]", ], ) def test_replace_pos_args_escaped(replace_one: ReplaceOne, value: str) -> None: result = replace_one(value, None) - outcome = value.replace("\\{", "{").replace("\\}", "}") + outcome = value.replace("\\", "") + assert result == outcome + + [email protected]( + ("value", "result"), + [ + ("[]-{posargs}", "foo-foo"), + ("{posargs}-[]", "foo-foo"), + ], +) +def test_replace_mixed_brackets_and_braces(replace_one: ReplaceOne, value: str, result: str) -> None: + outcome = replace_one(value, ["foo"]) assert result == outcome
tox 4 bracket posargs are missing as example i cut down the apipkg tox.ini to just ``` [testenv] deps=pytest commands=pytest [] ``` ran ``` $ tox4 py: install_deps> python -I -m pip install pytest .pkg: get_requires_for_build_wheel> python /home/rpfannsc/.local/lib/python3.9/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ .pkg: prepare_metadata_for_build_wheel> python /home/rpfannsc/.local/lib/python3.9/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ .pkg: get_requires_for_build_sdist> python /home/rpfannsc/.local/lib/python3.9/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ .pkg: build_sdist> python /home/rpfannsc/.local/lib/python3.9/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ py: install_package> python -I -m pip install --no-deps --force-reinstall /home/rpfannsc/Projects/pytest-dev/apipkg/.tox/4/.pkg/dist/apipkg-1.6.dev16+ge54efbf.d20210227.tar.gz py: commands[0]> pytest '[]' ERROR: file or directory not found: [] ========================================================================================= test session starts ========================================================================================== platform linux -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 apipkg full install version=1.6.dev16+ge54efbf.d20210227 rootdir: /home/rpfannsc/Projects/pytest-dev/apipkg collected 0 items ======================================================================================== no tests ran in 0.00s ========================================================================================= py: exit 4 (0.34 seconds) /home/rpfannsc/Projects/pytest-dev/apipkg> pytest '[]' pid=1183180 .pkg: _exit> python /home/rpfannsc/.local/lib/python3.9/site-packages/tox/util/pep517/backend.py True setuptools.build_meta __legacy__ py: FAIL code 4 (9.90=setup[9.57]+cmd[0.34] seconds) evaluation failed :( (10.00 seconds) ``` and ran ``` $ tox GLOB sdist-make: /home/rpfannsc/Projects/pytest-dev/apipkg/setup.py python create: /home/rpfannsc/Projects/pytest-dev/apipkg/.tox/python python installdeps: pytest python inst: /home/rpfannsc/Projects/pytest-dev/apipkg/.tox/.tmp/package/1/apipkg-1.6.dev16+ge54efbf.d20210227.zip python installed: apipkg @ file:///home/rpfannsc/Projects/pytest-dev/apipkg/.tox/.tmp/package/1/apipkg-1.6.dev16%2Bge54efbf.d20210227.zip,attrs==20.3.0,iniconfig==1.1.1,packaging==20.9,pluggy==0.13.1,py==1.10.0,pyparsing==2.4.7,pytest==6.2.2,toml==0.10.2 python run-test-pre: PYTHONHASHSEED='1155200767' python run-test: commands[0] | pytest ========================================================================================= test session starts ========================================================================================== platform linux -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 cachedir: .tox/python/.pytest_cache apipkg full install version=1.6.dev16+ge54efbf.d20210227 rootdir: /home/rpfannsc/Projects/pytest-dev/apipkg collected 42 items test_apipkg.py .......................................... [100%] ========================================================================================== 42 passed in 0.63s ========================================================================================== _______________________________________________________________________________________________ summary ________________________________________________________________________________________________ python: commands succeeded congratulations :) ``` and then ran ``` $ tox -- -k aliasmod GLOB sdist-make: /home/rpfannsc/Projects/pytest-dev/apipkg/setup.py python inst-nodeps: /home/rpfannsc/Projects/pytest-dev/apipkg/.tox/.tmp/package/1/apipkg-1.6.dev16+ge54efbf.d20210227.zip python installed: apipkg @ file:///home/rpfannsc/Projects/pytest-dev/apipkg/.tox/.tmp/package/1/apipkg-1.6.dev16%2Bge54efbf.d20210227.zip,attrs==20.3.0,iniconfig==1.1.1,packaging==20.9,pluggy==0.13.1,py==1.10.0,pyparsing==2.4.7,pytest==6.2.2,toml==0.10.2 python run-test-pre: PYTHONHASHSEED='1148858278' python run-test: commands[0] | pytest -k aliasmod ========================================================================================= test session starts ========================================================================================== platform linux -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 cachedir: .tox/python/.pytest_cache apipkg full install version=1.6.dev16+ge54efbf.d20210227 rootdir: /home/rpfannsc/Projects/pytest-dev/apipkg collected 42 items / 33 deselected / 9 selected test_apipkg.py ......... [100%] =================================================================================== 9 passed, 33 deselected in 0.19s =================================================================================== _______________________________________________________________________________________________ summary ________________________________________________________________________________________________ python: commands succeeded congratulations :) ```
0.0
11b150eaa0b43461910847092afa49a083851b98
[ "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_none_sys_argv[[]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_empty_sys_argv[[]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_extra_sys_argv[[]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args[[]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[\\\\[]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[[\\\\]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[\\\\[\\\\]]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_mixed_brackets_and_braces[[]-{posargs}-foo-foo]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_mixed_brackets_and_braces[{posargs}-[]-foo-foo]" ]
[ "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_none_sys_argv[{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_empty_sys_argv[{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_extra_sys_argv[{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args[{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_default[magic-magic]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_default[magic:colon-magic:colon]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_default[magic\\n", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_default[magi\\\\\\n", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_default[\\\\{a\\\\}-{a}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[\\\\{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[{posargs\\\\}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[\\\\{posargs\\\\}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[{\\\\{posargs}]", "tests/config/loader/ini/replace/test_replace_posargs.py::test_replace_pos_args_escaped[{\\\\{posargs}{}]" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-03-03 12:20:42+00:00
mit
6,074
tox-dev__tox-2131
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index e794efc5..14d9bbad 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -99,6 +99,7 @@ Philip Thiem Pierre-Jean Campigotto Pierre-Luc Tessier Gagné Prakhar Gurunani +Rahul Bangar Ronald Evers Ronny Pfannschmidt Ryuichi Ohori diff --git a/docs/changelog/2130.bugfix.rst b/docs/changelog/2130.bugfix.rst new file mode 100644 index 00000000..aac4524c --- /dev/null +++ b/docs/changelog/2130.bugfix.rst @@ -0,0 +1,1 @@ +``get_requires_for_build_sdist`` hook (PEP 517) is assumed to return an empty list if left unimplemented by the backend build system - by :user:`oczkoisse` diff --git a/src/tox/helper/build_requires.py b/src/tox/helper/build_requires.py index aafb258c..a91671c0 100644 --- a/src/tox/helper/build_requires.py +++ b/src/tox/helper/build_requires.py @@ -12,6 +12,13 @@ backend = __import__(backend_spec, fromlist=["_trash"]) if backend_obj: backend = getattr(backend, backend_obj) -for_build_requires = backend.get_requires_for_build_sdist(None) +try: + for_build_requires = backend.get_requires_for_build_sdist(None) +except AttributeError: + # PEP 517 states that get_requires_for_build_sdist is optional for a build + # backend object. When the backend object omits it, the default + # implementation must be equivalent to return [] + for_build_requires = [] + output = json.dumps(for_build_requires) print(output)
tox-dev/tox
a61a6b6bf8713f35e560a2449480a8ea5721bad7
diff --git a/tests/unit/package/builder/test_package_builder_isolated.py b/tests/unit/package/builder/test_package_builder_isolated.py index dd783d85..f05d8ae8 100644 --- a/tests/unit/package/builder/test_package_builder_isolated.py +++ b/tests/unit/package/builder/test_package_builder_isolated.py @@ -202,3 +202,71 @@ def test_isolated_build_script_args(tmp_path): # cannot import build_isolated because of its side effects script_path = os.path.join(os.path.dirname(tox.helper.__file__), "build_isolated.py") subprocess.check_call(("python", script_path, str(tmp_path), "setuptools.build_meta")) + + +def test_isolated_build_backend_missing_hook(initproj, cmd): + """Verify that tox works with a backend missing optional hooks + + PEP 517 allows backends to omit get_requires_for_build_sdist hook, in which + case a default implementation that returns an empty list should be assumed + instead of raising an error. + """ + name = "ensconsproj" + version = "0.1" + src_root = "src" + + initproj( + (name, version), + filedefs={ + "pyproject.toml": """ + [build-system] + requires = ["pytoml>=0.1", "enscons==0.26.0"] + build-backend = "enscons.api" + + [tool.enscons] + name = "{name}" + version = "{version}" + description = "Example enscons project" + license = "MIT" + packages = ["{name}"] + src_root = "{src_root}" + """.format( + name=name, version=version, src_root=src_root + ), + "tox.ini": """ + [tox] + isolated_build = true + """, + "SConstruct": """ + import enscons + + env = Environment( + tools=["default", "packaging", enscons.generate], + PACKAGE_METADATA=dict( + name = "{name}", + version = "{version}" + ), + WHEEL_TAG="py2.py3-none-any" + ) + + py_source = env.Glob("src/{name}/*.py") + + purelib = env.Whl("purelib", py_source, root="{src_root}") + whl = env.WhlFile(purelib) + + sdist = env.SDist(source=FindSourceFiles() + ["PKG-INFO"]) + env.NoClean(sdist) + env.Alias("sdist", sdist) + + develop = env.Command("#DEVELOP", enscons.egg_info_targets(env), enscons.develop) + env.Alias("develop", develop) + + env.Default(whl, sdist) + """.format( + name=name, version=version, src_root=src_root + ), + }, + ) + + result = cmd("--sdistonly", "-v", "-v", "-e", "py") + assert "scons: done building targets" in result.out, result.out
Isolated build with 'enscons' as backend build system fails I'm trying to use `tox` with `isolated_build` set to `true` and [`enscons`](https://github.com/dholth/enscons) as the backend build system. When `isolated_build` is not set (default is `false` I think), `tox` works fine. However, when `isolated_build` is set to `true`, the build fails with the following error: ``` action: .package, msg: get-build-requires cwd: C:\Users\banga\Projects\Personal\labeling-tool cmd: 'C:\Users\banga\Projects\Personal\labeling-tool\.tox\.package\Scripts\python' '.venv\Lib\site-packages\tox\helper\build_requires.py' enscons.api '' '' Traceback (most recent call last): File ".venv\Lib\site-packages\tox\helper\build_requires.py", line 15, in <module> for_build_requires = backend.get_requires_for_build_sdist(None) AttributeError: module 'enscons.api' has no attribute 'get_requires_for_build_sdist' ``` I might be wrong but I thought `get_requires_for_build_sdist` and `get_requires_for_build_wheel` were optional hooks in PEP 517 and should be assumed to return empty list if absent. The tox configuration in `pyproject.toml` is: ```toml [tool.tox] legacy_tox_ini = """ [tox] envlist = py37, py38, py39 isolated_build = true [testenv] deps = pytest commands = pytest """ ```
0.0
a61a6b6bf8713f35e560a2449480a8ea5721bad7
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_isolated_build_backend_missing_hook" ]
[ "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_requires", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_no_pyproject_toml", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_requires", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_backend_path_outside_root", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_build_system", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_no_backend", "tests/unit/package/builder/test_package_builder_isolated.py::test_package_isolated_toml_bad_backend_path" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-07-31 05:56:48+00:00
mit
6,075
tox-dev__tox-2146
diff --git a/docs/changelog/763.bugfix.rst b/docs/changelog/763.bugfix.rst new file mode 100644 index 00000000..88cc3e0b --- /dev/null +++ b/docs/changelog/763.bugfix.rst @@ -0,0 +1,1 @@ +Support ``#`` character in path for the tox project - by :user:`gaborbernat`. diff --git a/src/tox/config/loader/ini/__init__.py b/src/tox/config/loader/ini/__init__.py index 5822555e..55d67be3 100644 --- a/src/tox/config/loader/ini/__init__.py +++ b/src/tox/config/loader/ini/__init__.py @@ -29,8 +29,10 @@ class IniLoader(StrConvert, Loader[str]): super().__init__(overrides) def load_raw(self, key: str, conf: Optional["Config"], env_name: Optional[str]) -> str: - value = self._section[key] + return self.process_raw(conf, env_name, self._section[key]) + @staticmethod + def process_raw(conf: Optional["Config"], env_name: Optional[str], value: str) -> str: # strip comments elements: List[str] = [] for line in value.split("\n"): @@ -38,7 +40,6 @@ class IniLoader(StrConvert, Loader[str]): part = _COMMENTS.sub("", line) elements.append(part.replace("\\#", "#")) strip_comments = "\n".join(elements) - if conf is None: # conf is None when we're loading the global tox configuration file for the CLI factor_filtered = strip_comments # we don't support factor and replace functionality there else: diff --git a/src/tox/config/loader/ini/replace.py b/src/tox/config/loader/ini/replace.py index 3e9d193f..06facf61 100644 --- a/src/tox/config/loader/ini/replace.py +++ b/src/tox/config/loader/ini/replace.py @@ -120,9 +120,10 @@ def replace_reference( for src in _config_value_sources(settings["env"], settings["section"], current_env, conf, loader): try: if isinstance(src, SectionProxy): - return src[key] + return loader.process_raw(conf, current_env, src[key]) value = src.load(key, chain) as_str, _ = stringify(value) + as_str = as_str.replace("#", r"\#") # escape comment characters as these will be stripped return as_str except KeyError as exc: # if fails, keep trying maybe another source can satisfy exception = exc diff --git a/src/tox/config/loader/str_convert.py b/src/tox/config/loader/str_convert.py index 01a114e6..ba373af8 100644 --- a/src/tox/config/loader/str_convert.py +++ b/src/tox/config/loader/str_convert.py @@ -47,8 +47,10 @@ class StrConvert(Convert[str]): @staticmethod def to_command(value: str) -> Command: is_win = sys.platform == "win32" + value = value.replace(r"\#", "#") splitter = shlex.shlex(value, posix=not is_win) splitter.whitespace_split = True + splitter.commenters = "" # comments handled earlier, and the shlex does not know escaped comment characters args: List[str] = [] pos = 0 try: diff --git a/src/tox/config/set_env.py b/src/tox/config/set_env.py index ce836516..acfd52fa 100644 --- a/src/tox/config/set_env.py +++ b/src/tox/config/set_env.py @@ -41,6 +41,7 @@ class SetEnv: return self._materialized[item] raw = self._raw[item] result = self.replacer(raw, chain) # apply any replace options + result = result.replace(r"\#", "#") # unroll escaped comment with replacement self._materialized[item] = result self._raw.pop(item, None) # if the replace requires the env we may be called again, so allow pop to fail return result diff --git a/whitelist.txt b/whitelist.txt index c8163050..c5fd2f25 100644 --- a/whitelist.txt +++ b/whitelist.txt @@ -27,6 +27,7 @@ chdir cmd codec colorama +commenters conf configs conftest
tox-dev/tox
174fd08e7db7076e262b96e4a76db49b40fbc620
diff --git a/src/tox/pytest.py b/src/tox/pytest.py index 73123355..1516297c 100644 --- a/src/tox/pytest.py +++ b/src/tox/pytest.py @@ -370,7 +370,9 @@ class ToxRunOutcome: class ToxProjectCreator(Protocol): - def __call__(self, files: Dict[str, Any], base: Optional[Path] = None) -> ToxProject: # noqa: U100 + def __call__( + self, files: Dict[str, Any], base: Optional[Path] = None, prj_path: Optional[Path] = None # noqa: U100 + ) -> ToxProject: ... @@ -378,9 +380,9 @@ class ToxProjectCreator(Protocol): def init_fixture( tmp_path: Path, capfd: CaptureFixture, monkeypatch: MonkeyPatch, mocker: MockerFixture ) -> ToxProjectCreator: - def _init(files: Dict[str, Any], base: Optional[Path] = None) -> ToxProject: + def _init(files: Dict[str, Any], base: Optional[Path] = None, prj_path: Optional[Path] = None) -> ToxProject: """create tox projects""" - return ToxProject(files, base, tmp_path / "p", capfd, monkeypatch, mocker) + return ToxProject(files, base, prj_path or tmp_path / "p", capfd, monkeypatch, mocker) return _init # noqa diff --git a/tests/session/cmd/test_show_config.py b/tests/session/cmd/test_show_config.py index bfeec554..366766ff 100644 --- a/tests/session/cmd/test_show_config.py +++ b/tests/session/cmd/test_show_config.py @@ -1,6 +1,8 @@ import platform import sys from configparser import ConfigParser +from pathlib import Path +from textwrap import dedent from typing import Callable, Tuple import pytest @@ -155,3 +157,27 @@ def test_show_config_description_normalize(tox_project: ToxProjectCreator) -> No outcome = tox_project({"tox.ini": tox_ini}).run("c", "-e", "py", "-k", "description") outcome.assert_success() assert outcome.out == "[testenv:py]\ndescription = A magical pipe of this\n" + + +def test_show_config_ini_comment_path(tox_project: ToxProjectCreator, tmp_path: Path) -> None: + prj_path = tmp_path / "#magic" + prj_path.mkdir() + ini = """ + [testenv] + package = skip + set_env = + A=1 # comment + # more comment + commands = {envpython} -c 'import os; print(os.linesep.join(f"{k}={v}" for k, v in os.environ.items()))' + [testenv:py] + set_env = + {[testenv]set_env} + B = {tox_root} # just some comment + """ + project = tox_project({"tox.ini": dedent(ini)}, prj_path=prj_path) + result = project.run("r", "-e", "py") + result.assert_success() + a_line = next(i for i in result.out.splitlines() if i.startswith("A=")) # pragma: no branch # not found raises + assert a_line == "A=1" + b_line = next(i for i in result.out.splitlines() if i.startswith("B=")) # pragma: no branch # not found raises + assert b_line == f"B={prj_path}"
tox fails when running in a path containing a hash On Archlinux with 2.9.1, when trying to run it in a folder called `test#foo`, I get: ``` $ tox -e flake8 flake8 create: /home/florian/proj/qutebrowser/test#foo/.tox/flake8 flake8 installdeps: -r/home/florian/proj/qutebrowser/test#foo/requirements.txt, -r/home/florian/proj/qutebrowser/test#foo/misc/requirements/requirements-flake8.txt flake8 installed: attrs==17.3.0,colorama==0.3.9,cssutils==1.0.2,flake8==3.5.0,flake8-bugbear==17.12.0,flake8-builtins==1.0.post0,flake8-comprehensions==1.4.1,flake8-copyright==0.2.0,flake8-debugger==3.0.0,flake8-deprecated==1.3,flake8-docstrings==1.1.0,flake8-future-import==0.4.3,flake8-mock==0.3,flake8-per-file-ignores==0.4,flake8-polyfill==1.0.1,flake8-string-format==0.2.3,flake8-tidy-imports==1.1.0,flake8-tuple==0.2.13,Jinja2==2.10,MarkupSafe==1.0,mccabe==0.6.1,pep8-naming==0.4.1,pycodestyle==2.3.1,pydocstyle==2.1.1,pyflakes==1.6.0,Pygments==2.2.0,pyPEG2==2.15.2,PyYAML==3.12,six==1.11.0,snowballstemmer==1.2.1 flake8 runtests: PYTHONHASHSEED='2112495524' flake8 runtests: commands[0] | /home/florian/proj/qutebrowser/test ERROR: invocation failed (errno 2), args: ['/home/florian/proj/qutebrowser/test'], cwd: /home/florian/proj/qutebrowser/test#foo Traceback (most recent call last): File "/bin/tox", line 11, in <module> load_entry_point('tox==2.9.1', 'console_scripts', 'tox')() File "/usr/lib/python3.6/site-packages/tox/session.py", line 40, in main retcode = Session(config).runcommand() File "/usr/lib/python3.6/site-packages/tox/session.py", line 392, in runcommand return self.subcommand_test() File "/usr/lib/python3.6/site-packages/tox/session.py", line 583, in subcommand_test self.runtestenv(venv) File "/usr/lib/python3.6/site-packages/tox/session.py", line 592, in runtestenv self.hook.tox_runtest(venv=venv, redirect=redirect) File "/usr/lib/python3.6/site-packages/pluggy/__init__.py", line 617, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "/usr/lib/python3.6/site-packages/pluggy/__init__.py", line 222, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/usr/lib/python3.6/site-packages/pluggy/__init__.py", line 216, in <lambda> firstresult=hook.spec_opts.get('firstresult'), File "/usr/lib/python3.6/site-packages/pluggy/callers.py", line 201, in _multicall return outcome.get_result() File "/usr/lib/python3.6/site-packages/pluggy/callers.py", line 76, in get_result raise ex[1].with_traceback(ex[2]) File "/usr/lib/python3.6/site-packages/pluggy/callers.py", line 180, in _multicall res = hook_impl.function(*args) File "/usr/lib/python3.6/site-packages/tox/venv.py", line 464, in tox_runtest venv.test(redirect=redirect) File "/usr/lib/python3.6/site-packages/tox/venv.py", line 384, in test ignore_ret=ignore_ret, testcommand=True) File "/usr/lib/python3.6/site-packages/tox/venv.py", line 414, in _pcall redirect=redirect, ignore_ret=ignore_ret) File "/usr/lib/python3.6/site-packages/tox/session.py", line 140, in popen stdout=stdout, stderr=subprocess.STDOUT) File "/usr/lib/python3.6/site-packages/tox/session.py", line 228, in _popen stdout=stdout, stderr=stderr, env=env) File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/florian/proj/qutebrowser/test': '/home/florian/proj/qutebrowser/test' ``` Nothing too special in tox.ini: ```ini [testenv:flake8] basepython = {env:PYTHON:python3} passenv = deps = -r{toxinidir}/requirements.txt -r{toxinidir}/misc/requirements/requirements-flake8.txt commands = {envpython} -m flake8 {posargs:qutebrowser tests scripts} ``` I'm guessing `{envpython}` gets replaced by the Python path (which contains a `#`) and only after that, comments are stripped out?
0.0
174fd08e7db7076e262b96e4a76db49b40fbc620
[ "tests/session/cmd/test_show_config.py::test_show_config_ini_comment_path" ]
[ "tests/session/cmd/test_show_config.py::test_show_config_default_run_env", "tests/session/cmd/test_show_config.py::test_show_config_commands", "tests/session/cmd/test_show_config.py::test_show_config_filter_keys", "tests/session/cmd/test_show_config.py::test_show_config_unused", "tests/session/cmd/test_show_config.py::test_show_config_exception", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[True]", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[False]", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_skip", "tests/session/cmd/test_show_config.py::test_show_config_select_only", "tests/session/cmd/test_show_config.py::test_show_config_alias", "tests/session/cmd/test_show_config.py::test_show_config_description_normalize" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-08-08 10:14:53+00:00
mit
6,076
tox-dev__tox-2212
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d6dd3e68..8ce71718 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,7 +12,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade - rev: v2.25.0 + rev: v2.25.1 hooks: - id: pyupgrade args: ["--py36-plus"] diff --git a/docs/changelog/2211.bugfix.rst b/docs/changelog/2211.bugfix.rst new file mode 100644 index 00000000..7584fd21 --- /dev/null +++ b/docs/changelog/2211.bugfix.rst @@ -0,0 +1,1 @@ +Fix old-new value on recreate cache miss-match are swapped -- by :user:`gaborbernat`. diff --git a/src/tox/tox_env/python/api.py b/src/tox/tox_env/python/api.py index 2bec85d2..222e14ec 100644 --- a/src/tox/tox_env/python/api.py +++ b/src/tox/tox_env/python/api.py @@ -173,7 +173,7 @@ class Python(ToxEnv, ABC): removed = [f"{k}={v!r}" for k, v in old.items() if k not in conf] if removed: result.append(f"removed {' | '.join(removed)}") - changed = [f"{k}={v!r}->{old[k]!r}" for k, v in conf.items() if k in old and v != old[k]] + changed = [f"{k}={old[k]!r}->{v!r}" for k, v in conf.items() if k in old and v != old[k]] if changed: result.append(f"changed {' | '.join(changed)}") return f'python {", ".join(result)}'
tox-dev/tox
957a280af356575b00ac6bee34fb02919e95766e
diff --git a/src/tox/pytest.py b/src/tox/pytest.py index 265292be..b7d7be7d 100644 --- a/src/tox/pytest.py +++ b/src/tox/pytest.py @@ -398,8 +398,11 @@ def empty_project(tox_project: ToxProjectCreator, monkeypatch: MonkeyPatch) -> T return project +_RUN_INTEGRATION_TEST_FLAG = "--run-integration" + + def pytest_addoption(parser: Parser) -> None: - parser.addoption("--run-integration", action="store_true", help="run the integration tests") + parser.addoption(_RUN_INTEGRATION_TEST_FLAG, action="store_true", help="run the integration tests") def pytest_configure(config: PyTestConfig) -> None: @@ -413,12 +416,12 @@ def pytest_collection_modifyitems(config: PyTestConfig, items: List[Function]) - if len(items) == 1: # pragma: no cover # hard to test return - skip_int = pytest.mark.skip(reason="integration tests not run (no --run-int flag)") + skip_int = pytest.mark.skip(reason=f"integration tests not run (no {_RUN_INTEGRATION_TEST_FLAG} flag)") def is_integration(test_item: Function) -> bool: return test_item.get_closest_marker("integration") is not None - integration_enabled = config.getoption("--run-integration") + integration_enabled = config.getoption(_RUN_INTEGRATION_TEST_FLAG) if not integration_enabled: # pragma: no cover # hard to test for item in items: if is_integration(item): diff --git a/tests/tox_env/python/test_python_api.py b/tests/tox_env/python/test_python_api.py index aa588d44..2204a22a 100644 --- a/tests/tox_env/python/test_python_api.py +++ b/tests/tox_env/python/test_python_api.py @@ -60,7 +60,7 @@ def test_build_wheel_in_non_base_pkg_env( def test_diff_msg_added_removed_changed() -> None: before = {"A": "1", "F": "8", "C": "3", "D": "4", "E": "6"} after = {"G": "9", "B": "2", "C": "3", "D": "5", "E": "7"} - expected = "python added A='1' | F='8', removed G='9' | B='2', changed D='4'->'5' | E='6'->'7'" + expected = "python added A='1' | F='8', removed G='9' | B='2', changed D='5'->'4' | E='7'->'6'" assert Python._diff_msg(before, after) == expected diff --git a/tests/tox_env/python/virtual_env/test_virtualenv_api.py b/tests/tox_env/python/virtual_env/test_virtualenv_api.py index 5398e7f2..490aa295 100644 --- a/tests/tox_env/python/virtual_env/test_virtualenv_api.py +++ b/tests/tox_env/python/virtual_env/test_virtualenv_api.py @@ -119,7 +119,7 @@ def test_recreate_when_virtualenv_changes(tox_project: ToxProjectCreator, mocker mocker.patch.object(api, "virtualenv_version", "1.0") result = proj.run("r") - assert f"recreate env because python changed virtualenv version='1.0'->'{virtualenv_version}'" in result.out + assert f"recreate env because python changed virtualenv version='{virtualenv_version}'->'1.0'" in result.out assert "remove tox env folder" in result.out
tox4 python version change arrow should be inverted ``` type: recreate env because python changed version_info=[3, 9, 7, 'final', 0]->[3, 10, 0, 'candidate', 2] | ```
0.0
957a280af356575b00ac6bee34fb02919e95766e
[ "tests/tox_env/python/test_python_api.py::test_diff_msg_added_removed_changed", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_recreate_when_virtualenv_changes" ]
[ "tests/tox_env/python/test_python_api.py::test_requirements_txt", "tests/tox_env/python/test_python_api.py::test_diff_msg_no_diff", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-pypy-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-pypy-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[.pkg-py-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[.pkg-py-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[cpython-pypy-pypy-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[cpython-pypy-pypy-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy-cpython-cpython-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy-cpython-cpython-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy2-pypy3-pypy3-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy2-pypy3-pypy3-False]", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_virtualenv_env_ignored_if_set", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_virtualenv_env_used_if_not_set", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_honor_set_env_for_clear_periodic_update", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_pip_pre[True]", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_pip_pre[False]", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_install_command_no_packages", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_list_dependencies_command", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_install_pkg[r]", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_install_pkg[p]", "tests/tox_env/python/virtual_env/test_virtualenv_api.py::test_install_pkg[le]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-09-11 16:31:51+00:00
mit
6,077
tox-dev__tox-2306
diff --git a/docs/changelog/2183.feature.rst b/docs/changelog/2183.feature.rst new file mode 100644 index 00000000..9ddfb8cf --- /dev/null +++ b/docs/changelog/2183.feature.rst @@ -0,0 +1,2 @@ +Display a hint for unrecognized argument CLI parse failures to use ``--`` separator to pass arguments to commands +- by :user:`gaborbernat`. diff --git a/docs/changelog/2287.doc.rst b/docs/changelog/2287.doc.rst new file mode 100644 index 00000000..40c2ab68 --- /dev/null +++ b/docs/changelog/2287.doc.rst @@ -0,0 +1,1 @@ +Document :meth:`tox.config.sets.ConfigSet.loaders` - by :user:`gaborbernat`. diff --git a/src/tox/config/cli/parser.py b/src/tox/config/cli/parser.py index a7a4e548..a49ce18b 100644 --- a/src/tox/config/cli/parser.py +++ b/src/tox/config/cli/parser.py @@ -76,6 +76,19 @@ class ArgumentParserWithEnvAndConfig(ArgumentParser): raise TypeError(action) return of_type + def parse_args( # type: ignore # avoid defining all overloads + self, + args: Sequence[str] | None = None, + namespace: Namespace | None = None, + ) -> Namespace: + res, argv = self.parse_known_args(args, namespace) + if argv: + self.error( + f'unrecognized arguments: {" ".join(argv)}\n' + "hint: if you tried to pass arguments to a command use -- to separate them from tox ones", + ) + return res + class HelpFormatter(ArgumentDefaultsHelpFormatter): """ diff --git a/src/tox/config/sets.py b/src/tox/config/sets.py index 46864030..5f0df677 100644 --- a/src/tox/config/sets.py +++ b/src/tox/config/sets.py @@ -24,7 +24,7 @@ class ConfigSet(ABC): self._section = section self._env_name = env_name self._conf = conf - self.loaders: list[Loader[Any]] = [] + self.loaders: list[Loader[Any]] = [] #: active configuration loaders, can alter to change configuration values self._defined: dict[str, ConfigDefinition[Any]] = {} self._keys: dict[str, None] = {} self._alias: dict[str, str] = {}
tox-dev/tox
b8307e79a8e6f6e7f1440c22a63765ecf895f208
diff --git a/tests/config/cli/test_parser.py b/tests/config/cli/test_parser.py index 71d515cf..3b965d0d 100644 --- a/tests/config/cli/test_parser.py +++ b/tests/config/cli/test_parser.py @@ -7,7 +7,7 @@ import pytest from pytest_mock import MockerFixture from tox.config.cli.parser import Parsed, ToxParser -from tox.pytest import MonkeyPatch +from tox.pytest import CaptureFixture, MonkeyPatch def test_parser_const_with_default_none(monkeypatch: MonkeyPatch) -> None: @@ -81,3 +81,11 @@ def test_parse_known_args_not_set(mocker: MockerFixture) -> None: parser = ToxParser.base() _, unknown = parser.parse_known_args(None) assert unknown == ["--help"] + + +def test_parser_hint(capsys: CaptureFixture) -> None: + parser = ToxParser.base() + with pytest.raises(SystemExit): + parser.parse_args("foo") + out, err = capsys.readouterr() + assert err.endswith("hint: if you tried to pass arguments to a command use -- to separate them from tox ones\n")
[tox4] Document loaders on config set I'm trying to port our tox extension to the new tox 4 and I have one problem described in this thread: https://github.com/fedora-python/tox-current-env/pull/42#pullrequestreview-799430800 The problem basically is that it's not possible to call `get_env` in `tox_add_env_config` because it causes an endless recursion. I need to do it so I can overwrite some settings loaded from config with values from the extension.
0.0
b8307e79a8e6f6e7f1440c22a63765ecf895f208
[ "tests/config/cli/test_parser.py::test_parser_hint" ]
[ "tests/config/cli/test_parser.py::test_parser_const_with_default_none", "tests/config/cli/test_parser.py::test_parser_color[None-None-None-True]", "tests/config/cli/test_parser.py::test_parser_color[None-None-None-False]", "tests/config/cli/test_parser.py::test_parser_color[None-None-0-True]", "tests/config/cli/test_parser.py::test_parser_color[None-None-0-False]", "tests/config/cli/test_parser.py::test_parser_color[None-None-1-True]", "tests/config/cli/test_parser.py::test_parser_color[None-None-1-False]", "tests/config/cli/test_parser.py::test_parser_color[None-0-None-True]", "tests/config/cli/test_parser.py::test_parser_color[None-0-None-False]", "tests/config/cli/test_parser.py::test_parser_color[None-0-0-True]", "tests/config/cli/test_parser.py::test_parser_color[None-0-0-False]", "tests/config/cli/test_parser.py::test_parser_color[None-0-1-True]", "tests/config/cli/test_parser.py::test_parser_color[None-0-1-False]", "tests/config/cli/test_parser.py::test_parser_color[None-1-None-True]", "tests/config/cli/test_parser.py::test_parser_color[None-1-None-False]", "tests/config/cli/test_parser.py::test_parser_color[None-1-0-True]", "tests/config/cli/test_parser.py::test_parser_color[None-1-0-False]", "tests/config/cli/test_parser.py::test_parser_color[None-1-1-True]", "tests/config/cli/test_parser.py::test_parser_color[None-1-1-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-None-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-None-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-0-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-0-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-1-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-None-1-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-None-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-None-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-0-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-0-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-1-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-0-1-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-None-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-None-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-0-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-0-False]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-1-True]", "tests/config/cli/test_parser.py::test_parser_color[bad-1-1-False]", "tests/config/cli/test_parser.py::test_parser_color[no-None-None-True]", "tests/config/cli/test_parser.py::test_parser_color[no-None-None-False]", "tests/config/cli/test_parser.py::test_parser_color[no-None-0-True]", "tests/config/cli/test_parser.py::test_parser_color[no-None-0-False]", "tests/config/cli/test_parser.py::test_parser_color[no-None-1-True]", "tests/config/cli/test_parser.py::test_parser_color[no-None-1-False]", "tests/config/cli/test_parser.py::test_parser_color[no-0-None-True]", "tests/config/cli/test_parser.py::test_parser_color[no-0-None-False]", "tests/config/cli/test_parser.py::test_parser_color[no-0-0-True]", "tests/config/cli/test_parser.py::test_parser_color[no-0-0-False]", "tests/config/cli/test_parser.py::test_parser_color[no-0-1-True]", "tests/config/cli/test_parser.py::test_parser_color[no-0-1-False]", "tests/config/cli/test_parser.py::test_parser_color[no-1-None-True]", "tests/config/cli/test_parser.py::test_parser_color[no-1-None-False]", "tests/config/cli/test_parser.py::test_parser_color[no-1-0-True]", "tests/config/cli/test_parser.py::test_parser_color[no-1-0-False]", "tests/config/cli/test_parser.py::test_parser_color[no-1-1-True]", "tests/config/cli/test_parser.py::test_parser_color[no-1-1-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-None-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-None-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-0-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-0-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-1-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-None-1-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-None-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-None-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-0-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-0-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-1-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-0-1-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-None-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-None-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-0-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-0-False]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-1-True]", "tests/config/cli/test_parser.py::test_parser_color[yes-1-1-False]", "tests/config/cli/test_parser.py::test_parser_unsupported_type", "tests/config/cli/test_parser.py::test_sub_sub_command", "tests/config/cli/test_parser.py::test_parse_known_args_not_set" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-01-09 10:50:14+00:00
mit
6,078
tox-dev__tox-2383
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index f3fc3407..15f58597 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -55,6 +55,7 @@ Isaac Pedisich Itxaka Serrano Jake Windle Jannis Leidel +Jason R. Coombs Jesse Schwartzentruber Joachim Brandon LeBlanc Johannes Christ diff --git a/docs/changelog/2382.feature.rst b/docs/changelog/2382.feature.rst new file mode 100644 index 00000000..59a75852 --- /dev/null +++ b/docs/changelog/2382.feature.rst @@ -0,0 +1,1 @@ +On Windows ``PROGRAMFILES``, ``PROGRAMFILES(X86)``, and ``PROGRAMDATA`` environment variables are now passed through, unmasking system values necessary to locate resources such as a C compiler. diff --git a/docs/config.rst b/docs/config.rst index c579733e..2ca82e3a 100644 --- a/docs/config.rst +++ b/docs/config.rst @@ -469,7 +469,8 @@ Complete list of settings that you can put into ``testenv*`` sections: ``REQUESTS_CA_BUNDLE``, ``SSL_CERT_FILE``, ``HTTP_PROXY``, ``HTTPS_PROXY``, ``NO_PROXY`` * Windows: ``SYSTEMDRIVE``, ``SYSTEMROOT``, ``PATHEXT``, ``TEMP``, ``TMP`` - ``NUMBER_OF_PROCESSORS``, ``USERPROFILE``, ``MSYSTEM`` + ``NUMBER_OF_PROCESSORS``, ``USERPROFILE``, ``MSYSTEM``, + ``PROGRAMFILES``, ``PROGRAMFILES(X86)``, ``PROGRAMDATA`` * Others (e.g. UNIX, macOS): ``TMPDIR`` You can override these variables with the ``setenv`` option. diff --git a/src/tox/config/__init__.py b/src/tox/config/__init__.py index b155fd1c..b49c06f6 100644 --- a/src/tox/config/__init__.py +++ b/src/tox/config/__init__.py @@ -807,6 +807,10 @@ def tox_addoption(parser): passenv.add("PROCESSOR_ARCHITECTURE") # platform.machine() passenv.add("USERPROFILE") # needed for `os.path.expanduser()` passenv.add("MSYSTEM") # fixes #429 + # PROGRAM* required for compiler tool discovery #2382 + passenv.add("PROGRAMFILES") + passenv.add("PROGRAMFILES(X86)") + passenv.add("PROGRAMDATA") else: passenv.add("TMPDIR")
tox-dev/tox
eb1bd33d152f11f521805fe17e2240fb768e05d9
diff --git a/tests/unit/config/test_config.py b/tests/unit/config/test_config.py index 6949bf93..3408de02 100644 --- a/tests/unit/config/test_config.py +++ b/tests/unit/config/test_config.py @@ -1518,6 +1518,9 @@ class TestConfigTestEnv: assert "PROCESSOR_ARCHITECTURE" in envconfig.passenv assert "USERPROFILE" in envconfig.passenv assert "MSYSTEM" in envconfig.passenv + assert "PROGRAMFILES" in envconfig.passenv + assert "PROGRAMFILES(X86)" in envconfig.passenv + assert "PROGRAMDATA" in envconfig.passenv else: assert "TMPDIR" in envconfig.passenv if sys.platform != "win32": @@ -1562,6 +1565,9 @@ class TestConfigTestEnv: assert "SYSTEMROOT" in envconfig.passenv assert "TEMP" in envconfig.passenv assert "TMP" in envconfig.passenv + assert "PROGRAMFILES" in envconfig.passenv + assert "PROGRAMFILES(X86)" in envconfig.passenv + assert "PROGRAMDATA" in envconfig.passenv else: assert "TMPDIR" in envconfig.passenv assert "PATH" in envconfig.passenv
Pass through ProgramFiles* and ProgramData by default I'd like to follow up on #1673. I couldn't comment or even +1 that issue. I believe the characterization of the issue as setuptools-specific was incorrect. Although the issue does affect Setuptools and not Flit, that's only because Setuptools supports building C extensions on Windows. The issue can't be fixed in Setuptools. By the time tox has masked the ProgramFiles env var, Setuptools has little hope of recovering that setting. We're not asking tox to patch Setuptools. Instead, we're asking tox to consider honoring the system's intrinsic environment configuration by passing through system-level variables, variables that would be unlikely to be configured by the user and which are necessary for basic operation on the platform (similar to `PATH`, `SYSTEMDRIVE`, and `SYSTEMROOT`). Failing to support this model will instead require every project that builds extension modules on Windows to bypass this setting in their tox config. I believe this issue was largely missed until recently because most users were still testing on older platforms/compilers that did not rely on vswhere for discovery, but now that Windows 2022 is the default in Github, it's affecting a wide array of users. I contend: - this exemption is required in every case it affects - there is no known case that this masking is currently important - the number of affected projects is large. I can put together a repro that doesn't involve Setuptools if that helps persuade.
0.0
eb1bd33d152f11f521805fe17e2240fb768e05d9
[ "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[win32]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[win32]" ]
[ "tests/unit/config/test_config.py::TestIniParserPrefix::test_other_section_substitution", "tests/unit/config/test_config.py::TestIniParserPrefix::test_fallback_sections", "tests/unit/config/test_config.py::TestIniParserPrefix::test_basic_section_access", "tests/unit/config/test_config.py::TestIniParserPrefix::test_value_matches_prefixed_section_substitution", "tests/unit/config/test_config.py::TestIniParserPrefix::test_value_doesn_match_prefixed_section_substitution", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args2-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_no_arg", "tests/unit/config/test_config.py::TestGlobalOptions::test_sdist_specification", "tests/unit/config/test_config.py::TestGlobalOptions::test_env_selection_with_section_name", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_true", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args0-0]", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_default", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args4-3]", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_context", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_not_specified", "tests/unit/config/test_config.py::TestGlobalOptions::test_correct_basepython_chosen_from_default_factors", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_overrides_true", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args0-0]", "tests/unit/config/test_config.py::TestGlobalOptions::test_defaultenv_partial_override", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_false", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args3-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_expansion", "tests/unit/config/test_config.py::TestGlobalOptions::test_defaultenv_commandline", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_cross_product", "tests/unit/config/test_config.py::TestGlobalOptions::test_envlist_multiline", "tests/unit/config/test_config.py::TestGlobalOptions::test_py_venv", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args2-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_quiet[args1-1]", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args4-3]", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args1-1]", "tests/unit/config/test_config.py::TestGlobalOptions::test_substitution_jenkins_global", "tests/unit/config/test_config.py::TestGlobalOptions::test_no_implicit_venv_from_cli_with_envlist", "tests/unit/config/test_config.py::TestGlobalOptions::test_env_selection_expanded_envlist", "tests/unit/config/test_config.py::TestGlobalOptions::test_notest", "tests/unit/config/test_config.py::TestGlobalOptions::test_verbosity[args3-2]", "tests/unit/config/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_cli_overrides_false", "tests/unit/config/test_config.py::TestParseconfig::test_search_parents", "tests/unit/config/test_config.py::TestParseconfig::test_explicit_config_path", "tests/unit/config/test_config.py::TestParseconfig::test_workdir_gets_resolved", "tests/unit/config/test_config.py::TestGetcontextname::test_blank", "tests/unit/config/test_config.py::TestGetcontextname::test_jenkins", "tests/unit/config/test_config.py::TestGetcontextname::test_hudson_legacy", "tests/unit/config/test_config.py::TestIndexServer::test_multiple_homedir_relative_local_indexservers", "tests/unit/config/test_config.py::TestIndexServer::test_parse_indexserver", "tests/unit/config/test_config.py::TestIndexServer::test_indexserver", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[win]", "tests/unit/config/test_config.py::TestConfigPlatform::test_platform_install_command", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[lin]", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_rex", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform", "tests/unit/config/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[osx]", "tests/unit/config/test_config.py::test_get_homedir", "tests/unit/config/test_config.py::test_env_spec[-e", "tests/unit/config/test_config.py::test_config_setup_cfg_no_tox_section", "tests/unit/config/test_config.py::test_isolated_build_ignores[deps-crazy-default0]", "tests/unit/config/test_config.py::test_interactive", "tests/unit/config/test_config.py::test_config_current_py", "tests/unit/config/test_config.py::test_config_bad_config_type_specified", "tests/unit/config/test_config.py::test_config_via_pyproject_legacy", "tests/unit/config/test_config.py::test_overwrite_skip_install_override", "tests/unit/config/test_config.py::test_config_bad_pyproject_specified", "tests/unit/config/test_config.py::test_posargs_relative_changedir", "tests/unit/config/test_config.py::test_config_file_not_required_with_devenv", "tests/unit/config/test_config.py::test_interactive_na", "tests/unit/config/test_config.py::test_provision_tox_env_cannot_be_in_envlist", "tests/unit/config/test_config.py::test_isolated_build_env_cannot_be_in_envlist", "tests/unit/config/test_config.py::test_config_no_version_data_in__name", "tests/unit/config/test_config.py::test_isolated_build_overrides", "tests/unit/config/test_config.py::test_isolated_build_ignores[sitepackages-True-False]", "tests/unit/config/test_config.py::test_interactive_available", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_multiple_words", "tests/unit/config/test_config.py::TestCommandParser::test_command_with_split_line_in_subst_arguments", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_word", "tests/unit/config/test_config.py::TestCommandParser::test_command_parsing_for_issue_10", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_posargs", "tests/unit/config/test_config.py::TestCommandParser::test_commands_with_backslash", "tests/unit/config/test_config.py::TestCommandParser::test_command_with_runs_of_whitespace", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_for_substitution_with_spaces", "tests/unit/config/test_config.py::TestCommandParser::test_command_parser_with_complex_word_set", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_no_plugins", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_with_normal_plugin", "tests/unit/config/test_config.py::TestCmdInvocation::test_no_tox_ini", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_with_fileless_module", "tests/unit/config/test_config.py::TestCmdInvocation::test_version_simple", "tests/unit/config/test_config.py::TestCmdInvocation::test_help", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults_changed_dir", "tests/unit/config/test_config.py::TestConfigPackage::test_defaults_distshare", "tests/unit/config/test_config.py::TestConfigPackage::test_project_paths", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_regression_issue595", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_simple", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_multiline", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_section_and_posargs_substitution", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_inherit", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_unnecessary", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_global", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs_with_spaced_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_default_escape", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_multi_env", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_posargs", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_posargs_with_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_setenv", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_posargs_with_colon", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_missing_substitution_complex", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_other_section", "tests/unit/config/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_recursion_error_same_section", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_windows_escaping", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_quoted_posargs", "tests/unit/config/test_config.py::TestIniParser::test_substitution_empty", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_quoting_in_command", "tests/unit/config/test_config.py::TestIniParser::test_getpath", "tests/unit/config/test_config.py::TestIniParser::test_argvlist", "tests/unit/config/test_config.py::TestIniParser::test_positional_arguments_are_only_replaced_when_standing_alone", "tests/unit/config/test_config.py::TestIniParser::test_getdict", "tests/unit/config/test_config.py::TestIniParser::test_missing_env_sub_populates_missing_subs", "tests/unit/config/test_config.py::TestIniParser::test_missing_env_sub_raises_config_error_in_non_testenv", "tests/unit/config/test_config.py::TestIniParser::test_substitution_with_multiple_words", "tests/unit/config/test_config.py::TestIniParser::test_expand_section_name", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_multiline", "tests/unit/config/test_config.py::TestIniParser::test_getstring_fallback_sections", "tests/unit/config/test_config.py::TestIniParser::test_normal_env_sub_works", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_posargs_with_quotes", "tests/unit/config/test_config.py::TestIniParser::test_getstring_other_section_substitution", "tests/unit/config/test_config.py::TestIniParser::test_getbool", "tests/unit/config/test_config.py::TestIniParser::test_substitution_colon_prefix", "tests/unit/config/test_config.py::TestIniParser::test_value_matches_section_substitution", "tests/unit/config/test_config.py::TestIniParser::test_getstring_single", "tests/unit/config/test_config.py::TestIniParser::test_getargv", "tests/unit/config/test_config.py::TestIniParser::test_getlist", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_command_contains_hash", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_comment_after_command", "tests/unit/config/test_config.py::TestIniParser::test_getstring_environment_substitution_with_default", "tests/unit/config/test_config.py::TestIniParser::test_argvlist_positional_substitution", "tests/unit/config/test_config.py::TestIniParser::test_getstring_substitution", "tests/unit/config/test_config.py::TestIniParser::test_missing_substitution", "tests/unit/config/test_config.py::TestIniParser::test_posargs_are_added_escaped_issue310", "tests/unit/config/test_config.py::TestIniParser::test_value_doesn_match_section_substitution", "tests/unit/config/test_config.py::TestParseEnv::test_parse_recreate", "tests/unit/config/test_config.py::TestConfigTestEnv::test_do_not_substitute_more_than_needed", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_support_curly_braces", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_from_global_env", "tests/unit/config/test_config.py::TestConfigTestEnv::test_rewrite_posargs", "tests/unit/config/test_config.py::TestConfigTestEnv::test_changedir_override", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[linux2]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_ignore_outcome", "tests/unit/config/test_config.py::TestConfigTestEnv::test_changedir", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_ignore_errors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_double", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors_conflict_lying_name", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy3]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_groups_touch", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_substitutions_other_section", "tests/unit/config/test_config.py::TestConfigTestEnv::test_installpkg_tops_develop", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_with_factor", "tests/unit/config/test_config.py::TestConfigTestEnv::test_single_value_from_other_secton", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_use_not_checked", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue515", "tests/unit/config/test_config.py::TestConfigTestEnv::test_period_in_factor", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_substitutions", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist0-deps0]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_pip_pre_cmdline_override", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_win[/-bin]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_in_boolean", "tests/unit/config/test_config.py::TestConfigTestEnv::test_multilevel_substitution", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_setting", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_section", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[linux2]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_rewrite_simple_posargs", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_win[\\\\-Scripts]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_nested_env_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_commentchars_issue33", "tests/unit/config/test_config.py::TestConfigTestEnv::test_simple", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir", "tests/unit/config/test_config.py::TestConfigTestEnv::test_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_recursive_substitution_cycle_fails", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_expansion", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_positional", "tests/unit/config/test_config.py::TestConfigTestEnv::test_passenv_glob_from_global_env", "tests/unit/config/test_config.py::TestConfigTestEnv::test_default_factors_conflict", "tests/unit/config/test_config.py::TestConfigTestEnv::test_allowlist_externals", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue246", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envconfigs_based_on_factors", "tests/unit/config/test_config.py::TestConfigTestEnv::test_specific_command_overrides", "tests/unit/config/test_config.py::TestConfigTestEnv::test_install_command_must_contain_packages", "tests/unit/config/test_config.py::TestConfigTestEnv::test_posargs_backslashed_or_quoted", "tests/unit/config/test_config.py::TestConfigTestEnv::test_regression_test_issue_706[envlist0]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_defaults", "tests/unit/config/test_config.py::TestConfigTestEnv::test_sitepackages_switch", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factors_in_setenv", "tests/unit/config/test_config.py::TestConfigTestEnv::test_factor_ops", "tests/unit/config/test_config.py::TestConfigTestEnv::test_no_spinner", "tests/unit/config/test_config.py::TestConfigTestEnv::test_pip_pre", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_noargs_issue240", "tests/unit/config/test_config.py::TestConfigTestEnv::test_curly_braces_in_setenv", "tests/unit/config/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist1-deps1]", "tests/unit/config/test_config.py::TestConfigTestEnv::test_substitution_error", "tests/unit/config/test_config.py::TestConfigTestEnv::test_envbindir_jython[jython]", "tests/unit/config/test_config.py::TestVenvConfig::test_process_deps", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually_setup_cfg", "tests/unit/config/test_config.py::TestVenvConfig::test_force_dep_version", "tests/unit/config/test_config.py::TestVenvConfig::test_config_parsing_multienv", "tests/unit/config/test_config.py::TestVenvConfig::test_force_dep_with_url", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually", "tests/unit/config/test_config.py::TestVenvConfig::test_suicide_interrupt_terminate_timeout_set_manually", "tests/unit/config/test_config.py::TestVenvConfig::test_config_parsing_minimal", "tests/unit/config/test_config.py::TestVenvConfig::test_envdir_set_manually_with_substitutions", "tests/unit/config/test_config.py::TestVenvConfig::test_is_same_dep", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_empty_string", "tests/unit/config/test_config.py::TestHashseedOption::test_setenv_in_one_testenv", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_string", "tests/unit/config/test_config.py::TestHashseedOption::test_default", "tests/unit/config/test_config.py::TestHashseedOption::test_noset_with_setenv", "tests/unit/config/test_config.py::TestHashseedOption::test_setenv", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_no_argument", "tests/unit/config/test_config.py::TestHashseedOption::test_passing_integer", "tests/unit/config/test_config.py::TestHashseedOption::test_one_random_hashseed", "tests/unit/config/test_config.py::TestHashseedOption::test_noset", "tests/unit/config/test_config.py::TestSetenv::test_setenv_uses_other_setenv", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[\\n-False]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_with_default", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[#MAGIC", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[\\nMAGIC", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_subst_issue294", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_mixed", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[None-False]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_with_default_nested", "tests/unit/config/test_config.py::TestSetenv::test_setenv_with_envdir_and_basepython", "tests/unit/config/test_config.py::TestSetenv::test_setenv_uses_os_environ", "tests/unit/config/test_config.py::TestSetenv::test_setenv_recursive_direct_without_default", "tests/unit/config/test_config.py::TestSetenv::test_getdict_lazy_update", "tests/unit/config/test_config.py::TestSetenv::test_setenv_ordering_1", "tests/unit/config/test_config.py::TestSetenv::test_setenv_cross_section_subst_twice", "tests/unit/config/test_config.py::TestSetenv::test_setenv_comment", "tests/unit/config/test_config.py::TestSetenv::test_setenv_default_os_environ", "tests/unit/config/test_config.py::TestSetenv::test_setenv_env_file[MAGIC=yes-True]", "tests/unit/config/test_config.py::TestSetenv::test_setenv_overrides", "tests/unit/config/test_config.py::TestSetenv::test_getdict_lazy", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep[;]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_replace[\\\\]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_replace[\\\\\\\\]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_dirsep_regex", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep[:]", "tests/unit/config/test_config.py::TestConfigConstSubstitutions::test_pathsep_regex" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-03-21 15:49:08+00:00
mit
6,079
tox-dev__tox-2529
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index e0259323..09ae1344 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -33,6 +33,7 @@ Cyril Roelandt Dane Hillard David Staheli David Diaz +Dmitrii Sutiagin a.k.a. f3flight Ederag Eli Collins Eugene Yunak diff --git a/docs/changelog/2528.bugfix.rst b/docs/changelog/2528.bugfix.rst new file mode 100644 index 00000000..c5cecd41 --- /dev/null +++ b/docs/changelog/2528.bugfix.rst @@ -0,0 +1,1 @@ +Add env cleanup to envreport - fix PYTHONPATH leak into "envreport" -- by :user:`f3flight`. diff --git a/src/tox/venv.py b/src/tox/venv.py index 8acb0c77..47f281f6 100644 --- a/src/tox/venv.py +++ b/src/tox/venv.py @@ -840,7 +840,11 @@ def tox_runtest_post(venv): def tox_runenvreport(venv, action): # write out version dependency information args = venv.envconfig.list_dependencies_command - output = venv._pcall(args, cwd=venv.envconfig.config.toxinidir, action=action, returnout=True) + env = venv._get_os_environ() + venv.ensure_pip_os_environ_ok(env) + output = venv._pcall( + args, cwd=venv.envconfig.config.toxinidir, action=action, returnout=True, env=env + ) # the output contains a mime-header, skip it output = output.split("\n\n")[-1] packages = output.strip().split("\n")
tox-dev/tox
0f0c505244f82b85b4c73f5f7ba33bc499b5e163
diff --git a/tests/unit/test_venv.py b/tests/unit/test_venv.py index aa78a48b..3da4e22e 100644 --- a/tests/unit/test_venv.py +++ b/tests/unit/test_venv.py @@ -14,6 +14,7 @@ from tox.venv import ( VirtualEnv, getdigest, prepend_shebang_interpreter, + tox_runenvreport, tox_testenv_create, tox_testenv_install_deps, ) @@ -1233,3 +1234,17 @@ def test_path_change(tmpdir, mocksession, newconfig, monkeypatch): path = x.env["PATH"] assert os.environ["PATH"] in path assert path.endswith(str(venv.envconfig.config.toxinidir) + "/bin") + + +def test_runenvreport_pythonpath_discarded(newmocksession, mocker): + mock_os_environ = mocker.patch("tox.venv.VirtualEnv._get_os_environ") + mocksession = newmocksession([], "") + venv = mocksession.getvenv("python") + mock_os_environ.return_value = dict(PYTHONPATH="/some/path/") + mock_pcall = mocker.patch.object(venv, "_pcall") + tox_runenvreport(venv, None) + try: + env = mock_pcall.mock_calls[0].kwargs["env"] + except TypeError: # older pytest (python 3.7 and below) + env = mock_pcall.mock_calls[0][2]["env"] + assert "PYTHONPATH" not in env
PYTHONPATH leaks into "envreport" Pretty trivial bug. Even though tox discards PYTHONPATH for `pip install`, it does not discard it for `pip freeze`, causing garbage output if PYTHONPATH has any extra packages (i.e. "pip freeze" will see packages from PYTHONPATH, which it should not do). https://github.com/tox-dev/tox/blob/3.27.0/src/tox/venv.py#L843 Fix is trivial - fetch env and apply `ensure_pip_os_environ_ok` the same way it is done for `pip install`, pass env to pcall. I will make a PR.
0.0
0f0c505244f82b85b4c73f5f7ba33bc499b5e163
[ "tests/unit/test_venv.py::test_runenvreport_pythonpath_discarded" ]
[ "tests/unit/test_venv.py::TestVenvTest::test_pythonpath_remove", "tests/unit/test_venv.py::TestVenvTest::test_pythonpath_keep", "tests/unit/test_venv.py::TestVenvTest::test_pythonpath_empty", "tests/unit/test_venv.py::TestVenvTest::test_envbindir_path", "tests/unit/test_venv.py::test_install_error", "tests/unit/test_venv.py::test_create_KeyboardInterrupt[_pcall]", "tests/unit/test_venv.py::test_develop_extras", "tests/unit/test_venv.py::test_install_python3", "tests/unit/test_venv.py::test_test_runtests_action_command_is_in_output", "tests/unit/test_venv.py::test_commandpath_venv_precedence", "tests/unit/test_venv.py::test_create", "tests/unit/test_venv.py::test_create_KeyboardInterrupt[update]", "tests/unit/test_venv.py::test_create_sitepackages", "tests/unit/test_venv.py::test_install_deps_indexserver", "tests/unit/test_venv.py::test_install_sdist_extras", "tests/unit/test_venv.py::test_env_variables_added_to_needs_reinstall", "tests/unit/test_venv.py::test_getdigest", "tests/unit/test_venv.py::test_install_recreate", "tests/unit/test_venv.py::test_install_deps_wildcard", "tests/unit/test_venv.py::test_install_command_allowlisted_exclusive", "tests/unit/test_venv.py::test_getsupportedinterpreter", "tests/unit/test_venv.py::test_test_empty_commands", "tests/unit/test_venv.py::test_install_deps_pre", "tests/unit/test_venv.py::test_install_command_whitelisted", "tests/unit/test_venv.py::test_install_command_not_installed_bash", "tests/unit/test_venv.py::test_install_command_allowlisted", "tests/unit/test_venv.py::test_installpkg_indexserver", "tests/unit/test_venv.py::test_test_hashseed_is_in_output", "tests/unit/test_venv.py::test_install_command_not_installed", "tests/unit/test_venv.py::test_create_download[True]", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_interpreter_arg", "tests/unit/test_venv.py::test_install_command_verbosity[6-3]", "tests/unit/test_venv.py::test_installpkg_upgrade", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_empty_interpreter_ws", "tests/unit/test_venv.py::test_tox_testenv_create", "tests/unit/test_venv.py::test_run_install_command", "tests/unit/test_venv.py::test_run_install_command_handles_KeyboardInterrupt", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_real", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_non_utf8", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_interpreter_simple", "tests/unit/test_venv.py::test_create_download[None]", "tests/unit/test_venv.py::test_env_variables_added_to_pcall", "tests/unit/test_venv.py::test_create_download[False]", "tests/unit/test_venv.py::test_install_command_verbosity[3-1]", "tests/unit/test_venv.py::test_install_command_verbosity[4-2]", "tests/unit/test_venv.py::test_ignore_outcome_failing_cmd", "tests/unit/test_venv.py::test_command_relative_issue36", "tests/unit/test_venv.py::test_path_change", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_empty_instance", "tests/unit/test_venv.py::test_install_command_verbosity[2-0]", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_skip_truncated", "tests/unit/test_venv.py::test_install_command_verbosity[0-0]", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_empty_interpreter", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_interpreter_ws", "tests/unit/test_venv.py::test_install_command_verbosity[1-0]", "tests/unit/test_venv.py::test_tox_testenv_pre_post", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_interpreter_args", "tests/unit/test_venv.py::test_tox_testenv_interpret_shebang_long_example", "tests/unit/test_venv.py::test_run_custom_install_command", "tests/unit/test_venv.py::test_install_command_verbosity[5-3]", "tests/unit/test_venv.py::test_installpkg_no_upgrade", "tests/unit/test_venv.py::test_ignore_outcome_missing_cmd", "tests/unit/test_venv.py::TestCreationConfig::test_basic", "tests/unit/test_venv.py::TestCreationConfig::test_python_recreation", "tests/unit/test_venv.py::TestCreationConfig::test_matchingdependencies_file", "tests/unit/test_venv.py::TestCreationConfig::test_matchingdependencies", "tests/unit/test_venv.py::TestCreationConfig::test_develop_recreation", "tests/unit/test_venv.py::TestCreationConfig::test_matchingdependencies_latest", "tests/unit/test_venv.py::TestCreationConfig::test_dep_recreation" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-11-03 22:07:58+00:00
mit
6,080
tox-dev__tox-2547
diff --git a/docs/changelog/2373.bugfix.rst b/docs/changelog/2373.bugfix.rst new file mode 100644 index 00000000..1fb3436f --- /dev/null +++ b/docs/changelog/2373.bugfix.rst @@ -0,0 +1,1 @@ +Allow ``--hash`` to be specified in requirements.txt files. - by :user:`masenf`. diff --git a/src/tox/tox_env/python/pip/req/args.py b/src/tox/tox_env/python/pip/req/args.py index 19bded34..23f98ec3 100644 --- a/src/tox/tox_env/python/pip/req/args.py +++ b/src/tox/tox_env/python/pip/req/args.py @@ -18,10 +18,10 @@ class _OurArgumentParser(ArgumentParser): raise ValueError(msg) -def build_parser(cli_only: bool) -> ArgumentParser: +def build_parser() -> ArgumentParser: parser = _OurArgumentParser(add_help=False, prog="", allow_abbrev=False) _global_options(parser) - _req_options(parser, cli_only) + _req_options(parser) return parser @@ -47,11 +47,10 @@ def _global_options(parser: ArgumentParser) -> None: ) -def _req_options(parser: ArgumentParser, cli_only: bool) -> None: +def _req_options(parser: ArgumentParser) -> None: parser.add_argument("--install-option", action=AddSortedUniqueAction) parser.add_argument("--global-option", action=AddSortedUniqueAction) - if not cli_only: - parser.add_argument("--hash", action=AddSortedUniqueAction, type=_validate_hash) + parser.add_argument("--hash", action=AddSortedUniqueAction, type=_validate_hash) _HASH = re.compile(r"sha(256:[a-f0-9]{64}|384:[a-f0-9]{96}|512:[a-f0-9]{128})") diff --git a/src/tox/tox_env/python/pip/req/file.py b/src/tox/tox_env/python/pip/req/file.py index 4ad4ae06..df11ebe5 100644 --- a/src/tox/tox_env/python/pip/req/file.py +++ b/src/tox/tox_env/python/pip/req/file.py @@ -156,7 +156,7 @@ class RequirementsFile: @property def _parser(self) -> ArgumentParser: if self._parser_private is None: - self._parser_private = build_parser(False) + self._parser_private = build_parser() return self._parser_private def _ensure_requirements_parsed(self) -> None: diff --git a/src/tox/tox_env/python/pip/req_file.py b/src/tox/tox_env/python/pip/req_file.py index 1f8754a8..91202345 100644 --- a/src/tox/tox_env/python/pip/req_file.py +++ b/src/tox/tox_env/python/pip/req_file.py @@ -1,14 +1,17 @@ from __future__ import annotations import re -from argparse import ArgumentParser +from argparse import Namespace from pathlib import Path -from .req.args import build_parser -from .req.file import ReqFileLines, RequirementsFile +from .req.file import ParsedRequirement, ReqFileLines, RequirementsFile class PythonDeps(RequirementsFile): + # these options are valid in requirements.txt, but not via pip cli and + # thus cannot be used in the testenv `deps` list + _illegal_options = ["hash"] + def __init__(self, raw: str, root: Path): super().__init__(root / "tox.ini", constraint=False) self._raw = self._normalize_raw(raw) @@ -28,12 +31,6 @@ class PythonDeps(RequirementsFile): line = f"{line[0:2]} {line[2:]}" yield at, line - @property - def _parser(self) -> ArgumentParser: - if self._parser_private is None: - self._parser_private = build_parser(cli_only=True) # e.g. no --hash for cli only - return self._parser_private - def lines(self) -> list[str]: return self._raw.splitlines() @@ -68,6 +65,20 @@ class PythonDeps(RequirementsFile): raw = f"{adjusted}\n" if raw.endswith("\\\n") else adjusted # preserve trailing newline if input has it return raw + def _parse_requirements(self, opt: Namespace, recurse: bool) -> list[ParsedRequirement]: + # check for any invalid options in the deps list + # (requirements recursively included from other files are not checked) + requirements = super()._parse_requirements(opt, recurse) + for r in requirements: + if r.from_file != str(self.path): + continue + for illegal_option in self._illegal_options: + if r.options.get(illegal_option): + raise ValueError( + f"Cannot use --{illegal_option} in deps list, it must be in requirements file. ({r})", + ) + return requirements + def unroll(self) -> tuple[list[str], list[str]]: if self._unroll is None: opts_dict = vars(self.options)
tox-dev/tox
023a4ed403f42915da52151ce296e0f398b67005
diff --git a/tests/tox_env/python/pip/test_req_file.py b/tests/tox_env/python/pip/test_req_file.py index 41908f96..66a0db9a 100644 --- a/tests/tox_env/python/pip/test_req_file.py +++ b/tests/tox_env/python/pip/test_req_file.py @@ -14,3 +14,31 @@ def test_legacy_requirement_file(tmp_path: Path, legacy_flag: str) -> None: assert python_deps.as_root_args == [legacy_flag, "a.txt"] assert vars(python_deps.options) == {} assert [str(i) for i in python_deps.requirements] == ["b" if legacy_flag == "-r" else "-c b"] + + +def test_deps_with_hash(tmp_path: Path) -> None: + """deps with --hash should raise an exception.""" + python_deps = PythonDeps( + raw="foo==1 --hash sha256:97a702083b0d906517b79672d8501eee470d60ae55df0fa9d4cfba56c7f65a82", + root=tmp_path, + ) + with pytest.raises(ValueError, match="Cannot use --hash in deps list"): + _ = python_deps.requirements + + +def test_deps_with_requirements_with_hash(tmp_path: Path) -> None: + """deps can point to a requirements file that has --hash.""" + exp_hash = "sha256:97a702083b0d906517b79672d8501eee470d60ae55df0fa9d4cfba56c7f65a82" + requirements = tmp_path / "requirements.txt" + requirements.write_text( + f"foo==1 --hash {exp_hash}", + ) + python_deps = PythonDeps( + raw="-r requirements.txt", + root=tmp_path, + ) + assert len(python_deps.requirements) == 1 + parsed_req = python_deps.requirements[0] + assert str(parsed_req.requirement) == "foo==1" + assert parsed_req.options == {"hash": [exp_hash]} + assert parsed_req.from_file == str(requirements)
tox4: fails to process requirement files with --hash There is a regression on tox4 where it fails to parse requirement files that contain hashes. While these are not very popular they are still the recommended for security reasons as they protect against potential hacks on pypi registry. Example of file that causes tox4 to fail, while it works fine with tox3: https://github.com/ansible/ansible-language-server/blob/v0.5.0/docs/requirements.txt ``` During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/session/cmd/run/single.py", line 45, in _evaluate tox_env.setup() File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/tox_env/api.py", line 226, in setup self._setup_env() File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/tox_env/python/runner.py", line 91, in _setup_env self._install_deps() File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/tox_env/python/runner.py", line 95, in _install_deps self.installer.install(requirements_file, PythonRun.__name__, "deps") File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/tox_env/python/pip/pip_install.py", line 84, in install self._install_requirement_file(arguments, section, of_type) File "/Users/ssbarnea/.pyenv/versions/3.10.2/lib/python3.10/site-packages/tox/tox_env/python/pip/pip_install.py", line 95, in _install_requirement_file raise HandledError(f"{exception} for tox env py within deps") tox.report.HandledError: unrecognized arguments: --hash=sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359 --hash=sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02 for tox env py within deps ``` It should be remarked that these files are produced by pip-compile (pip-tools). Note: I temporary removed the hashes from the lock file but we cannot really ignore this issue.
0.0
023a4ed403f42915da52151ce296e0f398b67005
[ "tests/tox_env/python/pip/test_req_file.py::test_deps_with_hash", "tests/tox_env/python/pip/test_req_file.py::test_deps_with_requirements_with_hash" ]
[ "tests/tox_env/python/pip/test_req_file.py::test_legacy_requirement_file[-r]", "tests/tox_env/python/pip/test_req_file.py::test_legacy_requirement_file[-c]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-11-25 11:28:53+00:00
mit
6,081
tox-dev__tox-2643
diff --git a/docs/changelog/2620.bugfix.rst b/docs/changelog/2620.bugfix.rst new file mode 100644 index 00000000..ba4c5bd5 --- /dev/null +++ b/docs/changelog/2620.bugfix.rst @@ -0,0 +1,1 @@ +Ensure :ref:`change_dir` is created if does not exist before executing :ref:`commands` - by :user:`gaborbernat`. diff --git a/src/tox/session/cmd/run/single.py b/src/tox/session/cmd/run/single.py index 9cc3e45e..9ef909d1 100644 --- a/src/tox/session/cmd/run/single.py +++ b/src/tox/session/cmd/run/single.py @@ -71,6 +71,7 @@ def run_commands(tox_env: RunToxEnv, no_test: bool) -> tuple[int, list[Outcome]] from tox.plugin.manager import MANAGER # importing this here to avoid circular import chdir: Path = tox_env.conf["change_dir"] + chdir.mkdir(exist_ok=True, parents=True) ignore_errors: bool = tox_env.conf["ignore_errors"] MANAGER.tox_before_run_commands(tox_env) status_pre, status_main, status_post = -1, -1, -1
tox-dev/tox
267d3275ad929b12e951dc8a6d2b73aa3e61b168
diff --git a/tests/tox_env/test_tox_env_api.py b/tests/tox_env/test_tox_env_api.py index c5542dbc..2c467bb6 100644 --- a/tests/tox_env/test_tox_env_api.py +++ b/tests/tox_env/test_tox_env_api.py @@ -86,3 +86,10 @@ def test_tox_env_pass_env_match_ignore_case(char: str, glob: str) -> None: with patch("os.environ", {"A1": "1", "a2": "2", "A2": "3", "B": "4"}): env = ToxEnv._load_pass_env([f"{char}{glob}"]) assert env == {"A1": "1", "a2": "2", "A2": "3"} + + +def test_change_dir_is_created_if_not_exist(tox_project: ToxProjectCreator) -> None: + prj = tox_project({"tox.ini": "[testenv]\npackage=skip\nchange_dir=a{/}b\ncommands=python --version"}) + result_first = prj.run("r") + result_first.assert_success() + assert (prj.path / "a" / "b").exists()
change_dir fails if directory does not exist I found the issue I think: `change_dir` says that the directory is created if it doesn't exist, but that does not seem to be the case: > Change to this working directory when executing the test command. If the directory does not exist yet, it will be created (required for Windows to be able to execute any command). with `change_dir = foo` the tests don't run and show the error above. When I do `mkdir foo` myself before, it works. _Originally posted by @maxnoe in https://github.com/tox-dev/tox/issues/2612#issuecomment-1341515799_
0.0
267d3275ad929b12e951dc8a6d2b73aa3e61b168
[ "tests/tox_env/test_tox_env_api.py::test_change_dir_is_created_if_not_exist" ]
[ "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_literal_exist", "tests/tox_env/test_tox_env_api.py::test_recreate", "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_match_ignore_case[A-*]", "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_literal_miss", "tests/tox_env/test_tox_env_api.py::test_allow_list_external_fail", "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_match_ignore_case[a-*]", "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_match_ignore_case[a-?]", "tests/tox_env/test_tox_env_api.py::test_env_log", "tests/tox_env/test_tox_env_api.py::test_tox_env_pass_env_match_ignore_case[A-?]" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-12-08 15:53:57+00:00
mit
6,082
tox-dev__tox-2716
diff --git a/docs/changelog/2640.feature.rst b/docs/changelog/2640.feature.rst new file mode 100644 index 00000000..bbf9b022 --- /dev/null +++ b/docs/changelog/2640.feature.rst @@ -0,0 +1,3 @@ +Add ``py_dot_ver`` and ``py_impl`` constants to environments to show the current Python implementation and dot version +(e.g. ``3.11``) for the current environment. These can be also used as substitutions in ``tox.ini`` - by +:user:`gaborbernat`. diff --git a/docs/faq.rst b/docs/faq.rst index f14d6266..205d8d54 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -79,6 +79,16 @@ tox 4 - removed tox.ini keys | ``distdir`` | Use the ``TOX_PACKAGE`` environment variable.| +--------------------------+----------------------------------------------+ +tox 4 - basepython not resolved ++++++++++++++++++++++++++++++++ +The base python configuration is no longer resolved to ``pythonx.y`` format, instead is kept as ``py39``, and is +the virtualenv project that handles mapping that to a Python interpreter. If you were using this variable we recommend +moving to the newly added ``py_impl`` and ``py_dot_ver`` variables, for example: + +.. code-block:: ini + + deps = -r{py_impl}{py_dot_ver}-req.txt + tox 4 - substitutions removed +++++++++++++++++++++++++++++ - The ``distshare`` substitution has been removed. diff --git a/src/tox/tox_env/api.py b/src/tox/tox_env/api.py index 13a9a4aa..e87710d5 100644 --- a/src/tox/tox_env/api.py +++ b/src/tox/tox_env/api.py @@ -323,7 +323,7 @@ class ToxEnv(ABC): result = self._load_pass_env(pass_env) # load/paths_env might trigger a load of the environment variables, set result here, returns current state - self._env_vars, self._env_vars_pass_env, set_env.changed = result, pass_env, False + self._env_vars, self._env_vars_pass_env, set_env.changed = result, pass_env.copy(), False # set PATH here in case setting and environment variable requires access to the environment variable PATH result["PATH"] = self._make_path() for key in set_env: diff --git a/src/tox/tox_env/python/api.py b/src/tox/tox_env/python/api.py index 09975569..6f25dd6a 100644 --- a/src/tox/tox_env/python/api.py +++ b/src/tox/tox_env/python/api.py @@ -40,6 +40,10 @@ class PythonInfo(NamedTuple): def impl_lower(self) -> str: return self.implementation.lower() + @property + def version_dot(self) -> str: + return f"{self.version_info.major}.{self.version_info.minor}" + class Python(ToxEnv, ABC): def __init__(self, create_args: ToxEnvCreateArgs) -> None: @@ -81,6 +85,14 @@ class Python(ToxEnv, ABC): desc="python executable from within the tox environment", value=lambda: self.env_python(), ) + self.conf.add_constant("py_dot_ver", "<python major>.<python minor>", value=self.py_dot_ver) + self.conf.add_constant("py_impl", "python implementation", value=self.py_impl) + + def py_dot_ver(self) -> str: + return self.base_python.version_dot + + def py_impl(self) -> str: + return self.base_python.impl_lower def _default_pass_env(self) -> list[str]: env = super()._default_pass_env()
tox-dev/tox
b8b0803cb8b295d520e19831ad5b7520fd45755c
diff --git a/tests/session/cmd/test_show_config.py b/tests/session/cmd/test_show_config.py index 95b422ac..cf2e719a 100644 --- a/tests/session/cmd/test_show_config.py +++ b/tests/session/cmd/test_show_config.py @@ -72,6 +72,15 @@ def test_show_config_unused(tox_project: ToxProjectCreator) -> None: assert "\n# !!! unused: magic, magical\n" in outcome.out +def test_show_config_py_ver_impl_constants(tox_project: ToxProjectCreator) -> None: + tox_ini = "[testenv]\npackage=skip\ndeps= {py_impl}{py_dot_ver}" + outcome = tox_project({"tox.ini": tox_ini}).run("c", "-e", "py", "-k", "py_dot_ver", "py_impl", "deps") + outcome.assert_success() + py_ver = ".".join(str(i) for i in sys.version_info[0:2]) + impl = sys.implementation.name + assert outcome.out == f"[testenv:py]\npy_dot_ver = {py_ver}\npy_impl = {impl}\ndeps = {impl}{py_ver}\n" + + def test_show_config_exception(tox_project: ToxProjectCreator) -> None: project = tox_project( {
Different basepython in tox 4 The content of `{basepython}` is different in tox 4, for instance this breaks using requirement files which names depend on the python version. AFAICT this does not seem to be clearly expected. ```console ❯ cat tox.ini [testenv] skip_install = True allowlist_externals = echo commands = echo {basepython} ❯ tox -e py310 py310 run-test-pre: PYTHONHASHSEED='1129533865' py310 run-test: commands[0] | echo python3.10 python3.10 _________________________________________ summary _________________________________________ py310: commands succeeded congratulations :) ❯ tox4 r -e py310 py310: commands[0]> echo py310 py310 py310: OK (0.04=setup[0.03]+cmd[0.00] seconds) congratulations :) (0.08 seconds) ```
0.0
b8b0803cb8b295d520e19831ad5b7520fd45755c
[ "tests/session/cmd/test_show_config.py::test_show_config_py_ver_impl_constants" ]
[ "tests/session/cmd/test_show_config.py::test_show_config_ini_comment_path", "tests/session/cmd/test_show_config.py::test_show_config_select_only", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_skip", "tests/session/cmd/test_show_config.py::test_show_config_alias", "tests/session/cmd/test_show_config.py::test_show_config_timeout_custom", "tests/session/cmd/test_show_config.py::test_show_config_core_host_python", "tests/session/cmd/test_show_config.py::test_show_config_exception", "tests/session/cmd/test_show_config.py::test_show_config_commands", "tests/session/cmd/test_show_config.py::test_show_config_timeout_default", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[True]", "tests/session/cmd/test_show_config.py::test_show_config_filter_keys", "tests/session/cmd/test_show_config.py::test_show_config_description_normalize", "tests/session/cmd/test_show_config.py::test_show_config_default_run_env", "tests/session/cmd/test_show_config.py::test_show_config_help", "tests/session/cmd/test_show_config.py::test_show_config_cli_flag", "tests/session/cmd/test_show_config.py::test_show_config_unused", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[False]", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_once" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-14 20:10:01+00:00
mit
6,083
tox-dev__tox-2907
diff --git a/docs/changelog/2702.bugfix.rst b/docs/changelog/2702.bugfix.rst new file mode 100644 index 00000000..7f3e64ee --- /dev/null +++ b/docs/changelog/2702.bugfix.rst @@ -0,0 +1,1 @@ +Forward ``HOME`` by default - by :user:`gschaffner`. diff --git a/src/tox/tox_env/api.py b/src/tox/tox_env/api.py index 1542a8fc..fcfc9e4b 100644 --- a/src/tox/tox_env/api.py +++ b/src/tox/tox_env/api.py @@ -218,6 +218,7 @@ class ToxEnv(ABC): "CPPFLAGS", # C++ compiler flags "LD_LIBRARY_PATH", # location of libs "LDFLAGS", # linker flags + "HOME", # needed for `os.path.expanduser()` on non-Windows systems ] if sys.stdout.isatty(): # if we're on a interactive shell pass on the TERM env.append("TERM")
tox-dev/tox
4408cff65d72d5662e85da632e74154dfc030ef2
diff --git a/tests/session/cmd/test_show_config.py b/tests/session/cmd/test_show_config.py index 9ef9f300..46a04246 100644 --- a/tests/session/cmd/test_show_config.py +++ b/tests/session/cmd/test_show_config.py @@ -117,7 +117,7 @@ def test_pass_env_config_default(tox_project: ToxProjectCreator, stdout_is_atty: expected = ( ["CC", "CCSHARED", "CFLAGS"] + (["COMSPEC"] if is_win else []) - + ["CPPFLAGS", "CURL_CA_BUNDLE", "CXX", "LANG", "LANGUAGE", "LDFLAGS", "LD_LIBRARY_PATH"] + + ["CPPFLAGS", "CURL_CA_BUNDLE", "CXX", "HOME", "LANG", "LANGUAGE", "LDFLAGS", "LD_LIBRARY_PATH"] + (["MSYSTEM", "NUMBER_OF_PROCESSORS", "PATHEXT"] if is_win else []) + ["PIP_*", "PKG_CONFIG", "PKG_CONFIG_PATH", "PKG_CONFIG_SYSROOT_DIR"] + (["PROCESSOR_ARCHITECTURE"] if is_win else [])
Tox 4 breaks in CI/CD pipelines where user does not exist ## Issue Starting with Tox 4, tox is failing to run unittests due to an exception in code trying to determiner HOME directory. ## Environment Our environment is using Jenkins with Docker based declarative pipelines but for the sake of the bug report, I'll demonstrate the problem with a direct Docker setup. ```console $ git clone https://github.com/psf/requests $ docker run --rm -it -u $UID -v $PWD:/src -w /src -e HOME=/src python:3.7 bash I have no name!@ffa04e72c39f:~$ pip freeze cachetools==5.2.0 chardet==5.1.0 colorama==0.4.6 distlib==0.3.6 filelock==3.8.2 importlib-metadata==5.1.0 packaging==22.0 platformdirs==2.6.0 pluggy==1.0.0 py==1.11.0 pyproject_api==1.2.1 six==1.16.0 tomli==2.0.1 tox==3.27.1 typing_extensions==4.4.0 virtualenv==20.17.1 zipp==3.11.0 ## Output of running tox Provide the output of `tox -rvv`: Moved the first comment as it makes the report exceed maximum size. ## Minimal example If possible, provide a minimal reproducer for the issue: ```console $ git clone https://github.com/psf/requests $ docker run --rm -it -u $UID -v $PWD:/src -w /src -e HOME=/src python:3.7 bash I have no name!@ffa04e72c39f:~$ pip install "tox<4" I have no name!@ffa04e72c39f:~$ .local/bin/tox -e py37 ---> works I have no name!@ffa04e72c39f:~$ pip install -U "tox" I have no name!@ffa04e72c39f:~$ .local/bin/tox -e py37 ---> fails ``` Blocking Tox to <4 does not seem to work for all our packages but I could reproduce our issue with requests at least so you can get an early report of the problem. You can see HOME environment variable is set on the Docker command line which we are doing in our Jenkins pipelines as well. We've had a similar issue in the past with running Spark based unittests as JVM is very picky about its environment but we would really like to avoid apply the same hack to get it to work with tox 4+.
0.0
4408cff65d72d5662e85da632e74154dfc030ef2
[ "tests/session/cmd/test_show_config.py::test_pass_env_config_default[True]", "tests/session/cmd/test_show_config.py::test_pass_env_config_default[False]" ]
[ "tests/session/cmd/test_show_config.py::test_show_config_default_run_env", "tests/session/cmd/test_show_config.py::test_show_config_commands", "tests/session/cmd/test_show_config.py::test_show_config_filter_keys", "tests/session/cmd/test_show_config.py::test_show_config_unused", "tests/session/cmd/test_show_config.py::test_show_config_py_ver_impl_constants", "tests/session/cmd/test_show_config.py::test_show_config_exception", "tests/session/cmd/test_show_config.py::test_show_config_empty_install_command_exception", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_once", "tests/session/cmd/test_show_config.py::test_show_config_pkg_env_skip", "tests/session/cmd/test_show_config.py::test_show_config_select_only", "tests/session/cmd/test_show_config.py::test_show_config_alias", "tests/session/cmd/test_show_config.py::test_show_config_description_normalize", "tests/session/cmd/test_show_config.py::test_show_config_ini_comment_path", "tests/session/cmd/test_show_config.py::test_show_config_cli_flag", "tests/session/cmd/test_show_config.py::test_show_config_timeout_default", "tests/session/cmd/test_show_config.py::test_show_config_timeout_custom", "tests/session/cmd/test_show_config.py::test_show_config_help", "tests/session/cmd/test_show_config.py::test_show_config_core_host_python", "tests/session/cmd/test_show_config.py::test_show_config_matching_env_section", "tests/session/cmd/test_show_config.py::test_package_env_inherits_from_pkgenv" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-01-30 09:42:47+00:00
mit
6,084
tox-dev__tox-3013
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 43128a4a..dac77aba 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,7 +17,7 @@ repos: - id: add-trailing-comma args: [--py36-plus] - repo: https://github.com/asottile/pyupgrade - rev: v3.3.1 + rev: v3.4.0 hooks: - id: pyupgrade args: ["--py37-plus"] @@ -52,7 +52,7 @@ repos: hooks: - id: flake8 additional_dependencies: - - flake8-bugbear==23.3.23 + - flake8-bugbear==23.5.9 - flake8-comprehensions==3.12 - flake8-pytest-style==1.7.2 - flake8-spellcheck==0.28 @@ -69,7 +69,7 @@ repos: - "@prettier/[email protected]" args: ["--print-width=120", "--prose-wrap=always"] - repo: https://github.com/igorshubovych/markdownlint-cli - rev: v0.33.0 + rev: v0.34.0 hooks: - id: markdownlint - repo: local diff --git a/docs/changelog/2925.bugfix.rst b/docs/changelog/2925.bugfix.rst new file mode 100644 index 00000000..f74003a9 --- /dev/null +++ b/docs/changelog/2925.bugfix.rst @@ -0,0 +1,1 @@ +Fix ``tox --devenv venv`` invocation without ``-e`` - by :user:`asottile`. diff --git a/pyproject.toml b/pyproject.toml index 87c2ce55..82810864 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ build-backend = "hatchling.build" requires = [ "hatch-vcs>=0.3", - "hatchling>=1.14", + "hatchling>=1.17", ] [project] @@ -51,23 +51,23 @@ dependencies = [ "cachetools>=5.3", "chardet>=5.1", "colorama>=0.4.6", - "filelock>=3.11", - 'importlib-metadata>=6.4.1; python_version < "3.8"', + "filelock>=3.12", + 'importlib-metadata>=6.6; python_version < "3.8"', "packaging>=23.1", - "platformdirs>=3.2", + "platformdirs>=3.5.1", "pluggy>=1", "pyproject-api>=1.5.1", 'tomli>=2.0.1; python_version < "3.11"', - 'typing-extensions>=4.5; python_version < "3.8"', - "virtualenv>=20.21", + 'typing-extensions>=4.6.2; python_version < "3.8"', + "virtualenv>=20.23", ] optional-dependencies.docs = [ - "furo>=2023.3.27", - "sphinx>=6.1.3", + "furo>=2023.5.20", + "sphinx>=7.0.1", "sphinx-argparse-cli>=1.11", "sphinx-autodoc-typehints!=1.23.4,>=1.23", "sphinx-copybutton>=0.5.2", - "sphinx-inline-tabs>=2022.1.2b11", + "sphinx-inline-tabs>=2023.4.21", "sphinxcontrib-towncrier>=0.2.1a0", "towncrier>=22.12", ] @@ -79,12 +79,12 @@ optional-dependencies.testing = [ "distlib>=0.3.6", "flaky>=3.7", "hatch-vcs>=0.3", - "hatchling>=1.14", - "psutil>=5.9.4", + "hatchling>=1.17", + "psutil>=5.9.5", "pytest>=7.3.1", - "pytest-cov>=4", + "pytest-cov>=4.1", "pytest-mock>=3.10", - "pytest-xdist>=3.2.1", + "pytest-xdist>=3.3.1", "re-assert>=1.1", 'time-machine>=2.9; implementation_name != "pypy"', "wheel>=0.40", diff --git a/src/tox/session/cmd/legacy.py b/src/tox/session/cmd/legacy.py index e92c3d27..82938d13 100644 --- a/src/tox/session/cmd/legacy.py +++ b/src/tox/session/cmd/legacy.py @@ -104,6 +104,8 @@ def legacy(state: State) -> int: if option.list_envs or option.list_envs_all: return list_env(state) if option.devenv_path: + if option.env.is_default_list: + option.env = CliEnv(["py"]) option.devenv_path = Path(option.devenv_path) return devenv(state) if option.parallel != 0: # only 0 means sequential diff --git a/tox.ini b/tox.ini index 13810f63..cf0a2b92 100644 --- a/tox.ini +++ b/tox.ini @@ -41,7 +41,7 @@ commands = description = format the code base to adhere to our styles, and complain about what we cannot do automatically skip_install = true deps = - pre-commit>=3.2.2 + pre-commit>=3.3.2 pass_env = {[testenv]passenv} PROGRAMDATA @@ -52,9 +52,9 @@ commands = [testenv:type] description = run type check on code base deps = - mypy==1.2 + mypy==1.3 types-cachetools>=5.3.0.5 - types-chardet>=5.0.4.3 + types-chardet>=5.0.4.6 commands = mypy src/tox mypy tests
tox-dev/tox
3238abf7e95fa7c5c041554452f4cee055f6c0d7
diff --git a/tests/session/cmd/test_legacy.py b/tests/session/cmd/test_legacy.py index 957149b6..73cc397a 100644 --- a/tests/session/cmd/test_legacy.py +++ b/tests/session/cmd/test_legacy.py @@ -78,14 +78,27 @@ def test_legacy_list_all(tox_project: ToxProjectCreator, mocker: MockerFixture, assert outcome.state.conf.options.show_core is False -def test_legacy_devenv(tox_project: ToxProjectCreator, mocker: MockerFixture, tmp_path: Path) -> None: - devenv = mocker.patch("tox.session.cmd.legacy.devenv") [email protected]( + "args", + [ + pytest.param((), id="empty"), + pytest.param(("-e", "py"), id="select"), + ], +) +def test_legacy_devenv( + tox_project: ToxProjectCreator, + mocker: MockerFixture, + tmp_path: Path, + args: tuple[str, ...], +) -> None: + run_sequential = mocker.patch("tox.session.cmd.devenv.run_sequential") into = tmp_path / "b" - outcome = tox_project({"tox.ini": ""}).run("le", "--devenv", str(into), "-e", "py") + outcome = tox_project({"tox.ini": ""}).run("le", "--devenv", str(into), *args) - assert devenv.call_count == 1 + assert run_sequential.call_count == 1 assert outcome.state.conf.options.devenv_path == into + assert set(outcome.state.conf.options.env) == {"py"} def test_legacy_run_parallel(tox_project: ToxProjectCreator, mocker: MockerFixture) -> None:
"IndexError: list index out of range" when using --devenv flag ## Issue Got following error: ``` tox --devenv venv Traceback (most recent call last): File "/Users/xzk/.local/bin/tox", line 8, in <module> sys.exit(run()) File "/Users/xzk/.local/pipx/venvs/tox/lib/python3.9/site-packages/tox/run.py", line 19, in run result = main(sys.argv[1:] if args is None else args) File "/Users/xzk/.local/pipx/venvs/tox/lib/python3.9/site-packages/tox/run.py", line 45, in main result = handler(state) File "/Users/xzk/.local/pipx/venvs/tox/lib/python3.9/site-packages/tox/session/cmd/legacy.py", line 108, in legacy return devenv(state) File "/Users/xzk/.local/pipx/venvs/tox/lib/python3.9/site-packages/tox/session/cmd/devenv.py", line 38, in devenv state.conf.memory_seed_loaders[list(opt.env)[0]].append(loader) IndexError: list index out of range ``` ``` ╰─ which tox /Users/xzk/.local/bin/tox ``` Tried to execute with `tox` installed in my virtual environment `myenv` ``` which python3 ─╯ /Users/xzk/workplace/my_project/myenv/bin/python3 ``` ```console ╰─ python3 -m tox -vvvv --devenv venv-dev ROOT: 275 D setup logging to NOTSET on pid 20334 [tox/report.py:221] Traceback (most recent call last): File "/Users/xzk/opt/anaconda3/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/Users/xzk/opt/anaconda3/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/Users/xzk/workplace/my_project/myenv/lib/python3.9/site-packages/tox/__main__.py", line 6, in <module> run() File "/Users/xzk/workplace/my_project/myenv/lib/python3.9/site-packages/tox/run.py", line 19, in run result = main(sys.argv[1:] if args is None else args) File "/Users/xzk/workplace/my_project/myenv/lib/python3.9/site-packages/tox/run.py", line 45, in main result = handler(state) File "/Users/xzk/workplace/my_project/myenv/lib/python3.9/site-packages/tox/session/cmd/legacy.py", line 108, in legacy return devenv(state) File "/Users/xzk/workplace/my_project/myenv/lib/python3.9/site-packages/tox/session/cmd/devenv.py", line 38, in devenv state.conf.memory_seed_loaders[list(opt.env)[0]].append(loader) IndexError: list index out of range ``` My `tox.ini` ``` [tox] envlist = py39 skip_missing_interpreters = True [testenv] deps = -e.[test] commands = pytest {posargs: ../tests/python_tests} ``` My setup.py ``` # setup.py from setuptools import setup from setuptools import find_packages setup( name='my_pkg', version='0.1.0', python_requires=">=3.8.0", packages=find_packages(), install_requires=["numpy>=1.24.2", "pandas>=1.5.3", "torch>=1.13.1", "tqdm>=4.64.1", "matplotlib>=3.6.3", "scikit-learn>=1.2.1", "pyarrow>=11.0.0"], extras_require=dict( test=[ 'pytest', ] ), ) ``` ## Environment Provide at least: - OS: MacOS Monterry - `pip list` of the host Python where `tox` is installed: ```console ╰─ pip list ─╯ Package Version ----------------- -------- attrs 22.2.0 cachetools 5.3.0 chardet 5.1.0 colorama 0.4.6 contourpy 1.0.7 cycler 0.11.0 distlib 0.3.6 exceptiongroup 1.1.0 filelock 3.9.0 fonttools 4.38.0 iniconfig 2.0.0 joblib 1.2.0 kiwisolver 1.4.4 matplotlib 3.6.3 numpy 1.24.2 packaging 23.0 pandas 1.5.3 Pillow 9.4.0 pip 23.0 platformdirs 3.0.0 pluggy 1.0.0 pyarrow 11.0.0 pyparsing 3.0.9 pyproject_api 1.5.0 pytest 7.2.1 pytest-mock 3.10.0 python-dateutil 2.8.2 pytz 2022.7.1 scikit-learn 1.2.1 scipy 1.10.0 setuptools 58.1.0 six 1.16.0 threadpoolctl 3.1.0 tomli 2.0.1 torch 1.13.1 tox 4.4.5 tqdm 4.64.1 typing_extensions 4.4.0 virtualenv 20.19. ``` ## Output of running tox Provide the output of `tox -rvv`: Please see above. ## Minimal example If possible, provide a minimal reproducer for the issue: ```console ```
0.0
3238abf7e95fa7c5c041554452f4cee055f6c0d7
[ "tests/session/cmd/test_legacy.py::test_legacy_devenv[empty]" ]
[ "tests/session/cmd/test_legacy.py::test_legacy_show_config", "tests/session/cmd/test_legacy.py::test_legacy_show_config_with_env", "tests/session/cmd/test_legacy.py::test_legacy_list_default[0]", "tests/session/cmd/test_legacy.py::test_legacy_list_default[1]", "tests/session/cmd/test_legacy.py::test_legacy_list_default[2]", "tests/session/cmd/test_legacy.py::test_legacy_list_env_with_empty_or_missing_env_list[missing", "tests/session/cmd/test_legacy.py::test_legacy_list_env_with_empty_or_missing_env_list[empty", "tests/session/cmd/test_legacy.py::test_legacy_list_all[0]", "tests/session/cmd/test_legacy.py::test_legacy_list_all[1]", "tests/session/cmd/test_legacy.py::test_legacy_list_all[2]", "tests/session/cmd/test_legacy.py::test_legacy_devenv[select]", "tests/session/cmd/test_legacy.py::test_legacy_run_parallel", "tests/session/cmd/test_legacy.py::test_legacy_run_sequential", "tests/session/cmd/test_legacy.py::test_legacy_help", "tests/session/cmd/test_legacy.py::test_legacy_cli_flags" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-13 17:54:07+00:00
mit
6,085
tox-dev__tox-3024
diff --git a/docs/changelog/3024.feature.rst b/docs/changelog/3024.feature.rst new file mode 100644 index 00000000..d63fa00d --- /dev/null +++ b/docs/changelog/3024.feature.rst @@ -0,0 +1,2 @@ +Addded ``--list-dependencies`` and ``--no-list-dependencies`` CLI parameters. +If unspecified, defaults to listing when in CI, but not otherwise. diff --git a/src/tox/session/cmd/run/common.py b/src/tox/session/cmd/run/common.py index 49aeb87b..2846f8d9 100644 --- a/src/tox/session/cmd/run/common.py +++ b/src/tox/session/cmd/run/common.py @@ -22,6 +22,7 @@ from tox.session.cmd.run.single import ToxEnvRunResult, run_one from tox.session.state import State from tox.tox_env.api import ToxEnv from tox.tox_env.runner import RunToxEnv +from tox.util.ci import is_ci from tox.util.graph import stable_topological_sort from tox.util.spinner import MISS_DURATION, Spinner @@ -156,6 +157,19 @@ def env_run_create_flags(parser: ArgumentParser, mode: str) -> None: help="if recreate is set do not recreate packaging tox environment(s)", action="store_true", ) + list_deps = parser.add_mutually_exclusive_group() + list_deps.add_argument( + "--list-dependencies", + action="store_true", + default=is_ci(), + help="list the dependencies installed during environment setup", + ) + list_deps.add_argument( + "--no-list-dependencies", + action="store_false", + dest="list_dependencies", + help="never list the dependencies installed during environment setup", + ) if mode not in ("devenv", "config", "depends"): parser.add_argument( "--skip-pkg-install", diff --git a/src/tox/tox_env/python/api.py b/src/tox/tox_env/python/api.py index da9e435f..6e57626e 100644 --- a/src/tox/tox_env/python/api.py +++ b/src/tox/tox_env/python/api.py @@ -15,7 +15,6 @@ from virtualenv.discovery.py_spec import PythonSpec from tox.config.main import Config from tox.tox_env.api import ToxEnv, ToxEnvCreateArgs from tox.tox_env.errors import Fail, Recreate, Skip -from tox.util.ci import is_ci class VersionInfo(NamedTuple): @@ -227,12 +226,11 @@ class Python(ToxEnv, ABC): def _done_with_setup(self) -> None: """called when setup is done""" super()._done_with_setup() - running_in_ci = is_ci() - if self.journal or running_in_ci: + if self.journal or self.options.list_dependencies: outcome = self.installer.installed() if self.journal: self.journal["installed_packages"] = outcome - if running_in_ci: + if self.options.list_dependencies: logging.warning(",".join(outcome)) def python_cache(self) -> dict[str, Any]:
tox-dev/tox
716564208c1853f3256d20bf3c508652f1df70b8
diff --git a/tests/config/cli/test_cli_env_var.py b/tests/config/cli/test_cli_env_var.py index 61dbf962..1d83175e 100644 --- a/tests/config/cli/test_cli_env_var.py +++ b/tests/config/cli/test_cli_env_var.py @@ -10,6 +10,7 @@ from tox.config.loader.api import Override from tox.pytest import CaptureFixture, LogCaptureFixture, MonkeyPatch from tox.session.env_select import CliEnv from tox.session.state import State +from tox.util.ci import is_ci def test_verbose() -> None: @@ -63,6 +64,7 @@ def test_verbose_no_test() -> None: "factors": [], "labels": [], "skip_env": "", + "list_dependencies": is_ci(), } @@ -121,6 +123,7 @@ def test_env_var_exhaustive_parallel_values( "labels": [], "exit_and_dump_after": 0, "skip_env": "", + "list_dependencies": is_ci(), } assert options.parsed.verbosity == 4 assert options.cmd_handlers == core_handlers diff --git a/tests/config/cli/test_cli_ini.py b/tests/config/cli/test_cli_ini.py index c7324e1a..623a56f5 100644 --- a/tests/config/cli/test_cli_ini.py +++ b/tests/config/cli/test_cli_ini.py @@ -19,6 +19,7 @@ from tox.config.source import discover_source from tox.pytest import CaptureFixture, LogCaptureFixture, MonkeyPatch from tox.session.env_select import CliEnv from tox.session.state import State +from tox.util.ci import is_ci @pytest.fixture() @@ -102,6 +103,7 @@ def default_options() -> dict[str, Any]: "labels": [], "exit_and_dump_after": 0, "skip_env": "", + "list_dependencies": is_ci(), } @@ -139,6 +141,7 @@ def test_ini_exhaustive_parallel_values(core_handlers: dict[str, Callable[[State "labels": [], "exit_and_dump_after": 0, "skip_env": "", + "list_dependencies": is_ci(), } assert options.parsed.verbosity == 4 assert options.cmd_handlers == core_handlers diff --git a/tests/tox_env/python/test_python_api.py b/tests/tox_env/python/test_python_api.py index 3348acda..a9ff7522 100644 --- a/tests/tox_env/python/test_python_api.py +++ b/tests/tox_env/python/test_python_api.py @@ -218,9 +218,25 @@ def test_python_set_hash_seed_incorrect(tox_project: ToxProjectCreator) -> None: @pytest.mark.parametrize("in_ci", [True, False]) def test_list_installed_deps(in_ci: bool, tox_project: ToxProjectCreator, mocker: MockerFixture) -> None: - mocker.patch("tox.tox_env.python.api.is_ci", return_value=in_ci) + mocker.patch("tox.session.cmd.run.common.is_ci", return_value=in_ci) result = tox_project({"tox.ini": "[testenv]\nskip_install = true"}).run("r", "-e", "py") if in_ci: assert "pip==" in result.out else: assert "pip==" not in result.out + + [email protected]("list_deps", ["--list-dependencies", "--no-list-dependencies"]) [email protected]("in_ci", [True, False]) +def test_list_installed_deps_explicit_cli( + list_deps: str, + in_ci: bool, + tox_project: ToxProjectCreator, + mocker: MockerFixture, +) -> None: + mocker.patch("tox.session.cmd.run.common.is_ci", return_value=in_ci) + result = tox_project({"tox.ini": "[testenv]\nskip_install = true"}).run(list_deps, "r", "-e", "py") + if list_deps == "--list-dependencies": + assert "pip==" in result.out + else: + assert "pip==" not in result.out
Allow CI runs to disable listing dependencies ## What's the problem this feature will solve? <!-- What are you trying to do, that you are unable to achieve with tox as it currently stands? --> Right now CI runs always list dependencies for each environment. While this is often nice, it can result in excessive output, especially when using tox to run linters and other tools. ## Describe the solution you'd like <!-- Clear and concise description of what you want to happen. --> If `list_dependencies_command` is explicitly set as an empty string for an environment, skip the listing dependencies command. <!-- Provide examples of real world use cases that this would enable and how it solves the problem described above. --> ## Alternative Solutions <!-- Have you tried to workaround the problem using tox or other tools? Or a different approach to solving this issue? Please elaborate here. --> One alternative would be a separate configuration option for an environment to specifically disable listing dependencies. ## Additional context <!-- Add any other context, links, etc. about the feature here. --> snapcraft and several other projects use tox to run our linters. However, when running in CI, it can be difficult to find specific linting failures between all the `pip freeze` lines: ![image](https://github.com/tox-dev/tox/assets/4305943/1a51f38a-74ec-4fac-925d-736db96b4301)
0.0
716564208c1853f3256d20bf3c508652f1df70b8
[ "tests/config/cli/test_cli_env_var.py::test_verbose_no_test", "tests/config/cli/test_cli_env_var.py::test_env_var_exhaustive_parallel_values", "tests/config/cli/test_cli_ini.py::test_ini_empty[[tox]]", "tests/config/cli/test_cli_ini.py::test_ini_empty[]", "tests/config/cli/test_cli_ini.py::test_ini_exhaustive_parallel_values", "tests/config/cli/test_cli_ini.py::test_bad_cli_ini", "tests/config/cli/test_cli_ini.py::test_bad_option_cli_ini", "tests/tox_env/python/test_python_api.py::test_list_installed_deps[True]", "tests/tox_env/python/test_python_api.py::test_list_installed_deps[False]", "tests/tox_env/python/test_python_api.py::test_list_installed_deps_explicit_cli[True---list-dependencies]", "tests/tox_env/python/test_python_api.py::test_list_installed_deps_explicit_cli[True---no-list-dependencies]", "tests/tox_env/python/test_python_api.py::test_list_installed_deps_explicit_cli[False---list-dependencies]", "tests/tox_env/python/test_python_api.py::test_list_installed_deps_explicit_cli[False---no-list-dependencies]" ]
[ "tests/config/cli/test_cli_env_var.py::test_verbose", "tests/config/cli/test_cli_env_var.py::test_verbose_compound", "tests/config/cli/test_cli_env_var.py::test_ini_help", "tests/config/cli/test_cli_env_var.py::test_bad_env_var", "tests/config/cli/test_cli_ini.py::test_ini_help", "tests/config/cli/test_cli_ini.py::test_cli_ini_with_interpolated", "tests/config/cli/test_cli_ini.py::test_conf_arg[ini-dir]", "tests/config/cli/test_cli_ini.py::test_conf_arg[ini]", "tests/config/cli/test_cli_ini.py::test_conf_arg[cfg-dir]", "tests/config/cli/test_cli_ini.py::test_conf_arg[cfg]", "tests/config/cli/test_cli_ini.py::test_conf_arg[toml-dir]", "tests/config/cli/test_cli_ini.py::test_conf_arg[toml]", "tests/tox_env/python/test_python_api.py::test_requirements_txt", "tests/tox_env/python/test_python_api.py::test_conflicting_base_python_factor", "tests/tox_env/python/test_python_api.py::test_diff_msg_added_removed_changed", "tests/tox_env/python/test_python_api.py::test_diff_msg_no_diff", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py3-py3]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py311-py311]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py3.12-py3.12]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[pypy2-pypy2]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[rustpython3-rustpython3]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[cpython3.8-cpython3.8]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[ironpython2.7-ironpython2.7]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[functional-py310-py310]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[bar-pypy2-foo-pypy2]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[django-32-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[eslint-8.3-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py-310-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[py3000-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[4.foo-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[310-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[5-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[2000-None]", "tests/tox_env/python/test_python_api.py::test_extract_base_python[4000-None]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-pypy-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-pypy-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_no_conflict[magic-py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy-cpython-pypy-cpython-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy-cpython-pypy-cpython-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy2-pypy3-pypy2-pypy3-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[pypy2-pypy3-pypy2-pypy3-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py3-py2-py3-py2-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py3-py2-py3-py2-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-py39-py38-py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-py39-py38-py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-py38|py39-py38-py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-py38|py39-py38-py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-python3-py38-python3-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py38-python3-py38-python3-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py310-py38|py39-py310-py38|py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py310-py38|py39-py310-py38|py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py3.11-py310-py3.11-py310-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py3.11-py310-py3.11-py310-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py310-magic-py39-py310-py39-True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict[py310-magic-py39-py310-py39-False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict_show_conf[True]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict_show_conf[False]", "tests/tox_env/python/test_python_api.py::test_base_python_env_conflict_show_conf[None]", "tests/tox_env/python/test_python_api.py::test_python_set_hash_seed", "tests/tox_env/python/test_python_api.py::test_python_generate_hash_seed", "tests/tox_env/python/test_python_api.py::test_python_keep_hash_seed", "tests/tox_env/python/test_python_api.py::test_python_disable_hash_seed", "tests/tox_env/python/test_python_api.py::test_python_set_hash_seed_negative", "tests/tox_env/python/test_python_api.py::test_python_set_hash_seed_incorrect" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-03 01:18:53+00:00
mit
6,086
tox-dev__tox-3123
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e78e4b05..c93da511 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,7 +5,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black - rev: 23.7.0 + rev: 23.9.1 hooks: - id: black - repo: https://github.com/codespell-project/codespell diff --git a/docs/changelog/3084.bugfix.rst b/docs/changelog/3084.bugfix.rst new file mode 100644 index 00000000..687acbd1 --- /dev/null +++ b/docs/changelog/3084.bugfix.rst @@ -0,0 +1,1 @@ +Fix ``quickstart`` command from requiring ``root`` positional argument diff --git a/src/tox/session/cmd/quickstart.py b/src/tox/session/cmd/quickstart.py index 30802399..575a5223 100644 --- a/src/tox/session/cmd/quickstart.py +++ b/src/tox/session/cmd/quickstart.py @@ -27,6 +27,7 @@ def tox_add_option(parser: ToxParser) -> None: "quickstart_root", metavar="root", default=Path().absolute(), + nargs="?", help="folder to create the tox.ini file", type=Path, )
tox-dev/tox
0799354d44a1585b89240d424309faff8f25a7ed
diff --git a/tests/session/cmd/test_quickstart.py b/tests/session/cmd/test_quickstart.py index 6effff29..f4672caf 100644 --- a/tests/session/cmd/test_quickstart.py +++ b/tests/session/cmd/test_quickstart.py @@ -53,3 +53,8 @@ def test_quickstart_refuse(tox_project: ToxProjectCreator) -> None: def test_quickstart_help(tox_project: ToxProjectCreator) -> None: outcome = tox_project({"tox.ini": ""}).run("q", "-h") outcome.assert_success() + + +def test_quickstart_no_args(tox_project: ToxProjectCreator) -> None: + outcome = tox_project({}).run("q") + outcome.assert_success()
tox quickstart: error: the following arguments are required: root ## Issue I ran `tox quickstart` as described in https://tox.wiki/en/latest/user_guide.html. and get the error `tox quickstart: error: the following arguments are required: root`. It seems that either the default parameter that should select the current working environment seems to be broken or the documentation should be updated. ## Environment Provide at least: - OS: Windows 11 <details open> <summary>Output of <code>pip list</code> of the host Python, where <code>tox</code> is installed</summary> ```console Python version: 3.11 Packages: No idea, I installed with pipx ``` </details> Thanks a lot for developing this super useful library!
0.0
0799354d44a1585b89240d424309faff8f25a7ed
[ "tests/session/cmd/test_quickstart.py::test_quickstart_no_args" ]
[ "tests/session/cmd/test_quickstart.py::test_quickstart_ok", "tests/session/cmd/test_quickstart.py::test_quickstart_refuse", "tests/session/cmd/test_quickstart.py::test_quickstart_help" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-09-11 17:14:10+00:00
mit
6,087
tox-dev__tox-3159
diff --git a/docs/changelog/3158.bugfix.rst b/docs/changelog/3158.bugfix.rst new file mode 100644 index 00000000..e7391238 --- /dev/null +++ b/docs/changelog/3158.bugfix.rst @@ -0,0 +1,1 @@ +``--parallel-no-spinner`` flag now implies ``--parallel`` diff --git a/docs/user_guide.rst b/docs/user_guide.rst index d08be62a..73a475df 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -394,8 +394,8 @@ Parallel mode - ``auto`` to limit it to CPU count, - or pass an integer to set that limit. - Parallel mode displays a progress spinner while running tox environments in parallel, and reports outcome of these as - soon as they have been completed with a human readable duration timing attached. This spinner can be disabled via the - ``--parallel-no-spinner`` flag. + soon as they have been completed with a human readable duration timing attached. To run parallelly without the spinner, + you can use the ``--parallel-no-spinner`` flag. - Parallel mode by default shows output only of failed environments and ones marked as :ref:`parallel_show_output` ``=True``. - There's now a concept of dependency between environments (specified via :ref:`depends`), tox will re-order the diff --git a/src/tox/session/cmd/legacy.py b/src/tox/session/cmd/legacy.py index 92a91fcf..a78d8bac 100644 --- a/src/tox/session/cmd/legacy.py +++ b/src/tox/session/cmd/legacy.py @@ -110,7 +110,7 @@ def legacy(state: State) -> int: option.env = CliEnv(["py"]) option.devenv_path = Path(option.devenv_path) return devenv(state) - if option.parallel != 0: # only 0 means sequential + if option.parallel_no_spinner is True or option.parallel != 0: # only 0 means sequential return run_parallel(state) return run_sequential(state) diff --git a/src/tox/session/cmd/run/parallel.py b/src/tox/session/cmd/run/parallel.py index 9b7e2843..d02eb1f0 100644 --- a/src/tox/session/cmd/run/parallel.py +++ b/src/tox/session/cmd/run/parallel.py @@ -74,7 +74,7 @@ def parallel_flags( "--parallel-no-spinner", action="store_true", dest="parallel_no_spinner", - help="do not show the spinner", + help="run tox environments in parallel, but don't show the spinner, implies --parallel", ) @@ -83,7 +83,7 @@ def run_parallel(state: State) -> int: option = state.conf.options return execute( state, - max_workers=option.parallel, + max_workers=None if option.parallel_no_spinner is True else option.parallel, has_spinner=option.parallel_no_spinner is False and option.parallel_live is False, live=option.parallel_live, )
tox-dev/tox
ddb006f80182f40647aa2c2cd4d4928b2e136396
diff --git a/tests/session/cmd/test_parallel.py b/tests/session/cmd/test_parallel.py index 8ab93a78..a546a263 100644 --- a/tests/session/cmd/test_parallel.py +++ b/tests/session/cmd/test_parallel.py @@ -6,9 +6,11 @@ from signal import SIGINT from subprocess import PIPE, Popen from time import sleep from typing import TYPE_CHECKING +from unittest import mock import pytest +from tox.session.cmd.run import parallel from tox.session.cmd.run.parallel import parse_num_processes from tox.tox_env.api import ToxEnv from tox.tox_env.errors import Fail @@ -169,3 +171,28 @@ def test_parallel_requires_arg(tox_project: ToxProjectCreator) -> None: outcome = tox_project({"tox.ini": ""}).run("p", "-p", "-h") outcome.assert_failed() assert "argument -p/--parallel: expected one argument" in outcome.err + + +def test_parallel_no_spinner(tox_project: ToxProjectCreator) -> None: + """Ensure passing `--parallel-no-spinner` implies `--parallel`.""" + with mock.patch.object(parallel, "execute") as mocked: + tox_project({"tox.ini": ""}).run("p", "--parallel-no-spinner") + + mocked.assert_called_once_with( + mock.ANY, + max_workers=None, + has_spinner=False, + live=False, + ) + + +def test_parallel_no_spinner_legacy(tox_project: ToxProjectCreator) -> None: + with mock.patch.object(parallel, "execute") as mocked: + tox_project({"tox.ini": ""}).run("--parallel-no-spinner") + + mocked.assert_called_once_with( + mock.ANY, + max_workers=None, + has_spinner=False, + live=False, + )
`--parallel-no-spinner` should imply `--parallel` ## Issue The flag `--parallel-no-spinner` reads like "the tests should run parallel, but don't show spinner". But if you just pass `--parallel-no-spinner` without also passing `--parallel`, it does nothing. I think the presence of this flag implies that we want to run the tests parallelly.
0.0
ddb006f80182f40647aa2c2cd4d4928b2e136396
[ "tests/session/cmd/test_parallel.py::test_parallel_no_spinner", "tests/session/cmd/test_parallel.py::test_parallel_no_spinner_legacy" ]
[ "tests/session/cmd/test_parallel.py::test_parse_num_processes_all", "tests/session/cmd/test_parallel.py::test_parse_num_processes_auto", "tests/session/cmd/test_parallel.py::test_parse_num_processes_exact", "tests/session/cmd/test_parallel.py::test_parse_num_processes_not_number", "tests/session/cmd/test_parallel.py::test_parse_num_processes_minus_one", "tests/session/cmd/test_parallel.py::test_parallel_general", "tests/session/cmd/test_parallel.py::test_parallel_run_live_out", "tests/session/cmd/test_parallel.py::test_parallel_show_output_with_pkg", "tests/session/cmd/test_parallel.py::test_keyboard_interrupt", "tests/session/cmd/test_parallel.py::test_parallels_help", "tests/session/cmd/test_parallel.py::test_parallel_legacy_accepts_no_arg", "tests/session/cmd/test_parallel.py::test_parallel_requires_arg" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-16 19:18:52+00:00
mit
6,088
tox-dev__tox-conda-144
diff --git a/tox_conda/plugin.py b/tox_conda/plugin.py index 8cfa2e4..d669718 100644 --- a/tox_conda/plugin.py +++ b/tox_conda/plugin.py @@ -160,14 +160,17 @@ def tox_testenv_create(venv, action): python = get_py_version(venv.envconfig, action) if venv.envconfig.conda_env is not None: + env_path = Path(venv.envconfig.conda_env) # conda env create does not have a --channel argument nor does it take # dependencies specifications (e.g., python=3.8). These must all be specified # in the conda-env.yml file yaml = YAML() - env_file = yaml.load(Path(venv.envconfig.conda_env)) + env_file = yaml.load(env_path) env_file["dependencies"].append(python) - with tempfile.NamedTemporaryFile(suffix=".yaml") as tmp_env: + with tempfile.NamedTemporaryFile( + dir=env_path.parent, prefix="tox_conda_tmp", suffix=".yaml" + ) as tmp_env: yaml.dump(env_file, tmp_env) args = [
tox-dev/tox-conda
041bd82aafe91f575a4877aec40233e4015a3f8f
diff --git a/tests/test_conda_env.py b/tests/test_conda_env.py index 6ef26ef..4435c15 100644 --- a/tests/test_conda_env.py +++ b/tests/test_conda_env.py @@ -281,6 +281,8 @@ def test_conda_env(tmpdir, newconfig, mocksession): with mocksession.newaction(venv.name, "getenv") as action: tox_testenv_create(action=action, venv=venv) + mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml") + pcalls = mocksession._pcalls assert len(pcalls) >= 1 call = pcalls[-1] @@ -291,8 +293,6 @@ def test_conda_env(tmpdir, newconfig, mocksession): assert call.args[5].startswith("--file") assert cmd[6] == str(mock_file().name) - mock_file.assert_any_call(suffix=".yaml") - yaml = YAML() tmp_env = yaml.load(mock_open_to_string(mock_file)) assert tmp_env["dependencies"][-1].startswith("python=") @@ -338,6 +338,8 @@ def test_conda_env_and_spec(tmpdir, newconfig, mocksession): with mocksession.newaction(venv.name, "getenv") as action: tox_testenv_create(action=action, venv=venv) + mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml") + pcalls = mocksession._pcalls assert len(pcalls) >= 1 call = pcalls[-1] @@ -348,8 +350,6 @@ def test_conda_env_and_spec(tmpdir, newconfig, mocksession): assert call.args[5].startswith("--file") assert cmd[6] == str(mock_file().name) - mock_file.assert_any_call(suffix=".yaml") - yaml = YAML() tmp_env = yaml.load(mock_open_to_string(mock_file)) assert tmp_env["dependencies"][-1].startswith("python=")
Behavior for relative paths in `environment.yml` changed. Hi, thanks for the package! Unfortunately, the new release broke my setup. The folder structure looks roughly like this ``` - docs - rtd_environment.yml - tox.ini - src - package ``` I use `rtd_environment.yml` in my `tox.ini` to create the environment for the documentation. The env file contains a pip section to install the package from the repo. ``` ... - dependencies: ... - pip: - -e ../ ``` With v0.10.0 the pip command fails. It says the directory does not contain a `setup.py` or `pyproject.toml` . Everything works with v0.9.2. The issue can be reproduced in this repo (https://github.com/pytask-dev/pytask/tree/e3c1a4cf6935a0c5cf14267acf9b5597261b3a7f) by typing `tox -e sphinx`.
0.0
041bd82aafe91f575a4877aec40233e4015a3f8f
[ "tests/test_conda_env.py::test_conda_env", "tests/test_conda_env.py::test_conda_env_and_spec" ]
[ "tests/test_conda_env.py::test_conda_create", "tests/test_conda_env.py::test_install_deps_no_conda", "tests/test_conda_env.py::test_install_conda_deps", "tests/test_conda_env.py::test_install_conda_no_pip", "tests/test_conda_env.py::test_update", "tests/test_conda_env.py::test_conda_spec", "tests/test_conda_env.py::test_empty_conda_spec_and_env", "tests/test_conda_env.py::test_conda_install_args", "tests/test_conda_env.py::test_conda_create_args", "tests/test_conda_env.py::test_verbosity" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-10-31 10:16:13+00:00
mit
6,089
tox-dev__tox-conda-161
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 762d974..4592cf4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: args: - --py3-plus - repo: https://github.com/PyCQA/isort - rev: 5.11.4 + rev: 5.12.0 hooks: - id: isort - repo: https://github.com/psf/black diff --git a/tox.ini b/tox.ini index ff58268..16db4ba 100644 --- a/tox.ini +++ b/tox.ini @@ -73,7 +73,7 @@ depends = [testenv:pkg_meta] description = check that the long description is valid -basepython = python3.9 +basepython = python3.10 skip_install = true deps = build>=0.0.4 diff --git a/tox_conda/plugin.py b/tox_conda/plugin.py index d669718..f93631f 100644 --- a/tox_conda/plugin.py +++ b/tox_conda/plugin.py @@ -168,22 +168,27 @@ def tox_testenv_create(venv, action): env_file = yaml.load(env_path) env_file["dependencies"].append(python) - with tempfile.NamedTemporaryFile( - dir=env_path.parent, prefix="tox_conda_tmp", suffix=".yaml" - ) as tmp_env: - yaml.dump(env_file, tmp_env) - - args = [ - venv.envconfig.conda_exe, - "env", - "create", - "-p", - envdir, - "--file", - tmp_env.name, - ] - - _run_conda_process(args, venv, action, basepath) + tmp_env = tempfile.NamedTemporaryFile( + dir=env_path.parent, + prefix="tox_conda_tmp", + suffix=".yaml", + delete=False, + ) + yaml.dump(env_file, tmp_env) + + args = [ + venv.envconfig.conda_exe, + "env", + "create", + "-p", + envdir, + "--file", + tmp_env.name, + ] + tmp_env.close() + _run_conda_process(args, venv, action, basepath) + Path(tmp_env.name).unlink() + else: args = [venv.envconfig.conda_exe, "create", "--yes", "-p", envdir] for channel in venv.envconfig.conda_channels:
tox-dev/tox-conda
099ec510c545581f8ff2efaac8616f232c5cf66a
diff --git a/tests/test_conda_env.py b/tests/test_conda_env.py index 4435c15..1756846 100644 --- a/tests/test_conda_env.py +++ b/tests/test_conda_env.py @@ -1,5 +1,6 @@ import io import os +import pathlib import re from unittest.mock import mock_open, patch @@ -278,10 +279,12 @@ def test_conda_env(tmpdir, newconfig, mocksession): mock_file = mock_open() with patch("tox_conda.plugin.tempfile.NamedTemporaryFile", mock_file): - with mocksession.newaction(venv.name, "getenv") as action: - tox_testenv_create(action=action, venv=venv) + with patch.object(pathlib.Path, "unlink", autospec=True) as mock_unlink: + with mocksession.newaction(venv.name, "getenv") as action: + tox_testenv_create(action=action, venv=venv) + mock_unlink.assert_called_once - mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml") + mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml", delete=False) pcalls = mocksession._pcalls assert len(pcalls) >= 1 @@ -335,10 +338,12 @@ def test_conda_env_and_spec(tmpdir, newconfig, mocksession): mock_file = mock_open() with patch("tox_conda.plugin.tempfile.NamedTemporaryFile", mock_file): - with mocksession.newaction(venv.name, "getenv") as action: - tox_testenv_create(action=action, venv=venv) + with patch.object(pathlib.Path, "unlink", autospec=True) as mock_unlink: + with mocksession.newaction(venv.name, "getenv") as action: + tox_testenv_create(action=action, venv=venv) + mock_unlink.assert_called_once - mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml") + mock_file.assert_called_with(dir=tmpdir, prefix="tox_conda_tmp", suffix=".yaml", delete=False) pcalls = mocksession._pcalls assert len(pcalls) >= 1
Permission error on conda environment temp file when running in Windows OS I am receiving the following error (in .tox/python/log/python-0.log) when running tox. ```python # Error snippet File "C:\Users\xxx\Anaconda3\lib\site-packages\conda_env\env.py", line 163, in from_file with open(filename, 'rb') as fp: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\yyy\\tox_conda_tmp13zv20n4.yaml' `$ C:\Users\xxx\Anaconda3\Scripts\conda-env-script.py create -p python --file C:\Users\yyy\tox_conda_tmp13zv20n4.yaml` ``` ### Steps to reproduce the error on Window OS (Windows 10). #### tox.ini ``` [tox] envlist = py310 skipsdist = True [testenv] conda_env = environment.yaml ``` #### environment.yaml ``` name: tox_environment dependencies: - python=3.10 - pytest=7.1.2 - tox=3.27.1 - tox-conda=0.10.1 ``` #### run the following commands on Windows OS ```bash # create conda env conda env create -f environment.yaml conda activate tox_environment # run tox tox ``` ### Suspected cause of error I suspect that the error might be due to the use of tempfile.NamedTemporaryFile in [plugins.py](https://github.com/tox-dev/tox-conda/blob/main/tox_conda/plugin.py#L171). As per [docs](https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile): > That name can be retrieved from the name attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows) Any help is appreciated, thanks!
0.0
099ec510c545581f8ff2efaac8616f232c5cf66a
[ "tests/test_conda_env.py::test_conda_env", "tests/test_conda_env.py::test_conda_env_and_spec" ]
[ "tests/test_conda_env.py::test_conda_create", "tests/test_conda_env.py::test_install_deps_no_conda", "tests/test_conda_env.py::test_install_conda_deps", "tests/test_conda_env.py::test_install_conda_no_pip", "tests/test_conda_env.py::test_update", "tests/test_conda_env.py::test_conda_spec", "tests/test_conda_env.py::test_empty_conda_spec_and_env", "tests/test_conda_env.py::test_conda_install_args", "tests/test_conda_env.py::test_conda_create_args", "tests/test_conda_env.py::test_verbosity" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-02-01 09:25:36+00:00
mit
6,090
tox-dev__tox-docker-19
diff --git a/README.md b/README.md index c99702c..efd4f4f 100644 --- a/README.md +++ b/README.md @@ -31,17 +31,24 @@ your test suite as it runs, as ordinary environment variables: POSTGRES_USER=username POSTGRES_DB=dbname -## Port Mapping +## Host and Port Mapping tox-docker runs docker with the "publish all ports" option. Any port the container exposes will be made available to your test suite via environment -variables of the form `<image-basename>_<exposed-port>_<proto>`. For +variables of the form `<image-basename>_<exposed-port>_<protocol>_PORT`. For instance, for the postgresql container, there will be an environment -variable `POSTGRES_5432_TCP` whose value is the ephemeral port number that -docker has bound the container's port 5432 to. +variable `POSTGRES_5432_TCP_PORT` whose value is the ephemeral port number +that docker has bound the container's port 5432 to. Likewise, exposed UDP ports will have environment variables like -`TELEGRAF_8092_UDP` whose value is the ephemeral port number that docker has -bound. NB! Since it's not possible to check whether UDP port is open it's -just mapping to environment variable without any checks that service up and -running. +`TELEGRAF_8092_UDP_PORT` Since it's not possible to check whether UDP port +is open it's just mapping to environment variable without any checks that +service up and running. + +The host name for each service is also exposed via environment as +`<image-basename>_HOST`, which is `POSTGRES_HOST` and `TELEGRAF_HOST` for +the two examples above. + +*Deprecation Note:* In older versions of tox-docker, the port was exposed as +`<image-basename>-<exposed-port>-<protocol>`. This additional environment +variable is deprecated, but will be supported until tox-docker 2.0. diff --git a/tox.ini b/tox.ini index cafee7d..f20bc70 100644 --- a/tox.ini +++ b/tox.ini @@ -1,11 +1,18 @@ [tox] -envlist = py27 +envlist = integration,registry -[testenv] +[testenv:integration] docker = nginx:1.13-alpine - telegraf:1.8-alpine + ksdn117/tcp-udp-test dockerenv = ENV_VAR=env-var-value deps = pytest commands = py.test [] test_integration.py + +[testenv:registry] +docker = docker.io/library/nginx:1.13-alpine +dockerenv = + ENV_VAR=env-var-value +deps = pytest +commands = py.test [] test_registry.py diff --git a/tox_docker.py b/tox_docker.py index a120a61..8095735 100644 --- a/tox_docker.py +++ b/tox_docker.py @@ -7,6 +7,28 @@ from docker.errors import ImageNotFound import docker as docker_module +def escape_env_var(varname): + """ + Convert a string to a form suitable for use as an environment variable. + + The result will be all uppercase, and will have all invalid characters + replaced by an underscore. + + The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]* + + Example: + "my.private.registry/cat/image" will become + "MY_PRIVATE_REGISTRY_CAT_IMAGE" + """ + varname = list(varname.upper()) + if not varname[0].isalpha(): + varname[0] = '_' + for i, c in enumerate(varname): + if not c.isalnum() and c != '_': + varname[i] = '_' + return "".join(varname) + + def _newaction(venv, message): try: # tox 3.7 and later @@ -62,20 +84,33 @@ def tox_runtest_pre(venv): conf._docker_containers.append(container) container.reload() + gateway_ip = container.attrs["NetworkSettings"]["Gateway"] or "0.0.0.0" for containerport, hostports in container.attrs["NetworkSettings"]["Ports"].items(): - hostport = None + for spec in hostports: if spec["HostIp"] == "0.0.0.0": hostport = spec["HostPort"] break - - if not hostport: + else: continue - envvar = "{}_{}".format( - name.upper(), - containerport.replace("/", "_").upper(), - ) + envvar = escape_env_var("{}_HOST".format( + name, + )) + venv.envconfig.setenv[envvar] = gateway_ip + + envvar = escape_env_var("{}_{}_PORT".format( + name, + containerport, + )) + venv.envconfig.setenv[envvar] = hostport + + # TODO: remove in 2.0 + _, proto = containerport.split("/") + envvar = escape_env_var("{}_{}".format( + name, + containerport, + )) venv.envconfig.setenv[envvar] = hostport _, proto = containerport.split("/") @@ -88,7 +123,7 @@ def tox_runtest_pre(venv): while (time.time() - start) < 30: try: sock = socket.create_connection( - address=("0.0.0.0", int(hostport)), + address=(gateway_ip, int(hostport)), timeout=0.1, ) except socket.error:
tox-dev/tox-docker
c571732e0c606a1cde123bf6899a7c246ba2e44e
diff --git a/test_integration.py b/test_integration.py index 2c672fe..4a0be70 100644 --- a/test_integration.py +++ b/test_integration.py @@ -1,6 +1,10 @@ import os import unittest -import urllib2 + +try: + from urllib.request import urlopen +except ImportError: + from urllib2 import urlopen class ToxDockerIntegrationTest(unittest.TestCase): @@ -12,13 +16,30 @@ class ToxDockerIntegrationTest(unittest.TestCase): def test_it_sets_automatic_env_vars(self): # the nginx image we use exposes port 80 + self.assertIn("NGINX_HOST", os.environ) self.assertIn("NGINX_80_TCP", os.environ) - # the telegraf image we use exposes UDP port 8092 - self.assertIn("TELEGRAF_8092_UDP", os.environ) + self.assertIn("NGINX_80_TCP_PORT", os.environ) + self.assertEqual( + os.environ["NGINX_80_TCP_PORT"], + os.environ["NGINX_80_TCP"], + ) + + # the test image we use exposes TCP port 1234 and UDP port 5678 + self.assertIn("KSDN117_TCP_UDP_TEST_1234_TCP", os.environ) + self.assertIn("KSDN117_TCP_UDP_TEST_1234_TCP_PORT", os.environ) + self.assertEqual( + os.environ["KSDN117_TCP_UDP_TEST_1234_TCP_PORT"], + os.environ["KSDN117_TCP_UDP_TEST_1234_TCP"], + ) + self.assertIn("KSDN117_TCP_UDP_TEST_5678_UDP_PORT", os.environ) + self.assertEqual( + os.environ["KSDN117_TCP_UDP_TEST_5678_UDP_PORT"], + os.environ["KSDN117_TCP_UDP_TEST_5678_UDP"], + ) def test_it_exposes_the_port(self): # the nginx image we use exposes port 80 - url = "http://127.0.0.1:{port}/".format(port=os.environ["NGINX_80_TCP"]) - response = urllib2.urlopen(url) + url = "http://{host}:{port}/".format(host=os.environ["NGINX_HOST"], port=os.environ["NGINX_80_TCP"]) + response = urlopen(url) self.assertEqual(200, response.getcode()) - self.assertIn("Thank you for using nginx.", response.read()) + self.assertIn("Thank you for using nginx.", str(response.read())) diff --git a/test_registry.py b/test_registry.py new file mode 100644 index 0000000..4884f36 --- /dev/null +++ b/test_registry.py @@ -0,0 +1,18 @@ +import os +import unittest + +from tox_docker import escape_env_var + + +class ToxDockerRegistryTest(unittest.TestCase): + + def test_it_sets_automatic_env_vars(self): + # the nginx image we use exposes port 80 + self.assertIn("DOCKER_IO_LIBRARY_NGINX_HOST", os.environ) + self.assertIn("DOCKER_IO_LIBRARY_NGINX_80_TCP", os.environ) + + def test_escape_env_var(self): + self.assertEqual( + escape_env_var("my.private.registry/cat/image"), + "MY_PRIVATE_REGISTRY_CAT_IMAGE", + )
support for remote docker hosts Docker itself could run on a remote machine and docker would use DOCKER_HOST variable to connect to it. Still, based on the fact that no IP address is returned in enviornment variables I suppose that tox-docker would not be able to work in this case. This is a serious isse as now docker perfectly supports ssh protocol, and user can easily do `DOCKER_HOST=ssh://root@remote`. ``` File "/Users/ssbarnea/.local/lib/python2.7/site-packages/pluggy/callers.py", line 81, in get_result _reraise(*ex) # noqa File "/Users/ssbarnea/.local/lib/python2.7/site-packages/pluggy/callers.py", line 187, in _multicall res = hook_impl.function(*args) File "/Users/ssbarnea/os/tox-docker/tox_docker.py", line 94, in tox_runtest_pre "Never got answer on port {} from {}".format(containerport, name) Exception: Never got answer on port 8080/tcp from gerritcodereview/gerrit tox -e py27 3.33s user 2.75s system 5% cpu 1:44.68 total ```
0.0
c571732e0c606a1cde123bf6899a7c246ba2e44e
[ "test_registry.py::ToxDockerRegistryTest::test_escape_env_var" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-14 13:57:01+00:00
bsd-3-clause
6,091
treasure-data__td-client-python-21
diff --git a/tdclient/client.py b/tdclient/client.py index 691b225..85c2258 100644 --- a/tdclient/client.py +++ b/tdclient/client.py @@ -527,10 +527,7 @@ class Client(object): [:class:`tdclient.models.Schedule`] """ result = self.api.list_schedules() - def schedule(m): - name,cron,query,database,result_url,timezone,delay,next_time,priority,retry_limit,org_name = m - return models.Schedule(self, name, cron, query, database, result_url, timezone, delay, next_time, priority, retry_limit, org_name) - return [ schedule(m) for m in result ] + return [ models.Schedule(self, m.get("name"), m.get("cron"), m.get("query"), **m) for m in result ] def update_schedule(self, name, params=None): """ diff --git a/tdclient/schedule_api.py b/tdclient/schedule_api.py index 8d9ec3b..02e7106 100644 --- a/tdclient/schedule_api.py +++ b/tdclient/schedule_api.py @@ -50,17 +50,12 @@ class ScheduleAPI(object): self.raise_error("List schedules failed", res, body) js = self.checked_json(body, ["schedules"]) def schedule(m): - name = m.get("name") - cron = m.get("cron") - query = m.get("query") - database = m.get("database") - result_url = m.get("result") - timezone = m.get("timezone", "UTC") - delay = m.get("delay") - next_time = self._parsedate(self.get_or_else(m, "next_time", "1970-01-01T00:00:00Z"), "%Y-%m-%dT%H:%M:%SZ") - priority = m.get("priority") - retry_limit = m.get("retry_limit") - return (name, cron, query, database, result_url, timezone, delay, next_time, priority, retry_limit, None) # same as database + m = dict(m) + if "timezone" not in m: + m["timezone"] = "UTC" + m["created_at"] = self._parsedate(self.get_or_else(m, "created_at", "1970-01-01T00:00:00Z"), "%Y-%m-%dT%H:%M:%SZ") + m["next_time"] = self._parsedate(self.get_or_else(m, "next_time", "1970-01-01T00:00:00Z"), "%Y-%m-%dT%H:%M:%SZ") + return m return [ schedule(m) for m in js["schedules"] ] def update_schedule(self, name, params=None): diff --git a/tdclient/schedule_model.py b/tdclient/schedule_model.py index 104550d..888ae08 100644 --- a/tdclient/schedule_model.py +++ b/tdclient/schedule_model.py @@ -24,19 +24,27 @@ class Schedule(Model): """Schedule on Treasure Data Service """ - def __init__(self, client, name, cron, query, database=None, result_url=None, timezone=None, delay=None, next_time=None, priority=None, retry_limit=None, org_name=None): + def __init__(self, client, name, cron, query, **kwargs): super(Schedule, self).__init__(client) self._name = name self._cron = cron + self._timezone = kwargs.get("timezone") + self._delay = kwargs.get("delay") + self._created_at = kwargs.get("created_at") + self._type = kwargs.get("type") self._query = query - self._database = database - self._result_url = result_url - self._timezone = timezone - self._delay = delay - self._next_time = next_time - self._priority = priority - self._retry_limit = retry_limit - self._org_name = org_name + self._database = kwargs.get("database") + self._user_name = kwargs.get("user_name") + self._priority = kwargs.get("priority") + self._retry_limit = kwargs.get("retry_limit") + if "result_url" in kwargs: + # backward compatibility for td-client-python < 0.6.0 + # TODO: remove this code if not necessary with fixing test + self._result = kwargs.get("result_url") + else: + self._result = kwargs.get("result") + self._next_time = kwargs.get("next_time") + self._org_name = kwargs.get("org_name") @property def name(self): @@ -68,7 +76,7 @@ class Schedule(Model): def result_url(self): """The result output configuration in URL form of a scheduled job """ - return self._result_url + return self._result @property def timezone(self): @@ -88,7 +96,10 @@ class Schedule(Model): def priority(self): """The priority of a scheduled job """ - return self._priority + if self._priority in Job.JOB_PRIORITY: + return Job.JOB_PRIORITY[self._priority] + else: + return str(self._priority) @property def retry_limit(self): @@ -111,6 +122,27 @@ class Schedule(Model): """ return self._next_time + @property + def created_at(self): + """ + TODO: add docstring + """ + return self._created_at + + @property + def type(self): + """ + TODO: add docstring + """ + return self._type + + @property + def user_name(self): + """ + TODO: add docstring + """ + return self._user_name + def run(self, time, num=None): """Run a scheduled job """
treasure-data/td-client-python
59f47438514f128cadf945f54cf56d5f311c5338
diff --git a/tdclient/test/schedule_api_test.py b/tdclient/test/schedule_api_test.py index b7f18bb..faca3d1 100644 --- a/tdclient/test/schedule_api_test.py +++ b/tdclient/test/schedule_api_test.py @@ -70,13 +70,54 @@ def test_delete_schedule_success(): def test_list_schedules_success(): td = api.API("APIKEY") - # TODO: should be replaced by wire dump body = b""" { "schedules":[ - {"name":"foo","cron":"* * * * *","query":"SELECT COUNT(1) FROM nasdaq;","database":"sample_datasets","result":"","timezone":"UTC","delay":"","next_time":"","priority":"","retry_limit":""}, - {"name":"bar","cron":"* * * * *","query":"SELECT COUNT(1) FROM nasdaq;","database":"sample_datasets","result":"","timezone":"UTC","delay":"","next_time":"","priority":"","retry_limit":""}, - {"name":"baz","cron":"* * * * *","query":"SELECT COUNT(1) FROM nasdaq;","database":"sample_datasets","result":"","timezone":"UTC","delay":"","next_time":"","priority":"","retry_limit":""} + { + "name": "foo", + "cron": null, + "timezone": "UTC", + "delay": 0, + "created_at": "2016-08-02T17:58:40Z", + "type": "presto", + "query": "SELECT COUNT(1) FROM nasdaq;", + "database": "sample_datasets", + "user_name": "Yuu Yamashita", + "priority": 0, + "retry_limit": 0, + "result": "", + "next_time": null + }, + { + "name": "bar", + "cron": "0 0 * * *", + "timezone": "UTC", + "delay": 0, + "created_at": "2016-08-02T18:01:04Z", + "type": "presto", + "query": "SELECT COUNT(1) FROM nasdaq;", + "database": "sample_datasets", + "user_name": "Kazuki Ota", + "priority": 0, + "retry_limit": 0, + "result": "", + "next_time": "2016-09-24T00:00:00Z" + }, + { + "name": "baz", + "cron": "* * * * *", + "timezone": "UTC", + "delay": 0, + "created_at": "2016-03-02T23:01:59Z", + "type": "hive", + "query": "SELECT COUNT(1) FROM nasdaq;", + "database": "sample_datasets", + "user_name": "Yuu Yamashita", + "priority": 0, + "retry_limit": 0, + "result": "", + "next_time": "2016-07-06T00:00:00Z" + } ] } """ @@ -84,6 +125,22 @@ def test_list_schedules_success(): schedules = td.list_schedules() td.get.assert_called_with("/v3/schedule/list") assert len(schedules) == 3 + next_time = sorted([ schedule.get("next_time") for schedule in schedules if "next_time" in schedule ]) + assert len(next_time) == 3 + assert next_time[2].year == 2016 + assert next_time[2].month == 9 + assert next_time[2].day == 24 + assert next_time[2].hour == 0 + assert next_time[2].minute == 0 + assert next_time[2].second == 0 + created_at = sorted([ schedule.get("created_at") for schedule in schedules if "created_at" in schedule ]) + assert len(created_at) == 3 + assert created_at[2].year == 2016 + assert created_at[2].month == 8 + assert created_at[2].day == 2 + assert created_at[2].hour == 18 + assert created_at[2].minute == 1 + assert created_at[2].second == 4 def test_list_schedules_failure(): td = api.API("APIKEY") @@ -100,13 +157,59 @@ def test_update_schedule_success(): def test_history_success(): td = api.API("APIKEY") - # TODO: should be replaced by wire dump body = b""" { "history": [ - {"job_id":"12345"}, - {"job_id":"67890"} - ] + { + "query": "SELECT COUNT(1) FROM nasdaq;", + "type": "presto", + "priority": 0, + "retry_limit": 0, + "duration": 1, + "status": "success", + "cpu_time": null, + "result_size": 30, + "job_id": "12345", + "created_at": "2016-04-13 05:24:59 UTC", + "updated_at": "2016-04-13 05:25:02 UTC", + "start_at": "2016-04-13 05:25:00 UTC", + "end_at": "2016-04-13 05:25:01 UTC", + "num_records": 1, + "database": "sample_datasets", + "user_name": "Ryuta Kamizono", + "result": "", + "url": "https://console.treasuredata.com/jobs/12345", + "hive_result_schema": "[[\\"_col0\\", \\"bigint\\"]]", + "organization": null, + "scheduled_at": "" + }, + { + "query": "SELECT COUNT(1) FROM nasdaq;", + "type": "presto", + "priority": 0, + "retry_limit": 0, + "duration": 1, + "status": "success", + "cpu_time": null, + "result_size": 30, + "job_id": "67890", + "created_at": "2016-04-13 05:24:59 UTC", + "updated_at": "2016-04-13 05:25:02 UTC", + "start_at": "2016-04-13 05:25:00 UTC", + "end_at": "2016-04-13 05:25:01 UTC", + "num_records": 1, + "database": "sample_datasets", + "user_name": "Ryuta Kamizono", + "result": "", + "url": "https://console.treasuredata.com/jobs/67890", + "hive_result_schema": "[[\\"_col0\\", \\"bigint\\"]]", + "organization": null, + "scheduled_at": "" + } + ], + "count": 2, + "from": 0, + "to": 20 } """ td.get = mock.MagicMock(return_value=make_response(200, body))
Missing created_time and user_name in list_schedules api Schedule API returns the following for each scheduled. But, created_time and user_name are missing ``` $ curl -H "AUTHORIZATION: TD1 XXXXX" "http://api.treasuredata.com/v3/schedule/list" ... { "name":"xxx", "cron":null, "timezone":"UTC", "delay":0, "created_at":"2016-08-15T23:03:59Z", "type":"presto", "query":"xxxx", "database":"api_production", "user_name":"YYYY", "priority":0, "retry_limit":0, "result":"", "next_time":null } ``` https://github.com/treasure-data/td-client-python/blob/master/tdclient/schedule_api.py#L52-L63
0.0
59f47438514f128cadf945f54cf56d5f311c5338
[ "tdclient/test/schedule_api_test.py::test_list_schedules_success" ]
[ "tdclient/test/schedule_api_test.py::test_create_schedule_success", "tdclient/test/schedule_api_test.py::test_create_schedule_without_cron_success", "tdclient/test/schedule_api_test.py::test_delete_schedule_success", "tdclient/test/schedule_api_test.py::test_list_schedules_failure", "tdclient/test/schedule_api_test.py::test_update_schedule_success", "tdclient/test/schedule_api_test.py::test_history_success", "tdclient/test/schedule_api_test.py::test_run_schedule_success" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-09-23 08:10:45+00:00
apache-2.0
6,092
treasure-data__td-client-python-44
diff --git a/tdclient/cursor.py b/tdclient/cursor.py index ef4b159..83cc292 100644 --- a/tdclient/cursor.py +++ b/tdclient/cursor.py @@ -82,15 +82,22 @@ class Cursor(object): return [ (column[0], None, None, None, None, None, None) for column in result_schema ] def fetchone(self): + """ + Fetch the next row of a query result set, returning a single sequence, or `None` when no more data is available. + """ self._check_executed() if self._rownumber < self._rowcount: row = self._rows[self._rownumber] self._rownumber += 1 return row else: - raise errors.InternalError("index out of bound (%d out of %d)" % (self._rownumber, self._rowcount)) + return None def fetchmany(self, size=None): + """ + Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). + An empty sequence is returned when no more rows are available. + """ if size is None: return self.fetchall() else: @@ -103,13 +110,17 @@ class Cursor(object): raise errors.InternalError("index out of bound (%d out of %d)" % (self._rownumber, self._rowcount)) def fetchall(self): + """ + Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). + Note that the cursor's arraysize attribute can affect the performance of this operation. + """ self._check_executed() if self._rownumber < self._rowcount: rows = self._rows[self._rownumber:] self._rownumber = self._rowcount return rows else: - raise errors.InternalError("row index out of bound (%d out of %d)" % (self._rownumber, self._rowcount)) + return [] def nextset(self): raise errors.NotSupportedError
treasure-data/td-client-python
e2d0e830c2b9b8615523d73ee53fb86d98c59c3b
diff --git a/tdclient/test/cursor_test.py b/tdclient/test/cursor_test.py index 24780e7..0c0e368 100644 --- a/tdclient/test/cursor_test.py +++ b/tdclient/test/cursor_test.py @@ -133,8 +133,7 @@ def test_fetchone(): assert td.fetchone() == ["foo", 1] assert td.fetchone() == ["bar", 1] assert td.fetchone() == ["baz", 2] - with pytest.raises(errors.InternalError) as error: - td.fetchone() + assert td.fetchone() == None def test_fetchmany(): td = cursor.Cursor(mock.MagicMock()) @@ -144,8 +143,9 @@ def test_fetchmany(): td._rowcount = len(td._rows) assert td.fetchmany(2) == [["foo", 1], ["bar", 1]] assert td.fetchmany() == [["baz", 2]] + assert td.fetchmany() == [] with pytest.raises(errors.InternalError) as error: - td.fetchmany() + td.fetchmany(1) def test_fetchall(): td = cursor.Cursor(mock.MagicMock()) @@ -154,8 +154,7 @@ def test_fetchall(): td._rownumber = 0 td._rowcount = len(td._rows) assert td.fetchall() == [["foo", 1], ["bar", 1], ["baz", 2]] - with pytest.raises(errors.InternalError) as error: - td.fetchall() + assert td.fetchall() == [] def test_show_job(): td = cursor.Cursor(mock.MagicMock())
[Q] An error occurs when the record count of `read_sql` is 0 I executed the following Python script. ``` pandas.read_sql("SELECT * FROM td_table WHERE 1=0", td) => tdclient.errors.InternalError: row index out of bound (0 out of 0) ``` Is this in the specifications? In the case of `mysql-connector-python`, the result is as follows. ``` pandas.read_sql("SELECT * FROM mysql_table WHERE 1=0", mysql) => Empty DataFrame ```
0.0
e2d0e830c2b9b8615523d73ee53fb86d98c59c3b
[ "tdclient/test/cursor_test.py::test_fetchone", "tdclient/test/cursor_test.py::test_fetchmany", "tdclient/test/cursor_test.py::test_fetchall" ]
[ "tdclient/test/cursor_test.py::test_cursor", "tdclient/test/cursor_test.py::test_cursor_close", "tdclient/test/cursor_test.py::test_cursor_execute", "tdclient/test/cursor_test.py::test_cursor_execute_format_dict", "tdclient/test/cursor_test.py::test_cursor_execute_format_tuple", "tdclient/test/cursor_test.py::test_cursor_executemany", "tdclient/test/cursor_test.py::test_check_executed", "tdclient/test/cursor_test.py::test_do_execute_success", "tdclient/test/cursor_test.py::test_do_execute_error", "tdclient/test/cursor_test.py::test_do_execute_wait", "tdclient/test/cursor_test.py::test_result_description", "tdclient/test/cursor_test.py::test_show_job", "tdclient/test/cursor_test.py::test_job_status", "tdclient/test/cursor_test.py::test_job_result", "tdclient/test/cursor_test.py::test_cursor_callproc", "tdclient/test/cursor_test.py::test_cursor_nextset", "tdclient/test/cursor_test.py::test_cursor_setinputsizes", "tdclient/test/cursor_test.py::test_cursor_setoutputsize" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-06-29 01:06:42+00:00
apache-2.0
6,093
troycomi__reportseff-21
diff --git a/pyproject.toml b/pyproject.toml index 9d2f914..f2ed2ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "reportseff" -version = "2.4.2" +version = "2.4.3" description= "Tablular seff output" authors = ["Troy Comi <[email protected]>"] license = "MIT" diff --git a/src/reportseff/job.py b/src/reportseff/job.py index c089426..97c7075 100644 --- a/src/reportseff/job.py +++ b/src/reportseff/job.py @@ -114,7 +114,9 @@ class Job: for k, value in entry.items(): if k not in self.other_entries or not self.other_entries[k]: self.other_entries[k] = value - self.stepmem += parsemem(entry["MaxRSS"]) if "MaxRSS" in entry else 0 + # self.stepmem += parsemem(entry["MaxRSS"]) if "MaxRSS" in entry else 0 + mem = parsemem(entry["MaxRSS"]) if "MaxRSS" in entry else 0 + self.stepmem = max(self.stepmem, mem) def _update_main_job(self, entry: Dict) -> None: """Update properties for the main job.
troycomi/reportseff
f1502769622e9744becca91d034607e8cb183ca5
diff --git a/tests/test_reportseff.py b/tests/test_reportseff.py index 36c40f3..9674186 100644 --- a/tests/test_reportseff.py +++ b/tests/test_reportseff.py @@ -63,7 +63,7 @@ def test_directory_input(mocker, mock_inquirer): "01:27:42", "48.7%", "99.8%", - "47.7%", + "47.6%", ] @@ -220,7 +220,7 @@ def test_simple_job(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] def test_simple_user(mocker, mock_inquirer): @@ -250,8 +250,8 @@ def test_simple_user(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] - assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.6%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] + assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] def test_simple_partition(mocker, mock_inquirer): @@ -282,8 +282,8 @@ def test_simple_partition(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] - assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.6%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] + assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] def test_format_add(mocker, mock_inquirer): @@ -336,8 +336,8 @@ def test_since(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] - assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.6%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] + assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] def test_since_all_users(mocker, mock_inquirer): @@ -372,8 +372,8 @@ def test_since_all_users(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] - assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.6%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] + assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] mock_sub.assert_called_once_with( args=( @@ -423,8 +423,8 @@ def test_since_all_users_partition(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] - assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.6%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] + assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] mock_sub.assert_called_once_with( args=( @@ -474,7 +474,7 @@ def test_parsable(mocker, mock_inquirer): # remove header output = result.output.split("\n")[1:] # no color/bold codes and | delimited - assert output[0].split("|") == ["24418435", "COMPLETED", "01:27:42", "99.8", "47.7"] + assert output[0].split("|") == ["24418435", "COMPLETED", "01:27:42", "99.8", "47.6"] # other is suppressed by state filter assert output[1].split("|") == ["25569410", "RUNNING", "21:14:48", "---", "---"] @@ -509,7 +509,7 @@ def test_simple_state(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] # other is suppressed by state filter assert output[1].split() == [] @@ -544,7 +544,7 @@ def test_simple_not_state(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n")[1:] - assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] + assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] # other is suppressed by state filter assert output[1].split() == [] @@ -582,7 +582,7 @@ def test_invalid_not_state(mocker, mock_inquirer): assert output[0] == "Unknown state CUNNING" assert output[1] == "No valid states provided to exclude" # output 2 is header - assert output[3].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.7%"] + assert output[3].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] assert output[4].split() == ["25569410", "RUNNING", "21:14:48", "---", "---"] assert output[5].split() == [] @@ -860,3 +860,67 @@ def test_no_systems(mocker, mock_inquirer): # remove header output = result.output.split("\n") assert output[0] == "No supported scheduling systems found!" + + +def test_issue_16(mocker, mock_inquirer): + """Incorrect memory usage for multi-node jobs.""" + mocker.patch("reportseff.console.which", return_value=True) + runner = CliRunner() + sub_result = mocker.MagicMock() + sub_result.returncode = 0 + sub_result.stdout = ( + "|16|07:36:03|65638294|65638294||2|32G|COMPLETED|6-23:59:00|4-23:56:21\n" + "|1|07:36:03|65638294.batch|65638294.batch|1147220K|1||COMPLETED||07:30:20\n" + "|16|07:36:03|65638294.extern|65638294.extern|0|2||COMPLETED||00:00.001\n" + "|15|00:00:11|65638294.0|65638294.0|0|1||COMPLETED||00:11.830\n" + "|15|00:02:15|65638294.1|65638294.1|4455540K|1||COMPLETED||31:09.458\n" + "|15|00:00:10|65638294.2|65638294.2|0|1||COMPLETED||00:00:04\n" + "|15|00:00:08|65638294.3|65638294.3|0|1||COMPLETED||00:09.602\n" + "|15|00:00:07|65638294.4|65638294.4|0|1||COMPLETED||00:56.827\n" + "|15|00:00:06|65638294.5|65638294.5|0|1||COMPLETED||00:03.512\n" + "|15|00:00:08|65638294.6|65638294.6|0|1||COMPLETED||00:08.520\n" + "|15|00:00:13|65638294.7|65638294.7|0|1||COMPLETED||01:02.013\n" + "|15|00:00:02|65638294.8|65638294.8|0|1||COMPLETED||00:03.639\n" + "|15|00:00:06|65638294.9|65638294.9|0|1||COMPLETED||00:08.683\n" + "|15|00:00:08|65638294.10|65638294.10|0|1||COMPLETED||00:57.438\n" + "|15|00:00:06|65638294.11|65638294.11|0|1||COMPLETED||00:03.642\n" + "|15|00:00:09|65638294.12|65638294.12|0|1||COMPLETED||00:10.271\n" + "|15|00:01:24|65638294.13|65638294.13|4149700K|1||COMPLETED||17:18.067\n" + "|15|00:00:01|65638294.14|65638294.14|0|1||COMPLETED||00:03.302\n" + "|15|00:00:10|65638294.15|65638294.15|0|1||COMPLETED||00:14.615\n" + "|15|00:06:45|65638294.16|65638294.16|4748052K|1||COMPLETED||01:36:40\n" + "|15|00:00:10|65638294.17|65638294.17|0|1||COMPLETED||00:03.864\n" + "|15|00:00:09|65638294.18|65638294.18|0|1||COMPLETED||00:48.987\n" + "|15|01:32:53|65638294.19|65638294.19|7734356K|1||COMPLETED||23:09:33\n" + "|15|00:00:01|65638294.20|65638294.20|0|1||COMPLETED||00:03.520\n" + "|15|00:00:07|65638294.21|65638294.21|0|1||COMPLETED||00:50.015\n" + "|15|00:55:17|65638294.22|65638294.22|8074500K|1||COMPLETED||13:45:29\n" + "|15|00:00:13|65638294.23|65638294.23|0|1||COMPLETED||00:04.413\n" + "|15|00:00:12|65638294.24|65638294.24|0|1||COMPLETED||00:49.100\n" + "|15|00:57:41|65638294.25|65638294.25|7883152K|1||COMPLETED||14:20:36\n" + "|15|00:00:01|65638294.26|65638294.26|0|1||COMPLETED||00:03.953\n" + "|15|00:00:05|65638294.27|65638294.27|0|1||COMPLETED||00:47.223\n" + "|15|01:00:17|65638294.28|65638294.28|7715752K|1||COMPLETED||14:59:40\n" + "|15|00:00:06|65638294.29|65638294.29|0|1||COMPLETED||00:04.341\n" + "|15|00:00:07|65638294.30|65638294.30|0|1||COMPLETED||00:50.416\n" + "|15|01:22:31|65638294.31|65638294.31|7663264K|1||COMPLETED||20:33:59\n" + "|15|00:00:05|65638294.32|65638294.32|0|1||COMPLETED||00:04.199\n" + "|15|00:00:08|65638294.33|65638294.33|0|1||COMPLETED||00:50.009\n" + "|15|01:32:23|65638294.34|65638294.34|7764884K|1||COMPLETED||23:01:52\n" + "|15|00:00:06|65638294.35|65638294.35|0|1||COMPLETED||00:04.527\n" + ) + mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) + result = runner.invoke(console.main, "--no-color 65638294".split()) + + assert result.exit_code == 0 + # remove header + output = result.output.split("\n")[1:-1] + assert output[0].split() == [ + "65638294", + "COMPLETED", + "07:36:03", + "4.5%", + "98.6%", + "24.1%", + ] + assert len(output) == 1
Memory Efficiency differs between reportseff and seff for multi-node jobs I've just started using reportseff on our university cluster specifically for the reasons mentioned on your blog post (be good to your scheduler) and overall its great. However, I've noticed that the memory efficiency reports by reportseff and seff differ specifically for multi node jobs. For example: reportseff: 65638294 COMPLETED 07:36:03 4.5% 98.6% 182.8% seff: Job ID: 65638294 State: COMPLETED (exit code 0) Nodes: 2 Cores per node: 8 CPU Utilized: 4-23:56:22 CPU Efficiency: 98.62% of 5-01:36:48 core-walltime Job Wall-clock time: 07:36:03 Memory Utilized: 7.70 GB Memory Efficiency: 24.06% of 32.00 GB I relatively new to both reportseff and seff so I am not sure if this an underlying issue with reporting for the SLURM side, but any insight into the origin the difference would be useful for interpreting the results. Thanks!
0.0
f1502769622e9744becca91d034607e8cb183ca5
[ "tests/test_reportseff.py::test_directory_input", "tests/test_reportseff.py::test_simple_job", "tests/test_reportseff.py::test_simple_user", "tests/test_reportseff.py::test_simple_partition", "tests/test_reportseff.py::test_since", "tests/test_reportseff.py::test_since_all_users", "tests/test_reportseff.py::test_since_all_users_partition", "tests/test_reportseff.py::test_parsable", "tests/test_reportseff.py::test_simple_state", "tests/test_reportseff.py::test_simple_not_state", "tests/test_reportseff.py::test_invalid_not_state", "tests/test_reportseff.py::test_issue_16" ]
[ "tests/test_reportseff.py::test_directory_input_exception", "tests/test_reportseff.py::test_debug_option", "tests/test_reportseff.py::test_process_failure", "tests/test_reportseff.py::test_short_output", "tests/test_reportseff.py::test_long_output", "tests/test_reportseff.py::test_format_add", "tests/test_reportseff.py::test_no_state", "tests/test_reportseff.py::test_array_job_raw_id", "tests/test_reportseff.py::test_array_job_single", "tests/test_reportseff.py::test_array_job_base", "tests/test_reportseff.py::test_sacct_error", "tests/test_reportseff.py::test_empty_sacct", "tests/test_reportseff.py::test_failed_no_mem", "tests/test_reportseff.py::test_canceled_by_other", "tests/test_reportseff.py::test_zero_runtime", "tests/test_reportseff.py::test_no_systems" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-01-23 19:24:12+00:00
mit
6,094
troycomi__reportseff-29
diff --git a/README.md b/README.md index 467c572..cc6c199 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ split_ubam_24419972 RUNNING 01:26:26 --- --- Without arguments, reportseff will try to find slurm output files in the current directory. Combine with `watch` to monitor job progress: -`watch -cn 300 reportseff --modified-sort` +`watch -cn 300 reportseff --color --modified-sort` ```txt JobID State Elapsed CPUEff MemEff @@ -214,6 +214,10 @@ directory to check for slurm outputs. - `--since`: Limit results to those occurring after the specified time. Accepts sacct formats and a comma separated list of key/value pairs. To get jobs in the last hour and a half, can pass `h=1,m=30`. +-`--until`: Limit results to those occurring before the specified time. Accepts + sacct formats and a comma separated list of key/value pairs. + Useful in combination with the 'since' option to query a specific range. +- `--partition`: Limit results to a specific partition. - `--node/-n`: Display information for multi-node jobs; requires additional sacct fields from jobstats. - `--node-and-gpu/-g`: Display information for multi-node jobs and GPU information; @@ -248,6 +252,23 @@ you get an error that pip isn't found, look for a python/anaconda/conda module. in an isolated environment. This resolves issues of dependency versions and allows applications to be run from any environment. +### The output has no color with many jobs! + +Click should determine if the output supports color display and react automatically +in a way you expect. Check that your terminal is setup to display colors and +that your pager (probably less) will display color by default. Some commands, +e.g. `watch` aren't handled properly even when invoked to support color. Here +are some useful settings for your `.bashrc`: +``` +# have less display colors by default. Will fix `reportseff` not showing colors +export LESS="-R" +# for watch aliases, include the `--color` option +watch -cn 300 reportseff --color --modified-sort +# ^ ^^^^^^^ +``` +You can always for display of color (or suppress it) with the `--color/--no-color` +options + ### I get an error about broken pipes when chaining to other commands Python will report that the consumer of process output has closed the stream @@ -264,20 +285,6 @@ will likely be absent. Node-level reporting is only shown for jobs which use multiple nodes or GPUs. If you need a list of where jobs were run, you can add `--format +NodeList`. -### My output is garbled with ESC[0m all over, where's the color? - -Those are ANSI color codes. Click will usually strip these if it detects -the consuming process can't display color codes, but `reportseff` defaults -to always display them. If you don't care for color, use the `--no-color` -option. For less, you can set -``` -export LESS="-R" -``` -in your `.bashrc`, or just type `-R` in an active less process. Some versions -of `watch` require the `-c` option to display color, others can't display -colors properly. If you search for `ansi color <tool>` you should get some -solutions. - ## Acknowledgments The code for calling sacct and parsing the returning information was taken diff --git a/pyproject.toml b/pyproject.toml index 58ab7e9..1891ee6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "reportseff" -version = "2.7.3" +version = "2.7.4" description= "Tablular seff output" authors = ["Troy Comi <[email protected]>"] license = "MIT" diff --git a/src/reportseff/console.py b/src/reportseff/console.py index 9087594..4803929 100644 --- a/src/reportseff/console.py +++ b/src/reportseff/console.py @@ -21,7 +21,7 @@ from .parameters import ReportseffParameters ) @click.option( "--color/--no-color", - default=True, + default=None, help="Force color output. No color will use click defaults", ) @click.option( diff --git a/src/reportseff/parameters.py b/src/reportseff/parameters.py index 2c12a9e..1f28ad4 100644 --- a/src/reportseff/parameters.py +++ b/src/reportseff/parameters.py @@ -28,7 +28,7 @@ class ReportseffParameters: def __init__( self, jobs: tuple, - color: bool = True, + color: bool, debug: bool = False, format_str: str = "", modified_sort: bool = False,
troycomi/reportseff
18236d7200309e852fd4aa9102b2565fb32d0ebf
diff --git a/tests/test_reportseff.py b/tests/test_reportseff.py index 1605f8a..8a155ae 100644 --- a/tests/test_reportseff.py +++ b/tests/test_reportseff.py @@ -173,10 +173,10 @@ def test_short_output(mocker, mock_inquirer): mocker.patch.object(OutputRenderer, "format_jobs", return_value="output") mock_click = mocker.patch("reportseff.console.click.echo") - result = runner.invoke(console.main, "--no-color 23000233".split()) + result = runner.invoke(console.main, " 23000233".split()) assert result.exit_code == 0 - mock_click.assert_called_once_with("output", color=False) + mock_click.assert_called_once_with("output", color=None) def test_long_output(mocker, mock_inquirer): @@ -192,10 +192,10 @@ def test_long_output(mocker, mock_inquirer): mocker.patch("reportseff.console.len", return_value=21) mocker.patch.object(OutputRenderer, "format_jobs", return_value="output") mock_click = mocker.patch("reportseff.console.click.echo_via_pager") - result = runner.invoke(console.main, "--no-color 23000233".split()) + result = runner.invoke(console.main, " 23000233".split()) assert result.exit_code == 0 - mock_click.assert_called_once_with("output", color=False) + mock_click.assert_called_once_with("output", color=None) def test_simple_job(mocker, mock_inquirer):
Enhancement default behavior of color Hi, I am wondering if it is possible to change the behavior of the option color/no-color. By default, with more than 20 lines, it will create a pager with the color activated because the default of color is True: ``` reportseff --since d=7 ESC[1m JobIDESC[0m ESC[1m State ESC[0m ESC[1m ElapsedESC[0m ESC[1m TimeEff ESC[0m ESC[1m CPUEff ESC[0m ESC[1m MemEff ESC[0m 15113138 ESC[32m COMPLETED ESC[0m 00:37:55 ESC[31m 0.0% ESC[0m ESC[32m 94.6% ESC[0m ESC[31m 0.1% ESC[0m 15116136 ESC[32m COMPLETED ESC[0m 00:37:55 ESC[31m 0.0% ESC[0m ESC[32m 94.7% ESC[0m ESC[31m 0.1% ESC[0m 15119524 ESC[32m COMPLETED ESC[0m 01:37:30 ESC[31m 0.0% ESC[0m 67.3% ESC[31m 0.2% ESC[0m [...] ``` I think it will be easier to use reportseff for an user, if it let the default value of color of the function echo_via_pager which is "autodetection". So the library will detect if it can display the color or not. In my example, I modify a bit the function main by the following code : ``` if entries > 20: if args.color : click.echo_via_pager(output,args.color) elif not args.color: click.echo_via_pager(output,args.color) else: click.echo_via_pager(output) else: if args.color : click.echo(output, color=args.color) else: click.echo(output) ``` Where args.color is equal to None (instead of True) if the option is not set. So with this "solution" : --> `reportseff --since d=7` will output in color on my shell without need of pipe. --> `reportseff --since d=7 >output_reportseff` will write in the file without color. --> `reportseff --color --since d=7` will output ANSI color codes on my shell, need to pipe with less -R to be readable. --> `reportseff --color --since d=7 >output_reportseff` will write in the file the ANSI color codes need to use the option -r to be readable. --> `reportseff --no-color --since d=7` will output without color on my shell. --> `reportseff --no-color --since d=7 >output_reportseff` will write in the file without the color. The current behavior : --> `reportseff --since d=7` will output ANSI color codes on my shell, need to pipe with less -R to be readable. --> `reportseff --since d=7 >output_reportseff` will write in the file the ANSI color codes, need to use the option -r to be readable. --> `reportseff --color --since d=7` will output ANSI color codes on my shell, need to pipe with less -R to be readable. --> `reportseff --color --since d=7 >output_reportseff` will write in the file the ANSI color codes, need to use the option -r to be readable. --> `reportseff --no-color --since d=7` will output without color on my shell. --> `reportseff --no-color --since d=7 >output_reportseff` will write in the file without the color. So it will only change de default behavior, if you don't set the option color/no-color. I have seen what you have write here https://github.com/troycomi/reportseff#my-output-is-garbled-with-esc0m-all-over-wheres-the-color, but it seems to me more user friendly with my approach. What do you think about that? I hope it is understandable, thanks for your tool again !
0.0
18236d7200309e852fd4aa9102b2565fb32d0ebf
[ "tests/test_reportseff.py::test_short_output", "tests/test_reportseff.py::test_long_output" ]
[ "tests/test_reportseff.py::test_directory_input", "tests/test_reportseff.py::test_directory_input_exception", "tests/test_reportseff.py::test_debug_option", "tests/test_reportseff.py::test_process_failure", "tests/test_reportseff.py::test_simple_job", "tests/test_reportseff.py::test_simple_user", "tests/test_reportseff.py::test_simple_partition", "tests/test_reportseff.py::test_format_add", "tests/test_reportseff.py::test_since", "tests/test_reportseff.py::test_since_all_users", "tests/test_reportseff.py::test_since_all_users_partition", "tests/test_reportseff.py::test_parsable", "tests/test_reportseff.py::test_simple_state", "tests/test_reportseff.py::test_simple_not_state", "tests/test_reportseff.py::test_invalid_not_state", "tests/test_reportseff.py::test_no_state", "tests/test_reportseff.py::test_array_job_raw_id", "tests/test_reportseff.py::test_array_job_single", "tests/test_reportseff.py::test_array_job_base", "tests/test_reportseff.py::test_sacct_error", "tests/test_reportseff.py::test_empty_sacct", "tests/test_reportseff.py::test_failed_no_mem", "tests/test_reportseff.py::test_canceled_by_other", "tests/test_reportseff.py::test_zero_runtime", "tests/test_reportseff.py::test_no_systems", "tests/test_reportseff.py::test_issue_16", "tests/test_reportseff.py::test_energy_reporting", "tests/test_reportseff.py::test_extra_args" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-31 18:20:29+00:00
mit
6,095
troycomi__reportseff-42
diff --git a/pyproject.toml b/pyproject.toml index d536f8b..2b81226 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "reportseff" -version = "2.7.5" +version = "2.7.6" description= "Tablular seff output" authors = ["Troy Comi <[email protected]>"] license = "MIT" diff --git a/src/reportseff/job.py b/src/reportseff/job.py index 5cba205..43750f8 100644 --- a/src/reportseff/job.py +++ b/src/reportseff/job.py @@ -60,7 +60,6 @@ class Job: self.time: Optional[str] = "---" self.time_eff: Union[str, float] = "---" self.cpu: Optional[Union[str, float]] = "---" - self.mem: Union[str, float] = "---" self.state: Optional[str] = None self.mem_eff: Optional[float] = None self.gpu: Optional[float] = None @@ -116,7 +115,8 @@ class Job: if k not in self.other_entries or not self.other_entries[k]: self.other_entries[k] = value mem = parsemem(entry["MaxRSS"]) if "MaxRSS" in entry else 0 - self.stepmem = max(self.stepmem, mem) + tasks = int(entry.get("NTasks", 1)) + self.stepmem = max(self.stepmem, mem * tasks) if "TRESUsageOutAve" in entry: self.energy = max( diff --git a/src/reportseff/output_renderer.py b/src/reportseff/output_renderer.py index 161accd..a5c2da0 100644 --- a/src/reportseff/output_renderer.py +++ b/src/reportseff/output_renderer.py @@ -45,7 +45,7 @@ class OutputRenderer: # values derived from other values, list includes all dependent values self.derived: Dict[str, List] = { "CPUEff": ["TotalCPU", "AllocCPUS", "Elapsed"], - "MemEff": ["REQMEM", "NNodes", "AllocCPUS", "MaxRSS"], + "MemEff": ["REQMEM", "NNodes", "AllocCPUS", "MaxRSS", "NTasks"], "TimeEff": ["Elapsed", "Timelimit"], "GPU": [], "GPUMem": [],
troycomi/reportseff
48acc9601d20ffedaa758fbd21c834982a8298bc
diff --git a/conftest.py b/conftest.py index 44f8a6a..0756750 100644 --- a/conftest.py +++ b/conftest.py @@ -30,6 +30,7 @@ def to_sacct_dict(sacct_line: str) -> dict: "State", "Timelimit", "TotalCPU", + "NTasks", ) return dict(zip(columns, sacct_line.split("|"))) @@ -316,3 +317,90 @@ def multinode_job(): "|36|12-14:16:39|6196869.batch|6196869.batch|33824748K|1|191846Mn|COMPLETED||451-06:00:24" ), ] + + [email protected] +def issue_41(): + """job run on multiple nodes, with multiple tasks.""" + return [ + to_sacct_dict( + "|8|00:00:53|131042|131042||1|16000M|COMPLETED|00:01:00|06:57.815|8" + ), + to_sacct_dict( + "|8|00:00:53|131042.batch|131042.batch|20264K|1||COMPLETED||00:00.034|8" + ), + to_sacct_dict( + "|8|00:00:53|131042.extern|131042.extern|1052K|1||COMPLETED||00:00.001|8" + ), + to_sacct_dict( + "|8|00:00:53|131042.0|131042.0|1947276K|1||COMPLETED||06:57.779|8" + ), + ] + + [email protected] +def console_jobs(): + """collection of sacct outputs for test_reportseff.""" + + # indexed on job id + return { + "25569410_notime": ( + "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^1^|^4000Mc^|^" + "COMPLETED^|^19:28:36\n" + "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^" + "1^|^1^|^4000Mc^|^COMPLETED^|^00:00:00\n" + "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" + "^|^1^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + ), + "24418435_notime": ( + "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1^|^1Gn^|^" + "COMPLETED^|^01:27:29\n" + "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^" + "1^|^1^|^1Gn^|^COMPLETED^|^01:27:29\n" + "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^" + "1^|^1^|^1Gn^|^COMPLETED^|^00:00:00\n" + ), + "24418435": ( + "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1^|^1Gn^|^" + "COMPLETED^|^03:00:00^|^01:27:29\n" + "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^" + "1^|^1^|^1Gn^|^COMPLETED^|^^|^01:27:29\n" + "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^" + "1^|^1^|^1Gn^|^COMPLETED^|^^|^00:00:00\n" + ), + "23000233": ( + "^|^16^|^00:00:00^|^23000233^|^23000233^|^^|^1^|^1^|^4000Mc^|^" + "CANCELLED by 129319^|^6-00:00:00^|^00:00:00\n" + ), + "24221219": ( + "^|^1^|^00:09:34^|^24220929_421^|^24221219^|^^|^1^|^1^|^16000Mn^|^" + "COMPLETED^|^09:28.052\n" + "^|^1^|^00:09:34^|^24220929_421.batch^|^24221219.batch" + "^|^5664932K^|^1^|^1^|^16000Mn^|^COMPLETED^|^09:28.051\n" + "^|^1^|^00:09:34^|^24220929_421.extern^|^24221219.extern" + "^|^1404K^|^1^|^1^|^16000Mn^|^COMPLETED^|^00:00:00\n" + ), + "24221220": ( + "^|^1^|^00:09:33^|^24220929_431^|^24221220^|^^|^1^|^1^|^16000Mn^|^" + "PENDING^|^09:27.460\n" + "^|^1^|^00:09:33^|^24220929_431.batch^|^24221220.batch" + "^|^5518572K^|^1^|^1^|^16000Mn^|^PENDING^|^09:27.459\n" + "^|^1^|^00:09:33^|^24220929_431.extern^|^24221220.extern" + "^|^1400K^|^1^|^1^|^16000Mn^|^PENDING^|^00:00:00\n" + ), + "23000381": ( + "^|^8^|^00:00:12^|^23000381^|^23000381^|^^|^1^|^1^|^4000Mc^|^FAILED^|^00:00:00\n" + "^|^8^|^00:00:12^|^23000381.batch^|^23000381.batch^|^^|^1^|^1^|^4000Mc^|^" + "FAILED^|^00:00:00\n" + "^|^8^|^00:00:12^|^23000381.extern^|^23000381.extern^|^1592K^|^1^|^1^|^4000Mc^|^" + "COMPLETED^|^00:00:00\n" + ), + "23000210": ( + "^|^8^|^00:00:00^|^23000210^|^23000210^|^^|^1^|^1^|^20000Mn^|^" + "FAILED^|^00:00.007\n" + "^|^8^|^00:00:00^|^23000210.batch^|^23000210.batch^|^1988K^|^1^|^1^|^20000Mn^|^" + "FAILED^|^00:00.006\n" + "^|^8^|^00:00:00^|^23000210.extern^|^23000210.extern^|^1556K^|^1^|^1^|^20000Mn^|^" + "COMPLETED^|^00:00:00\n" + ), + } diff --git a/tests/test_job.py b/tests/test_job.py index bb09c5e..7f6eb46 100644 --- a/tests/test_job.py +++ b/tests/test_job.py @@ -40,7 +40,6 @@ def test_job_init(job): assert job.totalmem is None assert job.time == "---" assert job.cpu == "---" - assert job.mem == "---" assert job.state is None @@ -250,7 +249,7 @@ def test_update_part_job(): "Elapsed": "00:10:00", "MaxRSS": "495644K", "NNodes": "1", - "NTasks": "", + "NTasks": "1", } ) assert job.state is None @@ -765,3 +764,16 @@ def test_multinode_job(multinode_job): job.update(line) assert job.cpu == 5.0 + + +def test_multinode_job_issue_41(issue_41): + """Testing issue 41 where multiple tasks are used. + + Previously reported incorrect memory efficiency. + """ + job = job_module.Job("131042", "131042", None) + for line in issue_41: + job.update(line) + + assert job.cpu == 98.3 + assert job.get_entry("MemEff") == 95.1 diff --git a/tests/test_output_renderer.py b/tests/test_output_renderer.py index 763fe65..09896a6 100644 --- a/tests/test_output_renderer.py +++ b/tests/test_output_renderer.py @@ -175,7 +175,7 @@ def test_renderer_init(renderer): assert sorted(renderer.query_columns) == sorted( ( "JobID JobIDRaw State Elapsed TotalCPU " - "AllocCPUS REQMEM NNodes MaxRSS AdminComment" + "AllocCPUS REQMEM NNodes NTasks MaxRSS AdminComment" ).split() ) @@ -277,7 +277,7 @@ def test_renderer_correct_columns(renderer): ( "JobID TotalCPU Elapsed REQMEM" " JobIDRaw State AdminComment" - " NNodes AllocCPUS MaxRSS Timelimit" + " NNodes NTasks AllocCPUS MaxRSS Timelimit" ).split() ) diff --git a/tests/test_reportseff.py b/tests/test_reportseff.py index a3a44d8..50a1f15 100644 --- a/tests/test_reportseff.py +++ b/tests/test_reportseff.py @@ -30,20 +30,13 @@ def mock_inquirer(mocker): ) -def test_directory_input(mocker, mock_inquirer): +def test_directory_input(mocker, mock_inquirer, console_jobs): """Able to get jobs from directory calls.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^03:00:00^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["24418435"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) def set_jobs(self, directory): @@ -68,20 +61,13 @@ def test_directory_input(mocker, mock_inquirer): ] -def test_directory_input_exception(mocker, mock_inquirer): +def test_directory_input_exception(mocker, mock_inquirer, console_jobs): """Catch exceptions in setting jobs from directory.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "24418435^|^24418435^|^COMPLETED^|^1^|^" - "01:27:29^|^01:27:42^|^03:00:00^|^1Gn^|^^|^1^|^\n" - "24418435.batch^|^24418435.batch^|^COMPLETED^|^1^|^" - "01:27:29^|^01:27:42^|^^|^1Gn^|^499092K^|^1^|^1\n" - "24418435.extern^|^24418435.extern^|^COMPLETED^|^1^|^" - "00:00:00^|^01:27:42^|^^|^1Gn^|^1376K^|^1^|^1\n" - ) + sub_result.stdout = console_jobs["24418435"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) def set_jobs(self, directory): @@ -94,16 +80,13 @@ def test_directory_input_exception(mocker, mock_inquirer): assert "Testing EXCEPTION" in result.output -def test_debug_option(mocker, mock_inquirer): +def test_debug_option(mocker, mock_inquirer, console_jobs): """Setting debug prints subprocess result.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^16^|^00:00:00^|^23000233^|^23000233^|^^|^1^|^4000Mc^|^" - "CANCELLED by 129319^|^6-00:00:00^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000233"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -113,10 +96,7 @@ def test_debug_option(mocker, mock_inquirer): assert result.exit_code == 0 # remove header output = result.output.split("\n") - assert output[0] == ( - "^|^16^|^00:00:00^|^23000233^|^23000233^|^^|^1^|^4000Mc^|^" - "CANCELLED by 129319^|^6-00:00:00^|^00:00:00" - ) + assert output[0] == console_jobs["23000233"].strip("\n") assert output[3].split() == [ "23000233", "CANCELLED", @@ -127,16 +107,13 @@ def test_debug_option(mocker, mock_inquirer): ] -def test_process_failure(mocker, mock_inquirer): +def test_process_failure(mocker, mock_inquirer, console_jobs): """Catch exceptions in process_entry by printing the offending entry.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^16^|^00:00:00^|^23000233^|^23000233^|^^|^1^|^4000Mc^|^" - "CANCELLED by 129319^|^6-00:00:00^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000233"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) mocker.patch.object( JobCollection, "process_entry", side_effect=Exception("TESTING") @@ -153,21 +130,18 @@ def test_process_failure(mocker, mock_inquirer): "{'AdminComment': '', 'AllocCPUS': '16', " "'Elapsed': '00:00:00', 'JobID': '23000233', " "'JobIDRaw': '23000233', 'MaxRSS': '', 'NNodes': '1', " - "'REQMEM': '4000Mc', 'State': 'CANCELLED by 129319', " + "'NTasks': '1', 'REQMEM': '4000Mc', 'State': 'CANCELLED by 129319', " "'TotalCPU': '6-00:00:00'}" ) -def test_short_output(mocker, mock_inquirer): +def test_short_output(mocker, mock_inquirer, console_jobs): """Outputs with 20 or fewer entries are directly printed.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^23000233^|^23000233^|^CANCELLED by 129319^|^16^|^" - "00:00:00^|^00:00:00^|^6-00:00:00^|^4000Mc^|^^|^1^|^\n" - ) + sub_result.stdout = console_jobs["23000233"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) mocker.patch("reportseff.console.len", return_value=20) mocker.patch.object(OutputRenderer, "format_jobs", return_value="output") @@ -179,16 +153,13 @@ def test_short_output(mocker, mock_inquirer): mock_click.assert_called_once_with("output", color=None) -def test_long_output(mocker, mock_inquirer): +def test_long_output(mocker, mock_inquirer, console_jobs): """Outputs with more than 20 entries are echoed via pager.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^16^|^00:00:00^|^23000233^|^23000233" - "^|^^|^1^|^4000Mc^|^CANCELLED by 129319^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000233"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) mocker.patch("reportseff.console.len", return_value=21) mocker.patch.object(OutputRenderer, "format_jobs", return_value="output") @@ -199,20 +170,13 @@ def test_long_output(mocker, mock_inquirer): mock_click.assert_called_once_with("output", color=None) -def test_simple_job(mocker, mock_inquirer): +def test_simple_job(mocker, mock_inquirer, console_jobs): """Can get efficiency from a single job.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -225,24 +189,14 @@ def test_simple_job(mocker, mock_inquirer): assert output[0].split() == ["24418435", "COMPLETED", "01:27:42", "99.8%", "47.6%"] -def test_simple_user(mocker, mock_inquirer): +def test_simple_user(mocker, mock_inquirer, console_jobs): """Can limit outputs by user.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + console_jobs["24418435_notime"] + console_jobs["25569410_notime"] ) mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( @@ -257,24 +211,14 @@ def test_simple_user(mocker, mock_inquirer): assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] -def test_simple_partition(mocker, mock_inquirer): +def test_simple_partition(mocker, mock_inquirer, console_jobs): """Can limit outputs by partition.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0" - "^|^62328K^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + console_jobs["24418435_notime"] + console_jobs["25569410_notime"] ) mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( @@ -310,24 +254,14 @@ def test_format_add(mocker, mock_inquirer): ) -def test_since(mocker, mock_inquirer): +def test_since(mocker, mock_inquirer, console_jobs): """Can limit outputs by time since argument.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + console_jobs["24418435_notime"] + console_jobs["25569410_notime"] ) mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( @@ -345,24 +279,14 @@ def test_since(mocker, mock_inquirer): assert output[1].split() == ["25569410", "COMPLETED", "21:14:48", "91.7%", "1.5%"] -def test_since_all_users(mocker, mock_inquirer): +def test_since_all_users(mocker, mock_inquirer, console_jobs): """Can limit outputs by time since argument.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + console_jobs["24418435_notime"] + console_jobs["25569410_notime"] ) mock_sub = mocker.patch( "reportseff.db_inquirer.subprocess.run", return_value=sub_result @@ -385,7 +309,7 @@ def test_since_all_users(mocker, mock_inquirer): args=( "sacct -P -n --delimiter=^|^ " "--format=AdminComment,AllocCPUS,Elapsed,JobID,JobIDRaw," - "MaxRSS,NNodes,REQMEM,State,TotalCPU " + "MaxRSS,NNodes,NTasks,REQMEM,State,TotalCPU " "--allusers " # all users is added since no jobs/files were specified "--starttime=200406" ).split(), @@ -397,24 +321,14 @@ def test_since_all_users(mocker, mock_inquirer): ) -def test_since_all_users_partition(mocker, mock_inquirer): +def test_since_all_users_partition(mocker, mock_inquirer, console_jobs): """Can limit outputs by time since and partition argument.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^COMPLETED^|^19:28:36\n" + console_jobs["24418435_notime"] + console_jobs["25569410_notime"] ) mock_sub = mocker.patch( "reportseff.db_inquirer.subprocess.run", return_value=sub_result @@ -437,7 +351,7 @@ def test_since_all_users_partition(mocker, mock_inquirer): args=( "sacct -P -n --delimiter=^|^ " "--format=AdminComment,AllocCPUS,Elapsed,JobID,JobIDRaw," - "MaxRSS,NNodes,REQMEM,State,TotalCPU " + "MaxRSS,NNodes,NTasks,REQMEM,State,TotalCPU " "--allusers " # all users is added since no jobs/files were specified "--starttime=200406 " "--partition=partition " @@ -450,25 +364,15 @@ def test_since_all_users_partition(mocker, mock_inquirer): ) -def test_parsable(mocker, mock_inquirer): +def test_parsable(mocker, mock_inquirer, console_jobs): """Can display output as parsable format.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "RUNNING^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] + console_jobs[ + "25569410_notime" + ].replace("COMPLETED", "RUNNING") mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -483,29 +387,18 @@ def test_parsable(mocker, mock_inquirer): output = result.output.split("\n")[1:] # no color/bold codes and ^|^ delimited assert output[0].split("|") == ["24418435", "COMPLETED", "01:27:42", "99.8", "47.6"] - # other is suppressed by state filter assert output[1].split("|") == ["25569410", "RUNNING", "21:14:48", "---", "---"] -def test_simple_state(mocker, mock_inquirer): +def test_simple_state(mocker, mock_inquirer, console_jobs): """Can limit outputs by filtering state.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "RUNNING^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] + console_jobs[ + "25569410_notime" + ].replace("COMPLETED", "RUNNING") mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -523,25 +416,15 @@ def test_simple_state(mocker, mock_inquirer): assert output[1].split() == [] -def test_simple_not_state(mocker, mock_inquirer): +def test_simple_not_state(mocker, mock_inquirer, console_jobs): """Can limit outputs by removing state.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "RUNNING^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] + console_jobs[ + "25569410_notime" + ].replace("COMPLETED", "RUNNING") mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -559,25 +442,15 @@ def test_simple_not_state(mocker, mock_inquirer): assert output[1].split() == [] -def test_invalid_not_state(mocker, mock_inquirer): +def test_invalid_not_state(mocker, mock_inquirer, console_jobs): """When not state isn't found, return all jobs.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern^|^1548K^|^1^|^4000Mc^|^" - "RUNNING^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] + console_jobs[ + "25569410_notime" + ].replace("COMPLETED", "RUNNING") mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -598,25 +471,15 @@ def test_invalid_not_state(mocker, mock_inquirer): assert output[5].split() == [] -def test_no_state(mocker, mock_inquirer): +def test_no_state(mocker, mock_inquirer, console_jobs): """Unknown states produce empty output.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^01:27:42^|^24418435^|^24418435^|^^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.batch^|^24418435.batch^|^499092K^|^1^|^1Gn^|^" - "COMPLETED^|^01:27:29\n" - "^|^1^|^01:27:42^|^24418435.extern^|^24418435.extern^|^1376K^|^1^|^1Gn^|^" - "COMPLETED^|^00:00:00\n" - "^|^1^|^21:14:48^|^25569410^|^25569410^|^^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - "^|^1^|^21:14:49^|^25569410.extern^|^25569410.extern" - "^|^1548K^|^1^|^4000Mc^|^RUNNING^|^00:00:00\n" - "^|^1^|^21:14:43^|^25569410.0^|^25569410.0^|^62328K" - "^|^1^|^4000Mc^|^RUNNING^|^19:28:36\n" - ) + sub_result.stdout = console_jobs["24418435_notime"] + console_jobs[ + "25569410_notime" + ].replace("COMPLETED", "RUNNING") mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, "--no-color --state ZZ 25569410 24418435".split() @@ -638,20 +501,13 @@ def test_no_state(mocker, mock_inquirer): assert output[3] == "" -def test_array_job_raw_id(mocker, mock_inquirer): +def test_array_job_raw_id(mocker, mock_inquirer, console_jobs): """Can find job array by base id.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^00:09:34^|^24220929_421^|^24221219^|^^|^1^|^16000Mn^|^" - "COMPLETED^|^09:28.052\n" - "^|^1^|^00:09:34^|^24220929_421.batch^|^24221219.batch" - "^|^5664932K^|^1^|^16000Mn^|^COMPLETED^|^09:28.051\n" - "^|^1^|^00:09:34^|^24220929_421.extern^|^24221219.extern" - "^|^1404K^|^1^|^16000Mn^|^COMPLETED^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["24221219"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -671,26 +527,13 @@ def test_array_job_raw_id(mocker, mock_inquirer): assert len(output) == 1 -def test_array_job_single(mocker, mock_inquirer): +def test_array_job_single(mocker, mock_inquirer, console_jobs): """Can get single array job element.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^00:09:34^|^24220929_421^|^24221219^|^^|^1^|^16000Mn^|^" - "COMPLETED^|^09:28.052\n" - "^|^1^|^00:09:34^|^24220929_421.batch^|^24221219.batch" - "^|^5664932K^|^1^|^16000Mn^|^COMPLETED^|^09:28.051\n" - "^|^1^|^00:09:34^|^24220929_421.extern^|^24221219.extern" - "^|^1404K^|^1^|^16000Mn^|^COMPLETED^|^00:00:00\n" - "^|^1^|^00:09:33^|^24220929_431^|^24221220^|^^|^1^|^16000Mn^|^" - "PENDING^|^09:27.460\n" - "^|^1^|^00:09:33^|^24220929_431.batch^|^24221220.batch" - "^|^5518572K^|^1^|^16000Mn^|^PENDING^|^09:27.459\n" - "^|^1^|^00:09:33^|^24220929_431.extern^|^24221220.extern" - "^|^1400K^|^1^|^16000Mn^|^PENDING^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["24221219"] + console_jobs["24221220"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -712,26 +555,13 @@ def test_array_job_single(mocker, mock_inquirer): assert len(output) == 1 -def test_array_job_base(mocker, mock_inquirer): +def test_array_job_base(mocker, mock_inquirer, console_jobs): """Base array job id gets all elements.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^1^|^00:09:34^|^24220929_421^|^24221219^|^^|^1^|^16000Mn^|^" - "COMPLETED^|^09:28.052\n" - "^|^1^|^00:09:34^|^24220929_421.batch^|^24221219.batch^|^" - "5664932K^|^1^|^16000Mn^|^COMPLETED^|^09:28.051\n" - "^|^1^|^00:09:34^|^24220929_421.extern^|^24221219.extern^|^" - "1404K^|^1^|^16000Mn^|^COMPLETED^|^00:00:00\n" - "^|^1^|^00:09:33^|^24220929_431^|^24221220^|^^|^1^|^16000Mn^|^" - "PENDING^|^09:27.460\n" - "^|^1^|^00:09:33^|^24220929_431.batch^|^24221220.batch^|^" - "5518572K^|^1^|^16000Mn^|^PENDING^|^09:27.459\n" - "^|^1^|^00:09:33^|^24220929_431.extern^|^24221220.extern^|^" - "1400K^|^1^|^16000Mn^|^PENDING^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["24221219"] + console_jobs["24221220"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke( console.main, @@ -789,19 +619,13 @@ def test_empty_sacct(mocker, mock_inquirer): assert len(output) == 1 -def test_failed_no_mem(mocker, mock_inquirer): +def test_failed_no_mem(mocker, mock_inquirer, console_jobs): """Empty memory entries produce valid output.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^8^|^00:00:12^|^23000381^|^23000381^|^^|^1^|^4000Mc^|^FAILED^|^00:00:00\n" - "^|^8^|^00:00:12^|^23000381.batch^|^23000381.batch^|^^|^1^|^4000Mc^|^" - "FAILED^|^00:00:00\n" - "^|^8^|^00:00:12^|^23000381.extern^|^23000381.extern^|^1592K^|^1^|^4000Mc^|^" - "COMPLETED^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000381"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke(console.main, "--no-color 23000381".split()) @@ -812,16 +636,13 @@ def test_failed_no_mem(mocker, mock_inquirer): assert len(output) == 1 -def test_canceled_by_other(mocker, mock_inquirer): +def test_canceled_by_other(mocker, mock_inquirer, console_jobs): """Canceled states are correctly handled.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^16^|^00:00:00^|^23000233^|^23000233^|^^|^1^|^" - "4000Mc^|^CANCELLED by 129319^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000233"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke(console.main, "--no-color 23000233 --state CA".split()) @@ -832,27 +653,20 @@ def test_canceled_by_other(mocker, mock_inquirer): "23000233", "CANCELLED", "00:00:00", - "---", + "0.0%", "---", "0.0%", ] assert len(output) == 1 -def test_zero_runtime(mocker, mock_inquirer): +def test_zero_runtime(mocker, mock_inquirer, console_jobs): """Entries with zero runtime produce reasonable timeeff.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 - sub_result.stdout = ( - "^|^8^|^00:00:00^|^23000210^|^23000210^|^^|^1^|^20000Mn^|^" - "FAILED^|^00:00.007\n" - "^|^8^|^00:00:00^|^23000210.batch^|^23000210.batch^|^1988K^|^1^|^20000Mn^|^" - "FAILED^|^00:00.006\n" - "^|^8^|^00:00:00^|^23000210.extern^|^23000210.extern^|^1556K^|^1^|^20000Mn^|^" - "COMPLETED^|^00:00:00\n" - ) + sub_result.stdout = console_jobs["23000210"] mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke(console.main, "--no-color 23000210".split()) @@ -875,56 +689,64 @@ def test_no_systems(mocker, mock_inquirer): assert output[0] == "No supported scheduling systems found!" -def test_issue_16(mocker, mock_inquirer): +def test_issue_16(mocker, mock_inquirer, console_jobs): """Incorrect memory usage for multi-node jobs.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = """ -^|^16^|^07:36:03^|^65638294^|^65638294^|^^|^2^|^32G\ +^|^16^|^07:36:03^|^65638294^|^65638294^|^^|^1^|^2^|^32G\ ^|^COMPLETED^|^6-23:59:00^|^4-23:56:21 ^|^1^|^07:36:03^|^65638294.batch^|^65638294.batch\ -^|^1147220K^|^1^|^^|^COMPLETED^|^^|^07:30:20 +^|^1147220K^|^1^|^1^|^^|^COMPLETED^|^^|^07:30:20 ^|^16^|^07:36:03^|^65638294.extern^|^65638294.extern\ -^|^0^|^2^|^^|^COMPLETED^|^^|^00:00.001 -^|^15^|^00:00:11^|^65638294.0^|^65638294.0^|^0^|^1^|^^|^COMPLETED^|^^|^00:11.830 -^|^15^|^00:02:15^|^65638294.1^|^65638294.1^|^4455540K^|^1^|^^|^COMPLETED^|^^|^31:09.458 -^|^15^|^00:00:10^|^65638294.2^|^65638294.2^|^0^|^1^|^^|^COMPLETED^|^^|^00:00:04 -^|^15^|^00:00:08^|^65638294.3^|^65638294.3^|^0^|^1^|^^|^COMPLETED^|^^|^00:09.602 -^|^15^|^00:00:07^|^65638294.4^|^65638294.4^|^0^|^1^|^^|^COMPLETED^|^^|^00:56.827 -^|^15^|^00:00:06^|^65638294.5^|^65638294.5^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.512 -^|^15^|^00:00:08^|^65638294.6^|^65638294.6^|^0^|^1^|^^|^COMPLETED^|^^|^00:08.520 -^|^15^|^00:00:13^|^65638294.7^|^65638294.7^|^0^|^1^|^^|^COMPLETED^|^^|^01:02.013 -^|^15^|^00:00:02^|^65638294.8^|^65638294.8^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.639 -^|^15^|^00:00:06^|^65638294.9^|^65638294.9^|^0^|^1^|^^|^COMPLETED^|^^|^00:08.683 -^|^15^|^00:00:08^|^65638294.10^|^65638294.10^|^0^|^1^|^^|^COMPLETED^|^^|^00:57.438 -^|^15^|^00:00:06^|^65638294.11^|^65638294.11^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.642 -^|^15^|^00:00:09^|^65638294.12^|^65638294.12^|^0^|^1^|^^|^COMPLETED^|^^|^00:10.271 +^|^0^|^1^|^2^|^^|^COMPLETED^|^^|^00:00.001 +^|^15^|^00:00:11^|^65638294.0^|^65638294.0^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:11.830 +^|^15^|^00:02:15^|^65638294.1^|^65638294.1^|^4455540K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^31:09.458 +^|^15^|^00:00:10^|^65638294.2^|^65638294.2^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:00:04 +^|^15^|^00:00:08^|^65638294.3^|^65638294.3^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:09.602 +^|^15^|^00:00:07^|^65638294.4^|^65638294.4^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:56.827 +^|^15^|^00:00:06^|^65638294.5^|^65638294.5^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.512 +^|^15^|^00:00:08^|^65638294.6^|^65638294.6^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:08.520 +^|^15^|^00:00:13^|^65638294.7^|^65638294.7^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^01:02.013 +^|^15^|^00:00:02^|^65638294.8^|^65638294.8^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.639 +^|^15^|^00:00:06^|^65638294.9^|^65638294.9^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:08.683 +^|^15^|^00:00:08^|^65638294.10^|^65638294.10^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:57.438 +^|^15^|^00:00:06^|^65638294.11^|^65638294.11^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.642 +^|^15^|^00:00:09^|^65638294.12^|^65638294.12^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:10.271 ^|^15^|^00:01:24^|^65638294.13^|^65638294.13^|^4149700K\ -^|^1^|^^|^COMPLETED^|^^|^17:18.067 -^|^15^|^00:00:01^|^65638294.14^|^65638294.14^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.302 -^|^15^|^00:00:10^|^65638294.15^|^65638294.15^|^0^|^1^|^^|^COMPLETED^|^^|^00:14.615 -^|^15^|^00:06:45^|^65638294.16^|^65638294.16^|^4748052K^|^1^|^^|^COMPLETED^|^^|^01:36:40 -^|^15^|^00:00:10^|^65638294.17^|^65638294.17^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.864 -^|^15^|^00:00:09^|^65638294.18^|^65638294.18^|^0^|^1^|^^|^COMPLETED^|^^|^00:48.987 -^|^15^|^01:32:53^|^65638294.19^|^65638294.19^|^7734356K^|^1^|^^|^COMPLETED^|^^|^23:09:33 -^|^15^|^00:00:01^|^65638294.20^|^65638294.20^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.520 -^|^15^|^00:00:07^|^65638294.21^|^65638294.21^|^0^|^1^|^^|^COMPLETED^|^^|^00:50.015 -^|^15^|^00:55:17^|^65638294.22^|^65638294.22^|^8074500K^|^1^|^^|^COMPLETED^|^^|^13:45:29 -^|^15^|^00:00:13^|^65638294.23^|^65638294.23^|^0^|^1^|^^|^COMPLETED^|^^|^00:04.413 -^|^15^|^00:00:12^|^65638294.24^|^65638294.24^|^0^|^1^|^^|^COMPLETED^|^^|^00:49.100 -^|^15^|^00:57:41^|^65638294.25^|^65638294.25^|^7883152K^|^1^|^^|^COMPLETED^|^^|^14:20:36 -^|^15^|^00:00:01^|^65638294.26^|^65638294.26^|^0^|^1^|^^|^COMPLETED^|^^|^00:03.953 -^|^15^|^00:00:05^|^65638294.27^|^65638294.27^|^0^|^1^|^^|^COMPLETED^|^^|^00:47.223 -^|^15^|^01:00:17^|^65638294.28^|^65638294.28^|^7715752K^|^1^|^^|^COMPLETED^|^^|^14:59:40 -^|^15^|^00:00:06^|^65638294.29^|^65638294.29^|^0^|^1^|^^|^COMPLETED^|^^|^00:04.341 -^|^15^|^00:00:07^|^65638294.30^|^65638294.30^|^0^|^1^|^^|^COMPLETED^|^^|^00:50.416 -^|^15^|^01:22:31^|^65638294.31^|^65638294.31^|^7663264K^|^1^|^^|^COMPLETED^|^^|^20:33:59 -^|^15^|^00:00:05^|^65638294.32^|^65638294.32^|^0^|^1^|^^|^COMPLETED^|^^|^00:04.199 -^|^15^|^00:00:08^|^65638294.33^|^65638294.33^|^0^|^1^|^^|^COMPLETED^|^^|^00:50.009 -^|^15^|^01:32:23^|^65638294.34^|^65638294.34^|^7764884K^|^1^|^^|^COMPLETED^|^^|^23:01:52 -^|^15^|^00:00:06^|^65638294.35^|^65638294.35^|^0^|^1^|^^|^COMPLETED^|^^|^00:04.527 +^|^1^|^1^|^^|^COMPLETED^|^^|^17:18.067 +^|^15^|^00:00:01^|^65638294.14^|^65638294.14^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.302 +^|^15^|^00:00:10^|^65638294.15^|^65638294.15^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:14.615 +^|^15^|^00:06:45^|^65638294.16^|^65638294.16^|^4748052K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^01:36:40 +^|^15^|^00:00:10^|^65638294.17^|^65638294.17^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.864 +^|^15^|^00:00:09^|^65638294.18^|^65638294.18^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:48.987 +^|^15^|^01:32:53^|^65638294.19^|^65638294.19^|^7734356K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^23:09:33 +^|^15^|^00:00:01^|^65638294.20^|^65638294.20^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.520 +^|^15^|^00:00:07^|^65638294.21^|^65638294.21^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:50.015 +^|^15^|^00:55:17^|^65638294.22^|^65638294.22^|^8074500K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^13:45:29 +^|^15^|^00:00:13^|^65638294.23^|^65638294.23^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:04.413 +^|^15^|^00:00:12^|^65638294.24^|^65638294.24^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:49.100 +^|^15^|^00:57:41^|^65638294.25^|^65638294.25^|^7883152K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^14:20:36 +^|^15^|^00:00:01^|^65638294.26^|^65638294.26^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:03.953 +^|^15^|^00:00:05^|^65638294.27^|^65638294.27^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:47.223 +^|^15^|^01:00:17^|^65638294.28^|^65638294.28^|^7715752K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^14:59:40 +^|^15^|^00:00:06^|^65638294.29^|^65638294.29^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:04.341 +^|^15^|^00:00:07^|^65638294.30^|^65638294.30^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:50.416 +^|^15^|^01:22:31^|^65638294.31^|^65638294.31^|^7663264K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^20:33:59 +^|^15^|^00:00:05^|^65638294.32^|^65638294.32^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:04.199 +^|^15^|^00:00:08^|^65638294.33^|^65638294.33^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:50.009 +^|^15^|^01:32:23^|^65638294.34^|^65638294.34^|^7764884K\ +^|^1^|^1^|^^|^COMPLETED^|^^|^23:01:52 +^|^15^|^00:00:06^|^65638294.35^|^65638294.35^|^0^|^1^|^1^|^^|^COMPLETED^|^^|^00:04.527 """ mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) result = runner.invoke(console.main, "--no-color 65638294".split()) @@ -943,36 +765,36 @@ def test_issue_16(mocker, mock_inquirer): assert len(output) == 1 -def test_energy_reporting(mocker, mock_inquirer): +def test_energy_reporting(mocker, mock_inquirer, console_jobs): """Include energy reporting with the `energy` format code.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner() sub_result = mocker.MagicMock() sub_result.returncode = 0 sub_result.stdout = ( - "^|^32^|^00:01:09^|^37403870_1^|^37403937^|^^|^1^|^32000M^|^" + "^|^32^|^00:01:09^|^37403870_1^|^37403937^|^^|^1^|^1^|^32000M^|^" "COMPLETED^|^^|^00:02:00^|^00:47.734\n" - "^|^32^|^00:01:09^|^37403870_1.batch^|^37403937.batch^|^6300K^|^1^|^^|^" + "^|^32^|^00:01:09^|^37403870_1.batch^|^37403937.batch^|^6300K^|^1^|^1^|^^|^" "COMPLETED^|^energy=33,fs/disk=0^|^^|^00:47.733\n" - "^|^32^|^00:01:09^|^37403870_1.extern^|^37403937.extern^|^4312K^|^1^|^^|^" + "^|^32^|^00:01:09^|^37403870_1.extern^|^37403937.extern^|^4312K^|^1^|^1^|^^|^" "COMPLETED^|^energy=33,fs/disk=0^|^^|^00:00.001\n" - "^|^32^|^00:01:21^|^37403870_2^|^37403938^|^^|^1^|^32000M^|^" + "^|^32^|^00:01:21^|^37403870_2^|^37403938^|^^|^1^|^1^|^32000M^|^" "COMPLETED^|^^|^00:02:00^|^00:41.211\n" - "^|^32^|^00:01:21^|^37403870_2.batch^|^37403938.batch^|^6316K^|^1^|^^|^" + "^|^32^|^00:01:21^|^37403870_2.batch^|^37403938.batch^|^6316K^|^1^|^1^|^^|^" "COMPLETED^|^energy=32,fs/disk=0^|^^|^00:41.210\n" - "^|^32^|^00:01:21^|^37403870_2.extern^|^37403938.extern^|^4312K^|^1^|^^|^" + "^|^32^|^00:01:21^|^37403870_2.extern^|^37403938.extern^|^4312K^|^1^|^1^|^^|^" "COMPLETED^|^energy=32,fs/disk=0^|^^|^00:00:00\n" - "^|^32^|^00:01:34^|^37403870_3^|^37403939^|^^|^1^|^32000M^|^" + "^|^32^|^00:01:34^|^37403870_3^|^37403939^|^^|^1^|^1^|^32000M^|^" "COMPLETED^|^^|^00:02:00^|^00:51.669\n" - "^|^32^|^00:01:34^|^37403870_3.batch^|^37403939.batch^|^6184K^|^1^|^^|^" + "^|^32^|^00:01:34^|^37403870_3.batch^|^37403939.batch^|^6184K^|^1^|^1^|^^|^" "COMPLETED^|^energy=30,fs/disk=0^|^^|^00:51.667\n" - "^|^32^|^00:01:35^|^37403870_3.extern^|^37403939.extern^|^4312K^|^1^|^^|^" + "^|^32^|^00:01:35^|^37403870_3.extern^|^37403939.extern^|^4312K^|^1^|^1^|^^|^" "COMPLETED^|^fs/disk=0,energy=30^|^^|^00:00.001\n" - "^|^32^|^00:01:11^|^37403870_4^|^37403870^|^^|^1^|^32000M^|^" + "^|^32^|^00:01:11^|^37403870_4^|^37403870^|^^|^1^|^1^|^32000M^|^" "COMPLETED^|^^|^00:02:00^|^01:38.184\n" - "^|^32^|^00:01:11^|^37403870_4.batch^|^37403870.batch^|^6300K^|^1^|^^|^" + "^|^32^|^00:01:11^|^37403870_4.batch^|^37403870.batch^|^6300K^|^1^|^1^|^^|^" "COMPLETED^|^fs/disk=0^|^^|^01:38.183\n" - "^|^32^|^00:01:11^|^37403870_4.extern^|^37403870.extern^|^4312K^|^1^|^^|^" + "^|^32^|^00:01:11^|^37403870_4.extern^|^37403870.extern^|^4312K^|^1^|^1^|^^|^" "COMPLETED^|^energy=27,fs/disk=0^|^^|^00:00.001\n" ) mocker.patch("reportseff.db_inquirer.subprocess.run", return_value=sub_result) @@ -1028,7 +850,7 @@ def test_energy_reporting(mocker, mock_inquirer): assert len(output) == 5 -def test_extra_args(mocker, mock_inquirer): +def test_extra_args(mocker, mock_inquirer, console_jobs): """Can add extra arguments for sacct.""" mocker.patch("reportseff.console.which", return_value=True) runner = CliRunner()
Wrong memory efficiency when using "srun" Hello, probably related to #37, but a bit different, so I thought I'd open a new issue. When I run: `srun -n 8 stress -m 1 -t 52 --vm-keep --vm-bytes 1800M ` I use 8 CPUs and almost 16GB, but `reportseff` gets the CPU efficiency OK, but the memory efficiency way off (it basically reports I only used 1800M). ``` $ seff 131042 ######################## JOB EFFICIENCY REPORT ######################## # Job ID: 131042 # State: COMPLETED (exit code 0) # Cores: 8 # CPU Utilized: 00:06:58 # CPU Efficiency: 98.58% of 00:07:04 core-walltime # Wall-clock time: 00:00:53 # Memory Utilized: 14.86 GB (estimated maximum) ####################################################################### $ reportseff --debug 131042 ^|^8^|^00:00:53^|^131042^|^131042^|^^|^1^|^16000M^|^COMPLETED^|^00:01:00^|^06:57.815 ^|^8^|^00:00:53^|^131042.batch^|^131042.batch^|^20264K^|^1^|^^|^COMPLETED^|^^|^00:00.034 ^|^8^|^00:00:53^|^131042.extern^|^131042.extern^|^1052K^|^1^|^^|^COMPLETED^|^^|^00:00.001 ^|^8^|^00:00:53^|^131042.0^|^131042.0^|^1947276K^|^1^|^^|^COMPLETED^|^^|^06:57.779 JobID State Elapsed TimeEff CPUEff MemEff 131042 COMPLETED 00:00:53 88.3% 98.3% 11.9% ```
0.0
48acc9601d20ffedaa758fbd21c834982a8298bc
[ "tests/test_job.py::test_multinode_job_issue_41", "tests/test_output_renderer.py::test_renderer_init", "tests/test_output_renderer.py::test_renderer_correct_columns", "tests/test_reportseff.py::test_directory_input", "tests/test_reportseff.py::test_debug_option", "tests/test_reportseff.py::test_process_failure", "tests/test_reportseff.py::test_short_output", "tests/test_reportseff.py::test_long_output", "tests/test_reportseff.py::test_simple_job", "tests/test_reportseff.py::test_simple_user", "tests/test_reportseff.py::test_simple_partition", "tests/test_reportseff.py::test_since", "tests/test_reportseff.py::test_since_all_users", "tests/test_reportseff.py::test_since_all_users_partition", "tests/test_reportseff.py::test_parsable", "tests/test_reportseff.py::test_simple_state", "tests/test_reportseff.py::test_simple_not_state", "tests/test_reportseff.py::test_invalid_not_state", "tests/test_reportseff.py::test_array_job_raw_id", "tests/test_reportseff.py::test_array_job_single", "tests/test_reportseff.py::test_array_job_base", "tests/test_reportseff.py::test_failed_no_mem", "tests/test_reportseff.py::test_canceled_by_other", "tests/test_reportseff.py::test_zero_runtime", "tests/test_reportseff.py::test_issue_16", "tests/test_reportseff.py::test_energy_reporting" ]
[ "tests/test_job.py::test_eq", "tests/test_job.py::test_repr", "tests/test_job.py::test_job_init", "tests/test_job.py::test_update_main_job", "tests/test_job.py::test_update_main_job_unlimited", "tests/test_job.py::test_update_main_job_partition_limit", "tests/test_job.py::test_update_part_job", "tests/test_job.py::test_parse_bug", "tests/test_job.py::test_name", "tests/test_job.py::test_get_entry", "tests/test_job.py::test_parse_slurm_timedelta", "tests/test_job.py::test_parsemem_nodes", "tests/test_job.py::test_parsemem_cpus", "tests/test_job.py::test_parsememstep", "tests/test_job.py::test_unknown_admin_comment", "tests/test_job.py::test_single_core", "tests/test_job.py::test_multi_node", "tests/test_job.py::test_single_gpu", "tests/test_job.py::test_multi_gpu", "tests/test_job.py::test_multi_node_multi_gpu", "tests/test_job.py::test_short_job", "tests/test_job.py::test_bad_gpu", "tests/test_job.py::test_bad_gpu_utilization", "tests/test_job.py::test_issue_26", "tests/test_job.py::test_multinode_job", "tests/test_output_renderer.py::test_renderer_build_formatters", "tests/test_output_renderer.py::test_renderer_validate_formatters", "tests/test_output_renderer.py::test_renderer_validate_formatters_with_node", "tests/test_output_renderer.py::test_renderer_format_jobs", "tests/test_output_renderer.py::test_renderer_format_jobs_multi_node", "tests/test_output_renderer.py::test_renderer_format_jobs_multi_node_with_nodes", "tests/test_output_renderer.py::test_renderer_format_jobs_multi_node_with_nodes_and_gpu", "tests/test_output_renderer.py::test_format_jobs_empty", "tests/test_output_renderer.py::test_format_jobs_single_str", "tests/test_output_renderer.py::test_formatter_init", "tests/test_output_renderer.py::test_formatter_eq", "tests/test_output_renderer.py::test_formatter_validate_title", "tests/test_output_renderer.py::test_formatter_compute_width", "tests/test_output_renderer.py::test_formatter_format_entry", "tests/test_reportseff.py::test_directory_input_exception", "tests/test_reportseff.py::test_format_add", "tests/test_reportseff.py::test_no_state", "tests/test_reportseff.py::test_sacct_error", "tests/test_reportseff.py::test_empty_sacct", "tests/test_reportseff.py::test_no_systems", "tests/test_reportseff.py::test_extra_args" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-14 14:32:03+00:00
mit
6,096
tryolabs__norfair-198
diff --git a/norfair/tracker.py b/norfair/tracker.py index 1a26b07..0a80b97 100644 --- a/norfair/tracker.py +++ b/norfair/tracker.py @@ -438,18 +438,14 @@ class TrackedObject: reid_hit_counter_max: Optional[int], abs_to_rel: Callable[[np.array], np.array], ): - try: - initial_detection_points = validate_points( - initial_detection.absolute_points - ) - except AttributeError: + if not isinstance(initial_detection, Detection): print( f"\n[red]ERROR[/red]: The detection list fed into `tracker.update()` should be composed of {Detection} objects not {type(initial_detection)}.\n" ) exit() - self.dim_points = initial_detection_points.shape[1] - self.num_points = initial_detection_points.shape[0] + self.dim_points = initial_detection.absolute_points.shape[1] + self.num_points = initial_detection.absolute_points.shape[0] self.hit_counter_max: int = hit_counter_max self.pointwise_hit_counter_max: int = pointwise_hit_counter_max self.initialization_delay = initialization_delay @@ -487,7 +483,7 @@ class TrackedObject: self.past_detections: Sequence["Detection"] = [] # Create Kalman Filter - self.filter = filter_factory.create_filter(initial_detection_points) + self.filter = filter_factory.create_filter(initial_detection.absolute_points) self.dim_z = self.dim_points * self.num_points self.label = initial_detection.label self.abs_to_rel = abs_to_rel @@ -550,7 +546,6 @@ class TrackedObject: return self.point_hit_counter > 0 def hit(self, detection: "Detection", period: int = 1): - points = validate_points(detection.absolute_points) self._conditionally_add_to_past_detections(detection) self.last_detection = detection @@ -580,7 +575,9 @@ class TrackedObject: self.point_hit_counter[self.point_hit_counter < 0] = 0 H_vel = np.zeros(H_pos.shape) # But we don't directly measure velocity H = np.hstack([H_pos, H_vel]) - self.filter.update(np.expand_dims(points.flatten(), 0).T, None, H) + self.filter.update( + np.expand_dims(detection.absolute_points.flatten(), 0).T, None, H + ) # Force points being detected for the first time to have velocity = 0 # This is needed because some detectors (like OpenPose) set points with @@ -600,7 +597,7 @@ class TrackedObject: ) self.filter.x[: self.dim_z][first_detection_mask] = np.expand_dims( - points.flatten(), 0 + detection.absolute_points.flatten(), 0 ).T[first_detection_mask] self.filter.x[self.dim_z :][np.logical_not(detected_at_least_once_mask)] = 0 @@ -690,9 +687,9 @@ class Detection: label: Hashable = None, embedding=None, ): - self.points = points + self.points = validate_points(points) self.scores = scores self.data = data self.label = label - self.absolute_points = points.copy() + self.absolute_points = self.points.copy() self.embedding = embedding
tryolabs/norfair
062c4330bd75ec3632ff88a97a516a665a718ad2
diff --git a/tests/conftest.py b/tests/conftest.py index e4162cd..45c5526 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from norfair.utils import validate_points + @pytest.fixture def mock_det(): @@ -30,3 +32,23 @@ def mock_obj(mock_det): self.last_detection = mock_det(points, scores=scores) return FakeTrackedObject + + [email protected] +def mock_coordinate_transformation(): + + # simple mock to return abs or relative positions + class TransformMock: + def __init__(self, relative_points, absolute_points) -> None: + self.absolute_points = validate_points(absolute_points) + self.relative_points = validate_points(relative_points) + + def abs_to_rel(self, points): + np.testing.assert_equal(points, self.absolute_points) + return self.relative_points + + def rel_to_abs(self, points): + np.testing.assert_equal(points, self.relative_points) + return self.absolute_points + + return TransformMock diff --git a/tests/test_tracker.py b/tests/test_tracker.py index ffdeb45..bb6da11 100644 --- a/tests/test_tracker.py +++ b/tests/test_tracker.py @@ -9,6 +9,7 @@ from norfair import ( OptimizedKalmanFilterFactory, Tracker, ) +from norfair.utils import validate_points def test_params(): @@ -154,6 +155,68 @@ def test_distance_t(filter_factory): assert 4 < tracked_objects[0].estimate[0][1] <= 4.5 [email protected]( + "filter_factory", [FilterPyKalmanFilterFactory(), OptimizedKalmanFilterFactory()] +) +def test_1d_points(filter_factory, mock_coordinate_transformation): + # + # Test a detection with rank 1 + # + tracker = Tracker( + "frobenius", + initialization_delay=0, + distance_threshold=1, + filter_factory=filter_factory, + ) + detection = Detection(points=np.array([1, 1])) + assert detection.points.shape == (1, 2) + assert detection.absolute_points.shape == (1, 2) + tracked_objects = tracker.update([detection]) + assert len(tracked_objects) == 1 + tracked_object = tracked_objects[0] + assert tracked_object.estimate.shape == (1, 2) + + +def test_camera_motion(mock_coordinate_transformation): + # + # Simple test for camera motion + # + for one_d in [True, False]: + tracker = Tracker("frobenius", 1, initialization_delay=0) + if one_d: + absolute_points = np.array([1, 1]) + else: + absolute_points = np.array([[1, 1]]) + + relative_points = absolute_points + 1 + + coord_transformation_mock = mock_coordinate_transformation( + relative_points=relative_points, absolute_points=absolute_points + ) + + detection = Detection(relative_points) + tracked_objects = tracker.update( + [detection], coord_transformations=coord_transformation_mock + ) + + # assert that the detection was correctly updated + np.testing.assert_equal( + detection.absolute_points, validate_points(absolute_points) + ) + np.testing.assert_equal(detection.points, validate_points(relative_points)) + + # check the tracked_object + assert len(tracked_objects) == 1 + obj = tracked_objects[0] + np.testing.assert_almost_equal( + obj.get_estimate(absolute=False), validate_points(relative_points) + ) + np.testing.assert_almost_equal( + obj.get_estimate(absolute=True), validate_points(absolute_points) + ) + np.testing.assert_almost_equal(obj.estimate, validate_points(relative_points)) + + # TODO tests list: # - detections with different labels # - partial matches where some points are missing
Absolute paths drawing with centroids We only allow drawing the absolute paths of bounding boxes. To draw an absolute path with centroids points I need to do a trick simulating a bounding box duplicating the centroid coordinate. Example: ``` centroid = np.array( [ [detection_as_xywh[0].item(), detection_as_xywh[1].item()], [detection_as_xywh[0].item(), detection_as_xywh[1].item()], ] ) ```
0.0
062c4330bd75ec3632ff88a97a516a665a718ad2
[ "tests/test_tracker.py::test_1d_points[filter_factory0]", "tests/test_tracker.py::test_1d_points[filter_factory1]", "tests/test_tracker.py::test_camera_motion" ]
[ "tests/test_tracker.py::test_params", "tests/test_tracker.py::test_simple[filter_factory0]", "tests/test_tracker.py::test_simple[filter_factory1]", "tests/test_tracker.py::test_moving[filter_factory0]", "tests/test_tracker.py::test_moving[filter_factory1]", "tests/test_tracker.py::test_distance_t[filter_factory0]", "tests/test_tracker.py::test_distance_t[filter_factory1]" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-29 18:25:28+00:00
bsd-3-clause
6,097
tsdat__tsdat-23
diff --git a/tsdat/pipeline/ingest_pipeline.py b/tsdat/pipeline/ingest_pipeline.py index f5dea5b..ef439d5 100644 --- a/tsdat/pipeline/ingest_pipeline.py +++ b/tsdat/pipeline/ingest_pipeline.py @@ -13,7 +13,7 @@ class IngestPipeline(Pipeline): applying quality checks and quality controls, and by saving the now-processed data in a standard file format.""" - def run(self, filepath: Union[str, List[str]]) -> None: + def run(self, filepath: Union[str, List[str]]) -> xr.Dataset: """Runs the IngestPipeline from start to finish. :param filepath: @@ -48,6 +48,8 @@ class IngestPipeline(Pipeline): # Hook to generate custom plots self.hook_generate_and_persist_plots(dataset) + return dataset + def hook_customize_dataset( self, dataset: xr.Dataset, raw_mapping: Dict[str, xr.Dataset] ) -> xr.Dataset:
tsdat/tsdat
b5e1b0c6c7c94de86175b2b18f6b7fbc2c33cac8
diff --git a/tests/test_examples.py b/tests/test_examples.py index e7c2a58..ff16cd0 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -67,25 +67,21 @@ def pipeline_produced_expected_directory_tree(pipeline: IngestPipeline) -> bool: return True -def pipeline_produced_expected_data( - pipeline: IngestPipeline, expected_data_file: str -) -> bool: - filename = os.path.basename(expected_data_file) - - # Retrieve the output data file - loc_id = pipeline.config.pipeline_definition.location_id - datastream = DSUtil.get_datastream_name(config=pipeline.config) - root: str = pipeline.storage._root - output_file = os.path.join(root, loc_id, datastream, filename) - - # Assert that the basename of the processed file and expected file match - assert os.path.isfile(output_file) - - # Compare data and optionally attributes to ensure everything matches. - ds_out: xr.Dataset = xr.open_dataset(output_file) - ds_exp: xr.Dataset = xr.open_dataset(expected_data_file) - - return ds_out.equals(ds_exp) +def execute_test( + storage_config: str, + pipeline_config: str, + pipeline: IngestPipeline, + input_filepath: str, + expected_filepath: str, +): + delete_existing_outputs(storage_config) + add_pipeline_module_to_path(storage_config) + + _pipeline = pipeline(pipeline_config, storage_config) + ds = _pipeline.run(input_filepath) + expected_ds = xr.open_dataset(expected_filepath) + xr.testing.assert_allclose(ds, expected_ds) + assert pipeline_produced_expected_directory_tree(_pipeline) def test_a2e_buoy_ingest_example(): @@ -98,23 +94,20 @@ def test_a2e_buoy_ingest_example(): STORAGE_CONFIG, ) - delete_existing_outputs(STORAGE_CONFIG) - - add_pipeline_module_to_path(STORAGE_CONFIG) - - humboldt_pipeline = BuoyIngestPipeline(HUMBOLDT_CONFIG, STORAGE_CONFIG) - morro_pipeline = BuoyIngestPipeline(MORRO_CONFIG, STORAGE_CONFIG) - - humboldt_pipeline.run(HUMBOLDT_FILE) - morro_pipeline.run(MORRO_FILE) - - assert pipeline_produced_expected_directory_tree(humboldt_pipeline) - assert pipeline_produced_expected_directory_tree(morro_pipeline) - - assert pipeline_produced_expected_data( - humboldt_pipeline, EXPECTED_HUMBOLDT_BUOY_FILE + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=HUMBOLDT_CONFIG, + pipeline=BuoyIngestPipeline, + input_filepath=HUMBOLDT_FILE, + expected_filepath=EXPECTED_HUMBOLDT_BUOY_FILE, + ) + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=MORRO_CONFIG, + pipeline=BuoyIngestPipeline, + input_filepath=MORRO_FILE, + expected_filepath=EXPECTED_MORRO_BUOY_FILE, ) - assert pipeline_produced_expected_data(morro_pipeline, EXPECTED_MORRO_BUOY_FILE) def test_a2e_imu_ingest_example(): @@ -127,23 +120,20 @@ def test_a2e_imu_ingest_example(): STORAGE_CONFIG, ) - delete_existing_outputs(STORAGE_CONFIG) - - add_pipeline_module_to_path(STORAGE_CONFIG) - - humboldt_pipeline = ImuIngestPipeline(HUMBOLDT_CONFIG, STORAGE_CONFIG) - morro_pipeline = ImuIngestPipeline(MORRO_CONFIG, STORAGE_CONFIG) - - humboldt_pipeline.run(HUMBOLDT_FILE) - morro_pipeline.run(MORRO_FILE) - - assert pipeline_produced_expected_directory_tree(humboldt_pipeline) - assert pipeline_produced_expected_directory_tree(morro_pipeline) - - assert pipeline_produced_expected_data( - humboldt_pipeline, EXPECTED_HUMBOLDT_IMU_FILE + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=HUMBOLDT_CONFIG, + pipeline=ImuIngestPipeline, + input_filepath=HUMBOLDT_FILE, + expected_filepath=EXPECTED_HUMBOLDT_IMU_FILE, + ) + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=MORRO_CONFIG, + pipeline=ImuIngestPipeline, + input_filepath=MORRO_FILE, + expected_filepath=EXPECTED_MORRO_IMU_FILE, ) - assert pipeline_produced_expected_data(morro_pipeline, EXPECTED_MORRO_IMU_FILE) def test_a2e_lidar_ingest_example(): @@ -156,23 +146,20 @@ def test_a2e_lidar_ingest_example(): STORAGE_CONFIG, ) - delete_existing_outputs(STORAGE_CONFIG) - - add_pipeline_module_to_path(STORAGE_CONFIG) - - humboldt_pipeline = LidarIngestPipeline(HUMBOLDT_CONFIG, STORAGE_CONFIG) - morro_pipeline = LidarIngestPipeline(MORRO_CONFIG, STORAGE_CONFIG) - - humboldt_pipeline.run(HUMBOLDT_FILE) - morro_pipeline.run(MORRO_FILE) - - assert pipeline_produced_expected_directory_tree(humboldt_pipeline) - assert pipeline_produced_expected_directory_tree(morro_pipeline) - - assert pipeline_produced_expected_data( - humboldt_pipeline, EXPECTED_HUMBOLDT_LIDAR_FILE + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=HUMBOLDT_CONFIG, + pipeline=LidarIngestPipeline, + input_filepath=HUMBOLDT_FILE, + expected_filepath=EXPECTED_HUMBOLDT_LIDAR_FILE, + ) + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=MORRO_CONFIG, + pipeline=LidarIngestPipeline, + input_filepath=MORRO_FILE, + expected_filepath=EXPECTED_MORRO_LIDAR_FILE, ) - assert pipeline_produced_expected_data(morro_pipeline, EXPECTED_MORRO_LIDAR_FILE) def test_a2e_waves_ingest_example(): @@ -185,20 +172,17 @@ def test_a2e_waves_ingest_example(): STORAGE_CONFIG, ) - delete_existing_outputs(STORAGE_CONFIG) - - add_pipeline_module_to_path(STORAGE_CONFIG) - - humboldt_pipeline = WaveIngestPipeline(HUMBOLDT_CONFIG, STORAGE_CONFIG) - morro_pipeline = WaveIngestPipeline(MORRO_CONFIG, STORAGE_CONFIG) - - humboldt_pipeline.run(HUMBOLDT_FILE) - morro_pipeline.run(MORRO_FILE) - - assert pipeline_produced_expected_directory_tree(humboldt_pipeline) - assert pipeline_produced_expected_directory_tree(morro_pipeline) - - assert pipeline_produced_expected_data( - humboldt_pipeline, EXPECTED_HUMBOLDT_WAVES_FILE + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=HUMBOLDT_CONFIG, + pipeline=WaveIngestPipeline, + input_filepath=HUMBOLDT_FILE, + expected_filepath=EXPECTED_HUMBOLDT_WAVES_FILE, + ) + execute_test( + storage_config=STORAGE_CONFIG, + pipeline_config=MORRO_CONFIG, + pipeline=WaveIngestPipeline, + input_filepath=MORRO_FILE, + expected_filepath=EXPECTED_MORRO_WAVES_FILE, ) - assert pipeline_produced_expected_data(morro_pipeline, EXPECTED_MORRO_WAVES_FILE)
`IngestPipeline.run(*)` should return the processed `xarray.Dataset()` object
0.0
b5e1b0c6c7c94de86175b2b18f6b7fbc2c33cac8
[ "tests/test_examples.py::test_a2e_buoy_ingest_example", "tests/test_examples.py::test_a2e_imu_ingest_example", "tests/test_examples.py::test_a2e_lidar_ingest_example", "tests/test_examples.py::test_a2e_waves_ingest_example" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2021-11-22 23:29:48+00:00
bsd-2-clause
6,098
tsifrer__python-twitch-client-49
diff --git a/twitch/api/search.py b/twitch/api/search.py index 98ae2e9..415e8e3 100644 --- a/twitch/api/search.py +++ b/twitch/api/search.py @@ -16,7 +16,7 @@ class Search(TwitchAPI): 'offset': offset } response = self._request_get('search/channels', params=params) - return [Channel.construct_from(x) for x in response['channels']] + return [Channel.construct_from(x) for x in response['channels'] or []] def games(self, query, live=False): params = { @@ -24,7 +24,7 @@ class Search(TwitchAPI): 'live': live, } response = self._request_get('search/games', params=params) - return [Game.construct_from(x) for x in response['games']] + return [Game.construct_from(x) for x in response['games'] or []] def streams(self, query, limit=25, offset=0, hls=None): if limit > 100: @@ -38,4 +38,4 @@ class Search(TwitchAPI): 'hls': hls } response = self._request_get('search/streams', params=params) - return [Stream.construct_from(x) for x in response['streams']] + return [Stream.construct_from(x) for x in response['streams'] or []]
tsifrer/python-twitch-client
120d8c3fb2c31d035a166062e05606e1d5ec69c4
diff --git a/tests/api/test_search.py b/tests/api/test_search.py index 9869ea3..3789831 100644 --- a/tests/api/test_search.py +++ b/tests/api/test_search.py @@ -62,6 +62,23 @@ def test_channels_raises_if_wrong_params_are_passed_in(param, value): client.search.channels('mah query', **kwargs) [email protected] +def test_channels_does_not_raise_if_no_channels_were_found(): + response = {'channels': None} + responses.add(responses.GET, + '{}search/channels'.format(BASE_URL), + body=json.dumps(response), + status=200, + content_type='application/json') + + client = TwitchClient('client id') + + channels = client.search.channels('mah bad query') + + assert len(responses.calls) == 1 + assert len(channels) == 0 + + @responses.activate def test_games(): response = { @@ -86,6 +103,23 @@ def test_games(): assert game.name == example_game['name'] [email protected] +def test_games_does_not_raise_if_no_games_were_found(): + response = {'games': None} + responses.add(responses.GET, + '{}search/games'.format(BASE_URL), + body=json.dumps(response), + status=200, + content_type='application/json') + + client = TwitchClient('client id') + + games = client.search.games('mah bad query') + + assert len(responses.calls) == 1 + assert len(games) == 0 + + @responses.activate def test_streams(): response = { @@ -123,3 +157,20 @@ def test_streams_raises_if_wrong_params_are_passed_in(param, value): kwargs = {param: value} with pytest.raises(TwitchAttributeException): client.search.streams('mah query', **kwargs) + + [email protected] +def test_streams_does_not_raise_if_no_streams_were_found(): + response = {'streams': None} + responses.add(responses.GET, + '{}search/streams'.format(BASE_URL), + body=json.dumps(response), + status=200, + content_type='application/json') + + client = TwitchClient('client id') + + streams = client.search.streams('mah bad query') + + assert len(responses.calls) == 1 + assert len(streams) == 0
TypeError upon empty games search results. ## Description Upon searching for a game using the `games()` function in `twitch.api.search.Search`, if the query yields no results a `TypeError` is thrown. ## Expected Behavior `games()` should return an empty list like the rest of the Search functions when no results are returned from Twitch. ## Actual Behavior Since the search function tries to perform a list comprehension on the `None` response of `self._request_get()`, a TypeError is raised and the program is terminated. ## Possible Fix Do a quick sanity check on the datatype of `response` from `self._request_get()` in games() before trying to parse it. ## Steps to Reproduce Create a client instance and search for a game title that doesn't exist. ```python from twitch import TwitchClient client = TwitchClient('<my client id>') client.search.games('This is not a valid game title') ``` This should cause a TypeError to get raised with the following output: ``` Traceback (most recent call last): File "crash_test.py", line 3, in <module> client.search.games('This is not a valid game title') File "C:\Python36\lib\site-packages\twitch\api\search.py", line 27, in games return [Game.construct_from(x) for x in response['games']] TypeError: 'NoneType' object is not iterable ``` ## Context I was doing some exploratory research into making a small script to sync a private streaming community's live stream metadata (Game title, stream title, etc) to their twitch restream. ## My Environment * Windows 10 * Python 3.6.4 * python-twitch-client 0.5.1 installed via pip3
0.0
120d8c3fb2c31d035a166062e05606e1d5ec69c4
[ "tests/api/test_search.py::test_channels_does_not_raise_if_no_channels_were_found", "tests/api/test_search.py::test_games_does_not_raise_if_no_games_were_found", "tests/api/test_search.py::test_streams_does_not_raise_if_no_streams_were_found" ]
[ "tests/api/test_search.py::test_streams_raises_if_wrong_params_are_passed_in[limit-101]", "tests/api/test_search.py::test_streams", "tests/api/test_search.py::test_channels_raises_if_wrong_params_are_passed_in[limit-101]", "tests/api/test_search.py::test_channels", "tests/api/test_search.py::test_games" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-10-10 14:23:18+00:00
mit
6,099
tskit-dev__tsdate-293
diff --git a/tsdate/approx.py b/tsdate/approx.py index c5fd295..0db0a87 100644 --- a/tsdate/approx.py +++ b/tsdate/approx.py @@ -111,9 +111,6 @@ def sufficient_statistics(a_i, b_i, a_j, b_j, y_ij, mu_ij): :return: normalizing constant, E[t_i], E[log t_i], E[t_j], E[log t_j] """ - assert a_i > 0 and b_i >= 0, "Invalid parent parameters" - assert a_j > 0 and b_j >= 0, "Invalid child parameters" - assert y_ij >= 0 and mu_ij > 0, "Invalid edge parameters" a = a_i + a_j + y_ij b = a_j @@ -124,9 +121,6 @@ def sufficient_statistics(a_i, b_i, a_j, b_j, y_ij, mu_ij): a_i, b_i, a_j, b_j, y_ij, mu_ij ) - if sign_f <= 0: - raise hypergeo.Invalid2F1("Singular hypergeometric function") - logconst = ( log_f + hypergeo._betaln(y_ij + 1, b) + hypergeo._gammaln(a) - a * np.log(t) ) @@ -142,6 +136,10 @@ def sufficient_statistics(a_i, b_i, a_j, b_j, y_ij, mu_ij): - hypergeo._digamma(c) ) + # check that Jensen's inequality holds + assert np.log(t_i) > ln_t_i + assert np.log(t_j) > ln_t_j + return logconst, t_i, ln_t_i, t_j, ln_t_j diff --git a/tsdate/hypergeo.py b/tsdate/hypergeo.py index 5bd396c..e3e14ea 100644 --- a/tsdate/hypergeo.py +++ b/tsdate/hypergeo.py @@ -29,8 +29,9 @@ import numba import numpy as np from numba.extending import get_cython_function_address +# TODO: these are reasonable defaults, but could +# be made settable via a control dict _HYP2F1_TOL = np.sqrt(np.finfo(np.float64).eps) -_HYP2F1_CHECK = np.sqrt(_HYP2F1_TOL) _HYP2F1_MAXTERM = int(1e6) _PTR = ctypes.POINTER @@ -115,7 +116,7 @@ def _is_valid_2f1(f1, f2, a, b, c, z): See Eq. 6 in https://doi.org/10.1016/j.cpc.2007.11.007 """ if z == 0.0: - return np.abs(f1 - a * b / c) < _HYP2F1_CHECK + return np.abs(f1 - a * b / c) < _HYP2F1_TOL u = c - (a + b + 1) * z v = a * b w = z * (1 - z) @@ -124,7 +125,7 @@ def _is_valid_2f1(f1, f2, a, b, c, z): numer = np.abs(u * f1 - v) else: numer = np.abs(f2 + u / w * f1 - v / w) - return numer / denom < _HYP2F1_CHECK + return numer / denom < _HYP2F1_TOL @numba.njit("UniTuple(float64, 7)(float64, float64, float64, float64)") @@ -255,7 +256,7 @@ def _hyp2f1_recurrence(a, b, c, z): @numba.njit( - "UniTuple(float64, 6)(float64, float64, float64, float64, float64, float64)" + "UniTuple(float64, 7)(float64, float64, float64, float64, float64, float64)" ) def _hyp2f1_dlmf1583_first(a_i, b_i, a_j, b_j, y, mu): """ @@ -287,7 +288,7 @@ def _hyp2f1_dlmf1583_first(a_i, b_i, a_j, b_j, y, mu): ) # 2F1(a, -y; c; z) via backwards recurrence - val, sign, da, _, dc, dz, _ = _hyp2f1_recurrence(a, y, c, z) + val, sign, da, _, dc, dz, d2z = _hyp2f1_recurrence(a, y, c, z) # map gradient to parameters da_i = dc - _digamma(a_i + a_j) + _digamma(a_i) @@ -295,13 +296,18 @@ def _hyp2f1_dlmf1583_first(a_i, b_i, a_j, b_j, y, mu): db_i = dz / (b_j - mu) + a_j / (mu + b_i) db_j = dz * (1 - z) / (b_j - mu) - a_j / s / (mu + b_i) + # needed to verify result + d2b_j = (1 - z) / (b_j - mu) ** 2 * (d2z * (1 - z) - 2 * dz * (1 + a_j)) + ( + 1 + a_j + ) * a_j / (b_j - mu) ** 2 + val += scale - return val, sign, da_i, db_i, da_j, db_j + return val, sign, da_i, db_i, da_j, db_j, d2b_j @numba.njit( - "UniTuple(float64, 6)(float64, float64, float64, float64, float64, float64)" + "UniTuple(float64, 7)(float64, float64, float64, float64, float64, float64)" ) def _hyp2f1_dlmf1583_second(a_i, b_i, a_j, b_j, y, mu): """ @@ -320,7 +326,7 @@ def _hyp2f1_dlmf1583_second(a_i, b_i, a_j, b_j, y, mu): ) # 2F1(a, y+1; c; z) via series expansion - val, sign, da, _, dc, dz, _ = _hyp2f1_taylor_series(a, y + 1, c, z) + val, sign, da, _, dc, dz, d2z = _hyp2f1_taylor_series(a, y + 1, c, z) # map gradient to parameters da_i = da + np.log(z) + dc + _digamma(a_i) - _digamma(a_i + y + 1) @@ -328,10 +334,16 @@ def _hyp2f1_dlmf1583_second(a_i, b_i, a_j, b_j, y, mu): db_i = (1 - z) * (dz + a / z) / (b_i + b_j) db_j = -z * (dz + a / z) / (b_i + b_j) + # needed to verify result + d2b_j = ( + z / (b_i + b_j) ** 2 * (d2z * z + 2 * dz * (1 + a)) + + a * (1 + a) / (b_i + b_j) ** 2 + ) + sign *= (-1) ** (y + 1) val += scale - return val, sign, da_i, db_i, da_j, db_j + return val, sign, da_i, db_i, da_j, db_j, d2b_j @numba.njit( @@ -345,18 +357,14 @@ def _hyp2f1_dlmf1583(a_i, b_i, a_j, b_j, y, mu): assert 0 <= mu <= b_j assert y >= 0 and y % 1.0 == 0.0 - f_1, s_1, da_i_1, db_i_1, da_j_1, db_j_1 = _hyp2f1_dlmf1583_first( + f_1, s_1, da_i_1, db_i_1, da_j_1, db_j_1, d2b_j_1 = _hyp2f1_dlmf1583_first( a_i, b_i, a_j, b_j, y, mu ) - f_2, s_2, da_i_2, db_i_2, da_j_2, db_j_2 = _hyp2f1_dlmf1583_second( + f_2, s_2, da_i_2, db_i_2, da_j_2, db_j_2, d2b_j_2 = _hyp2f1_dlmf1583_second( a_i, b_i, a_j, b_j, y, mu ) - if np.abs(f_1 - f_2) < _HYP2F1_TOL: - # TODO: detect a priori if this will occur - raise Invalid2F1("Singular hypergeometric function") - f_0 = max(f_1, f_2) f_1 = np.exp(f_1 - f_0) * s_1 f_2 = np.exp(f_2 - f_0) * s_2 @@ -366,10 +374,22 @@ def _hyp2f1_dlmf1583(a_i, b_i, a_j, b_j, y, mu): db_i = (db_i_1 * f_1 + db_i_2 * f_2) / f da_j = (da_j_1 * f_1 + da_j_2 * f_2) / f db_j = (db_j_1 * f_1 + db_j_2 * f_2) / f + d2b_j = (d2b_j_1 * f_1 + d2b_j_2 * f_2) / f sign = np.sign(f) val = np.log(np.abs(f)) + f_0 + # use first/second derivatives to check that result is non-singular + dz = -db_j * (mu + b_i) + d2z = d2b_j * (mu + b_i) ** 2 + if ( + not _is_valid_2f1( + dz, d2z, a_j, a_i + a_j + y, a_j + y + 1, (mu - b_j) / (mu + b_i) + ) + or sign <= 0 + ): + raise Invalid2F1("Hypergeometric series is singular") + return val, sign, da_i, db_i, da_j, db_j
tskit-dev/tsdate
4a1890cd5c01c8fc1063fc94e5a654075295c13e
diff --git a/tests/test_hypergeo.py b/tests/test_hypergeo.py index 86afdfa..ba248bd 100644 --- a/tests/test_hypergeo.py +++ b/tests/test_hypergeo.py @@ -240,3 +240,28 @@ class TestTransforms: offset = self._2f1_validate(*pars) check = self._2f1_grad_validate(*pars, offset=offset) assert np.allclose(grad, check) + + [email protected]( + "pars", + [ + # taken from examples in issues tsdate/286, tsdate/289 + [1.104, 0.0001125, 118.1396, 0.009052, 1.0, 0.001404], + [2.7481, 0.001221, 344.94083, 0.02329, 3.0, 0.00026624], + ], +) +class TestSingular2F1: + """ + Test detection of cases where 2F1 is close to singular and DLMF 15.8.3 + suffers from catastrophic cancellation: in these cases, use DLMF 15.8.1 + even though it takes much longer to converge. + """ + + def test_dlmf1583_throws_exception(self, pars): + with pytest.raises(Exception, match="is singular"): + hypergeo._hyp2f1_dlmf1583(*pars) + + def test_exception_uses_dlmf1581(self, pars): + v1, *_ = hypergeo._hyp2f1(*pars) + v2, *_ = hypergeo._hyp2f1_dlmf1581(*pars) + assert np.isclose(v1, v2)
"Invalid parent parameters" error using variational gamma When running the following code, I get an error. I have attached the trees file so we can debug ```python import tskit import tsdate ts = tskit.load("debug.trees") tsdate.date(ts, mutation_rate=1e-8, Ne=1e4, progress=True, method="variational_gamma") ``` ``` File ~/Library/jupyterlab-desktop/jlab_server/lib/python3.10/site-packages/tsdate/core.py:1050, in ExpectationPropagation.iterate(self, iter_num, progress) 1048 if iter_num: 1049 desc = f"EP (iter {iter_num + 1:>2}, leafwards)" -> 1050 self.propagate( 1051 edges=self.edges_by_child_desc(grouped=False), desc=desc, progress=progress 1052 ) File ~/Library/jupyterlab-desktop/jlab_server/lib/python3.10/site-packages/tsdate/core.py:1022, in ExpectationPropagation.propagate(self, edges, desc, progress) 1012 child_cavity = self.lik.ratio( 1013 self.posterior[edge.child], self.child_message[edge.id] 1014 ) 1015 # Get the target posterior: that is, the cavity multiplied by the 1016 # edge likelihood, and projected onto a gamma distribution via 1017 # moment matching. 1018 ( 1019 norm_const, 1020 self.posterior[edge.parent], 1021 self.posterior[edge.child], -> 1022 ) = approx.gamma_projection(*parent_cavity, *child_cavity, *edge_lik) 1023 # Get the messages: that is, the multiplicative difference between 1024 # the target and cavity posteriors. This only involves updating the 1025 # variational parameters for the parent and child on the edge. 1026 self.parent_message[edge.id] = self.lik.ratio( 1027 self.posterior[edge.parent], parent_cavity 1028 ) File ~/Library/jupyterlab-desktop/jlab_server/lib/python3.10/site-packages/tsdate/approx.py:114, in sufficient_statistics() 95 @numba.njit( 96 "UniTuple(float64, 5)(float64, float64, float64, float64, float64, float64)" 97 ) 98 def sufficient_statistics(a_i, b_i, a_j, b_j, y_ij, mu_ij): 99 """ 100 Calculate gamma sufficient statistics for the PDF proportional to 101 :math:`Ga(t_j | a_j, b_j) Ga(t_i | a_i, b_i) Po(y_{ij} | (...) 112 :return: normalizing constant, E[t_i], E[log t_i], E[t_j], E[log t_j] 113 """ --> 114 assert a_i > 0 and b_i >= 0, "Invalid parent parameters" 115 assert a_j > 0 and b_j >= 0, "Invalid child parameters" 116 assert y_ij >= 0 and mu_ij > 0, "Invalid edge parameters" AssertionError: Invalid parent parameters ``` [debug.trees.zip](https://github.com/tskit-dev/tsdate/files/12013054/debug.trees.zip)
0.0
4a1890cd5c01c8fc1063fc94e5a654075295c13e
[ "tests/test_hypergeo.py::TestSingular2F1::test_dlmf1583_throws_exception[pars0]", "tests/test_hypergeo.py::TestSingular2F1::test_dlmf1583_throws_exception[pars1]" ]
[ "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars3]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[1e-10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars38]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars73]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars4]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars39]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[1e-06]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[0.01]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars5]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars6]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[10.0]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[100.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars40]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars41]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars42]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[1000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars43]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[100000.0]", "tests/test_hypergeo.py::TestPolygamma::test_gammaln[10000000000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars7]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars8]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars9]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars44]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars45]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars46]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[1e-10]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[1e-06]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars11]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars74]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars75]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars12]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars76]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[0.01]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars13]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars47]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[10.0]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[100.0]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[1000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars14]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars15]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars48]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars49]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars16]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[100000.0]", "tests/test_hypergeo.py::TestPolygamma::test_digamma[10000000000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars17]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[1e-10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars18]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars77]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[1e-06]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars19]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars50]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars51]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[0.01]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars52]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars78]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars79]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[10.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars53]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[100.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars20]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[1000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars80]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars54]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars21]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[100000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars55]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars56]", "tests/test_hypergeo.py::TestPolygamma::test_trigamma[10000000000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars22]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars0]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[1e-10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars57]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars58]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars59]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars1]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[1e-06]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[0.01]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars60]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[10.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars61]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[100.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars2]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars23]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars24]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars25]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars26]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars62]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars63]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars64]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars3]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars27]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[1000.0]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[100000.0]", "tests/test_hypergeo.py::TestPolygamma::test_betaln[10000000000.0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars4]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars65]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars66]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars67]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars28]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars29]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars30]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars31]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars1]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars2]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars32]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars33]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars5]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars6]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars0]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars68]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars69]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars70]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars34]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars35]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars7]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars8]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars1]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars71]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars72]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars36]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1[pars37]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars2]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars3]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars4]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars5]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars55]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars27]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars28]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars6]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars9]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars10]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars7]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars8]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars9]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars29]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars11]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars56]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars30]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars11]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars12]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars12]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars13]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars57]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars13]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars31]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars14]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars15]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars58]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars16]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars32]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars14]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars17]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars33]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars18]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars15]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars59]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars34]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars19]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars20]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars16]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars35]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars21]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars60]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars17]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars22]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars23]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars36]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars61]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars18]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars62]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars24]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars48]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars37]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars63]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars49]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars50]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars19]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars51]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars52]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars64]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars38]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars53]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars54]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars39]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars55]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars40]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars56]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars57]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars58]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars59]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars41]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars60]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars61]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars42]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars65]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars62]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars43]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars63]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars66]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars64]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars44]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars65]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars67]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars45]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars66]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars67]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars68]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars69]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars46]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars68]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars69]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars1]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars20]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars70]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars21]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars2]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars71]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars22]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars72]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars3]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars4]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars5]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars73]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars6]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars7]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars47]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars8]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars48]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars23]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars24]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars9]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars49]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars25]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars10]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars26]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars11]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars25]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars26]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars12]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars27]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars28]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars29]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars13]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars30]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars31]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars32]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars14]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars33]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars34]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars35]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars15]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars36]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars37]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars38]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars16]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars50]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars39]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars40]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars41]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars51]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars42]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars17]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars43]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars52]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars44]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars18]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars45]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars19]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars46]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars53]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars74]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars75]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars47]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars54]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars20]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars70]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars71]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars21]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars72]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars36]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars73]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars74]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars76]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars75]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars22]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars37]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars38]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars39]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars23]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars24]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars76]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars77]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars78]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars79]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars40]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars80]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars81]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars25]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars82]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars41]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars83]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars26]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars84]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars85]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars42]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars86]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars27]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars87]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars88]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars89]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars28]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars43]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars81]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars29]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars44]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars82]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars30]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars45]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars83]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars31]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars46]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars32]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars84]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars47]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars33]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars48]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars85]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars77]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars78]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars34]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars86]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars49]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars50]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars79]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars35]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars87]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars51]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars67]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars88]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars68]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars52]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars69]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars53]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars89]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars70]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars54]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars90]", "tests/test_hypergeo.py::TestTaylorSeries::test_2f1_grad[pars80]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars90]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars55]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars91]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars71]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars91]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars92]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars93]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars56]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars94]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars72]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars92]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars95]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars96]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars57]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars97]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars73]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars98]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars93]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars99]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars58]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars100]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars74]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars101]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars94]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars59]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars102]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars103]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars75]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars95]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars104]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars105]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars60]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars106]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars76]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars96]", "tests/test_hypergeo.py::TestRecurrence::test_2f1[pars107]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars61]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars77]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars0]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars78]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars20]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars62]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars97]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars21]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars22]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars63]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars23]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars24]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars79]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars98]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars64]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars25]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars26]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars65]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars99]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars27]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars28]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars80]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars66]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars29]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars100]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars101]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars9]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars102]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars106]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars10]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars11]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars12]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars13]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars103]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars14]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars104]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars107]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars15]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars16]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars0]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars17]", "tests/test_hypergeo.py::TestRecurrence::test_2f1_grad[pars105]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars1]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars18]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars2]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars3]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars39]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars19]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars4]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars48]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars49]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars5]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars30]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars6]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars50]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars7]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars51]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars8]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars52]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars56]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars53]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars57]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars58]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars31]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars54]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars32]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars59]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars33]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars34]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars60]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars40]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars41]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars42]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars61]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars43]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars62]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars55]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars63]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars71]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars44]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars72]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars64]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars73]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars45]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars65]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars74]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars46]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars47]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars66]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars84]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars67]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars68]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars69]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars35]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars36]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars37]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars38]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars78]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars85]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars79]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars86]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars87]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars88]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars75]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars89]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars101]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars102]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars103]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars104]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars70]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars96]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars105]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars97]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars98]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars99]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars100]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars80]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars106]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars107]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars108]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars109]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars111]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars112]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars113]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars114]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars110]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars76]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars77]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars90]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars91]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars119]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars92]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars93]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars94]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars81]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars82]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars95]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars83]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars127]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars123]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars128]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars124]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars129]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars115]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars116]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars117]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars130]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars118]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars133]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars134]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1521-pars0-0.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1521-pars0-1.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1521-pars0-5.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1521-pars0-10.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1581-pars1-0.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1581-pars1-1.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1581-pars1-5.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1581-pars1-10.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1583-pars2-0.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1583-pars2-1.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1583-pars2-5.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1[_hyp2f1_dlmf1583-pars2-10.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1521-pars0-0.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1521-pars0-1.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1521-pars0-5.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1521-pars0-10.0]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars120]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1581-pars1-0.0]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars131]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1581-pars1-1.0]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars132]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars125]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1581-pars1-5.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1581-pars1-10.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1583-pars2-1.0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1583-pars2-0.0]", "tests/test_hypergeo.py::TestSingular2F1::test_exception_uses_dlmf1581[pars0]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1583-pars2-10.0]", "tests/test_hypergeo.py::TestSingular2F1::test_exception_uses_dlmf1581[pars1]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars121]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars122]", "tests/test_hypergeo.py::TestCheckValid2F1::test_is_valid_2f1[pars126]", "tests/test_hypergeo.py::TestTransforms::test_2f1_grad[_hyp2f1_dlmf1583-pars2-5.0]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-07-12 22:11:46+00:00
mit
6,100
tsroten__dragonmapper-21
diff --git a/docs/index.rst b/docs/index.rst index 558b17c..310ad40 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -15,6 +15,7 @@ functions for Chinese text processing: .. code:: python + >>> import dragonmapper.hanzi >>> s = '我是一个美国人。' >>> dragonmapper.hanzi.is_simplified(s) True @@ -25,6 +26,7 @@ functions for Chinese text processing: .. code:: python + >>> import dragonmapper.transcriptions >>> s = 'Wǒ shì yīgè měiguórén.' >>> dragonmapper.transcriptions.is_pinyin(s) True diff --git a/dragonmapper/data/transcriptions.csv b/dragonmapper/data/transcriptions.csv index 6447017..072be78 100644 --- a/dragonmapper/data/transcriptions.csv +++ b/dragonmapper/data/transcriptions.csv @@ -234,6 +234,7 @@ nun,ㄋㄨㄣ,nwən nuo,ㄋㄨㄛ,nwɔ nü,ㄋㄩ,ny nüe,ㄋㄩㄝ,nɥœ +o,ㄛ,ɔ ou,ㄡ,oʊ pa,ㄆㄚ,pʰa pai,ㄆㄞ,pʰaɪ
tsroten/dragonmapper
0f58b30f65718494afb1de9cb25d68d5b3246a0f
diff --git a/dragonmapper/tests/test-transcriptions.py b/dragonmapper/tests/test-transcriptions.py index a4d5e14..04a5733 100644 --- a/dragonmapper/tests/test-transcriptions.py +++ b/dragonmapper/tests/test-transcriptions.py @@ -173,3 +173,9 @@ class TestConvertFunctions(unittest.TestCase): numbered = 'Ao4di4li4' self.assertEqual(numbered, trans.accented_to_numbered(accented)) + + def test_issue_23(self): + pinyin = 'ó' + zhuyin = 'ㄛˊ' + + self.assertEqual(zhuyin, trans.pinyin_to_zhuyin(pinyin))
AttributeError: 'module' object has no attribute 'hanzi' Hey! I'm trying to use dragonmapper and I'm getting a confusing error. I installed it on Ubuntu 16.04 with the following command: `pip install dragonmapper --user` Then tried to use it: ``` import dragonmapper dragonmapper.hanzi.is_simplified(u'你好') ``` but get the following error: `AttributeError: 'module' object has no attribute 'hanzi'` python --version outputs: `Python 2.7.12` What's up?
0.0
0f58b30f65718494afb1de9cb25d68d5b3246a0f
[ "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_23" ]
[ "dragonmapper/tests/test-transcriptions.py::TestIdentifyFunctions::test_is_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestIdentifyFunctions::test_is_zhuyin_compatible", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_drop_apostrophe", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_handle_middle_dot", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_ipa_to_pinyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_ipa_to_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_2", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_3", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_4", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_5", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_6", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_8", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_middle_dot", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_r_suffix", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_to_ipa", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_to_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_zhuyin_to_ipa", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_zhuyin_to_pinyin" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-10-22 00:18:13+00:00
mit
6,101
tsroten__dragonmapper-24
diff --git a/dragonmapper/data/transcriptions.csv b/dragonmapper/data/transcriptions.csv index 6447017..072be78 100644 --- a/dragonmapper/data/transcriptions.csv +++ b/dragonmapper/data/transcriptions.csv @@ -234,6 +234,7 @@ nun,ㄋㄨㄣ,nwən nuo,ㄋㄨㄛ,nwɔ nü,ㄋㄩ,ny nüe,ㄋㄩㄝ,nɥœ +o,ㄛ,ɔ ou,ㄡ,oʊ pa,ㄆㄚ,pʰa pai,ㄆㄞ,pʰaɪ
tsroten/dragonmapper
0f58b30f65718494afb1de9cb25d68d5b3246a0f
diff --git a/dragonmapper/tests/test-transcriptions.py b/dragonmapper/tests/test-transcriptions.py index a4d5e14..04a5733 100644 --- a/dragonmapper/tests/test-transcriptions.py +++ b/dragonmapper/tests/test-transcriptions.py @@ -173,3 +173,9 @@ class TestConvertFunctions(unittest.TestCase): numbered = 'Ao4di4li4' self.assertEqual(numbered, trans.accented_to_numbered(accented)) + + def test_issue_23(self): + pinyin = 'ó' + zhuyin = 'ㄛˊ' + + self.assertEqual(zhuyin, trans.pinyin_to_zhuyin(pinyin))
Pinyin/Zhuyin/IPA syllable `o` is missing. ```python >>> print(transcriptions.pinyin_to_zhuyin(ó)) Traceback (most recent call last): File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 100, in <module> print(printBopomofo(eachLine)+"\n"*3) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 42, in printBopomofo bopomofoDictionary=makeToneDictionary(hanzistring2) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 35, in makeToneDictionary bopomofoList=listBopomofo(hanzi) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 11, in listBopomofo print(transcriptions.pinyin_to_zhuyin(ó)) NameError: name 'ó' is not defined ``` also the following string returns an error ``` (1 4 事情是這樣的 , 父親讀到也看到許多偉大而奇妙的事時 , 他向主高呼許多事 , 諸如 : 哦 , 主神全能者 , 您的事工多麼偉大而奇妙 ! 您的寶座在高天之上 , 您的大能、良善和慈悲廣被世上全民 , 而且 , 由於您的慈悲 , 您不會讓歸向您的人滅亡 ! ) ``` ```python >>> pinyin=hanzi.to_zhuyin(hanzistring) Traceback (most recent call last): File "C:\Users\Kei\AppData\Local\Programs\Python\Python35\lib\site-packages\dragonmapper\transcriptions.py", line 227, in pinyin_syllable_to_zhuyin zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin'] KeyError: 'o' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 100, in <module> print(printBopomofo(eachLine)+"\n"*3) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 42, in printBopomofo bopomofoDictionary=makeToneDictionary(hanzistring2) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 35, in makeToneDictionary bopomofoList=listBopomofo(hanzi) File "D:\OneDrive\My Programs\zhuyin converter\Convert2BopomofoPunctuation.py", line 12, in listBopomofo pinyin=hanzi.to_zhuyin(hanzistring) File "C:\Users\Kei\AppData\Local\Programs\Python\Python35\lib\site-packages\dragonmapper\hanzi.py", line 190, in to_zhuyin zhuyin = pinyin_to_zhuyin(numbered_pinyin) File "C:\Users\Kei\AppData\Local\Programs\Python\Python35\lib\site-packages\dragonmapper\transcriptions.py", line 365, in pinyin_to_zhuyin remove_apostrophes=True, separate_syllables=True) File "C:\Users\Kei\AppData\Local\Programs\Python\Python35\lib\site-packages\dragonmapper\transcriptions.py", line 341, in _convert new += syllable_function(match.group()) File "C:\Users\Kei\AppData\Local\Programs\Python\Python35\lib\site-packages\dragonmapper\transcriptions.py", line 229, in pinyin_syllable_to_zhuyin raise ValueError('Not a valid syllable: %s' % s) ValueError: Not a valid syllable: o2 ```
0.0
0f58b30f65718494afb1de9cb25d68d5b3246a0f
[ "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_23" ]
[ "dragonmapper/tests/test-transcriptions.py::TestIdentifyFunctions::test_is_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestIdentifyFunctions::test_is_zhuyin_compatible", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_drop_apostrophe", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_handle_middle_dot", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_ipa_to_pinyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_ipa_to_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_2", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_3", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_4", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_5", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_6", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_issue_8", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_middle_dot", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_r_suffix", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_to_ipa", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_pinyin_to_zhuyin", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_zhuyin_to_ipa", "dragonmapper/tests/test-transcriptions.py::TestConvertFunctions::test_zhuyin_to_pinyin" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-03-21 14:35:28+00:00
mit
6,102
tsutsu3__linkify-it-py-24
diff --git a/README.md b/README.md index 0763763..bd45d54 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![CI](https://github.com/tsutsu3/linkify-it-py/workflows/CI/badge.svg?branch=main)](https://github.com/tsutsu3/linkify-it-py/actions) [![pypi](https://img.shields.io/pypi/v/linkify-it-py)](https://pypi.org/project/linkify-it-py/) +[![Anaconda-Server Badge](https://anaconda.org/conda-forge/linkify-it-py/badges/version.svg)](https://anaconda.org/conda-forge/linkify-it-py) [![codecov](https://codecov.io/gh/tsutsu3/linkify-it-py/branch/main/graph/badge.svg)](https://codecov.io/gh/tsutsu3/linkify-it-py) [![Maintainability](https://api.codeclimate.com/v1/badges/6341fd3ec5f05fde392f/maintainability)](https://codeclimate.com/github/tsutsu3/linkify-it-py/maintainability) @@ -25,6 +26,12 @@ Why it's awesome: pip install linkify-it-py ``` +or + +```bash +conda install -c conda-forge linkify-it-py +``` + ## Usage examples ### Example 1. Simple use @@ -82,28 +89,28 @@ print(linkify.match("Site tamanegi.onion!")) ### Example 3. Add twitter mentions handler ```python -from linkify import LinkfiyIt +from linkify_it import LinkifyIt -linkifyit = LinkifyIt() +linkify = LinkifyIt() -def validate(self, text, pos): +def validate(obj, text, pos): tail = text[pos:] - if not self.re.get("twitter"): - self.re["twitter"] = re.compile( - "^([a-zA-Z0-9_]){1,15}(?!_)(?=$|" + self.re["src_ZPCc"] + ")" + if not obj.re.get("twitter"): + obj.re["twitter"] = re.compile( + "^([a-zA-Z0-9_]){1,15}(?!_)(?=$|" + obj.re["src_ZPCc"] + ")" ) - if self.re["twitter"].search(tail): + if obj.re["twitter"].search(tail): if pos > 2 and tail[pos - 2] == "@": return False - return len(self.re["twitter"].search(tail).group()) + return len(obj.re["twitter"].search(tail).group()) return 0 -def normalize(self, m): - m.url = "https://twitter.com/" + re.sub(r"^@", "", m.url) +def normalize(obj, match): + match.url = "https://twitter.com/" + re.sub(r"^@", "", match.url) -linkifyit.add("@", {"validate": validate, "normalize": normalize}) +linkify.add("@", {"validate": validate, "normalize": normalize}) ``` diff --git a/linkify_it/main.py b/linkify_it/main.py index 7e6af33..b06a7b3 100644 --- a/linkify_it/main.py +++ b/linkify_it/main.py @@ -189,7 +189,7 @@ class LinkifyIt: def _create_normalizer(self): def func(match): - self._normalize(match) + self.normalize(match) return func @@ -590,11 +590,11 @@ class LinkifyIt: self._compile() return self - def _normalize(self, match): + def normalize(self, match): """Default normalizer (if schema does not define it's own). Args: - match (): + match (:class:`linkify_it.main.Match`): Match result """ if not match.schema: match.url = "http://" + match.url
tsutsu3/linkify-it-py
1e35d3c46172864eb3e2c275d6e797a1b2acb43e
diff --git a/test/test_linkify.py b/test/test_linkify.py index afa4f00..79bf297 100644 --- a/test/test_linkify.py +++ b/test/test_linkify.py @@ -20,7 +20,7 @@ def dummy(_): def test_links(number, line, expected): linkifyit = LinkifyIt(options={"fuzzy_ip": True}) - linkifyit._normalize = dummy + linkifyit.normalize = dummy assert linkifyit.pretest(line) is True assert linkifyit.test("\n" + line + "\n") is True @@ -35,6 +35,6 @@ def test_links(number, line, expected): def test_not_links(number, line, expected): linkifyit = LinkifyIt() - linkifyit._normalize = dummy + linkifyit.normalize = dummy assert linkifyit.test(line) is False
Release on conda-forge If you release on conda-forge, then I'll include in markdown-it-py conda requirements 😄 (If you don't know, you need to make a PR to https://github.com/conda-forge/staged-recipes)
0.0
1e35d3c46172864eb3e2c275d6e797a1b2acb43e
[ "test/test_linkify.py::test_links[49->>example.com", "test/test_linkify.py::test_links[88-4.4.4.4-4.4.4.4]", "test/test_linkify.py::test_links[90-192.168.1.1/abc-192.168.1.1/abc]", "test/test_linkify.py::test_links[102-google.com-google.com]", "test/test_linkify.py::test_links[104-google.com:", "test/test_linkify.py::test_links[107-s.l.o.w.io-s.l.o.w.io]", "test/test_linkify.py::test_links[109-a-b.com-a-b.com]", "test/test_linkify.py::test_links[111-GOOGLE.COM.-GOOGLE.COM]", "test/test_linkify.py::test_links[114-google.xxx", "test/test_linkify.py::test_links[153-[example.com/foo_bar.jpg)]-example.com/foo_bar.jpg]", "test/test_linkify.py::test_links[218-<domain.com>-domain.com]", "test/test_linkify.py::test_links[221-<domain.com>.-domain.com]", "test/test_linkify.py::test_links[224-<domain.com/foo>-domain.com/foo]", "test/test_linkify.py::test_links[227-<[email protected]>[email protected]]", "test/test_linkify.py::test_links[230-<[email protected]>[email protected]]", "test/test_linkify.py::test_links[241-test.\"foo\"[email protected]!-test.\"foo\"[email protected]]", "test/test_linkify.py::test_links[244-\"[email protected]\"[email protected]]", "test/test_linkify.py::test_links[[email protected]@example.com]", "test/test_linkify.py::test_links[249->>[email protected]", "test/test_linkify.py::test_links[[email protected][email protected]]", "test/test_linkify.py::test_links[[email protected]@gmail.com]", "test/test_linkify.py::test_links[265-(foobar", "test/test_linkify.py::test_links[268-([email protected]", "test/test_linkify.py::test_links[271-([email protected])[email protected]]", "test/test_linkify.py::test_links[282-a.ws-a.ws]", "test/test_linkify.py::test_links[284-\\u27a1.ws/\\u4a39-\\u27a1.ws/\\u4a39]", "test/test_linkify.py::test_links[286-example.com/\\u4a39-example.com/\\u4a39]", "test/test_linkify.py::test_links[288-\\u043f\\u0440\\u0435\\u0437\\u0438\\u0434\\u0435\\u043d\\u0442.\\u0440\\u0444-\\u043f\\u0440\\u0435\\u0437\\u0438\\u0434\\u0435\\u043d\\u0442.\\u0440\\u0444]", "test/test_linkify.py::test_links[309-\\uff5cwww.google.com/www.google.com/foo\\uff5cbar", "test/test_linkify.py::test_links[312-\\[email protected]\\[email protected]]", "test/test_linkify.py::test_links[324-www.a--b.com-www.a--b.com]", "test/test_linkify.py::test_links[326-www.c--u.com-www.c--u.com]" ]
[ "test/test_linkify.py::test_links[4-My", "test/test_linkify.py::test_links[7-My", "test/test_linkify.py::test_links[10-http://example.com/foo_bar/-http://example.com/foo_bar/]", "test/test_linkify.py::test_links[12-http://user:[email protected]:8080-http://user:[email protected]:8080]", "test/test_linkify.py::test_links[14-http://[email protected]://[email protected]]", "test/test_linkify.py::test_links[16-http://[email protected]:8080-http://[email protected]:8080]", "test/test_linkify.py::test_links[18-http://user:[email protected]://user:[email protected]]", "test/test_linkify.py::test_links[20-[https](https://www.ibm.com)[mailto](mailto:[email protected])", "test/test_linkify.py::test_links[23-http://example.com:8080-http://example.com:8080]", "test/test_linkify.py::test_links[25-http://example.com/?foo=bar-http://example.com/?foo=bar]", "test/test_linkify.py::test_links[27-http://example.com?foo=bar-http://example.com?foo=bar]", "test/test_linkify.py::test_links[29-http://example.com/#foo=bar-http://example.com/#foo=bar]", "test/test_linkify.py::test_links[31-http://example.com#foo=bar-http://example.com#foo=bar]", "test/test_linkify.py::test_links[33-http://a.in-http://a.in]", "test/test_linkify.py::test_links[35-HTTP://GOOGLE.COM-HTTP://GOOGLE.COM]", "test/test_linkify.py::test_links[37-http://example.invalid", "test/test_linkify.py::test_links[40-http://inrgess2", "test/test_linkify.py::test_links[43-http://999", "test/test_linkify.py::test_links[46-http://host-name", "test/test_linkify.py::test_links[52->>http://example.com", "test/test_linkify.py::test_links[55-http://lyricstranslate.com/en/someone-you-\\u0d28\\u0d3f\\u0d28\\u0d4d\\u0d28\\u0d46-\\u0d2a\\u0d4b\\u0d32\\u0d4a\\u0d30\\u0d3e\\u0d33\\u0d4d\\u200d.html", "test/test_linkify.py::test_links[61-//localhost-//localhost]", "test/test_linkify.py::test_links[63-//test.123-//test.123]", "test/test_linkify.py::test_links[65-http://localhost:8000?-http://localhost:8000]", "test/test_linkify.py::test_links[72-My", "test/test_linkify.py::test_links[75-My", "test/test_linkify.py::test_links[82-My", "test/test_linkify.py::test_links[96-test.example@http://vk.com-http://vk.com]", "test/test_linkify.py::test_links[99-text:http://example.com/-http://example.com/]", "test/test_linkify.py::test_links[121-(Scoped", "test/test_linkify.py::test_links[124-http://example.com/foo_bar_(wiki)-http://example.com/foo_bar_(wiki)]", "test/test_linkify.py::test_links[126-http://foo.com/blah_blah_[other]-http://foo.com/blah_blah_[other]]", "test/test_linkify.py::test_links[128-http://foo.com/blah_blah_{I'm_king}-http://foo.com/blah_blah_{I'm_king}]", "test/test_linkify.py::test_links[130-http://foo.com/blah_blah_I'm_king-http://foo.com/blah_blah_I'm_king]", "test/test_linkify.py::test_links[132-http://www.kmart.com/bestway-10'-x-30inch-steel-pro-frame-pool/p-004W007538417001P-http://www.kmart.com/bestway-10'-x-30inch-steel-pro-frame-pool/p-004W007538417001P]", "test/test_linkify.py::test_links[134-http://foo.com/blah_blah_\"doublequoted\"-http://foo.com/blah_blah_\"doublequoted\"]", "test/test_linkify.py::test_links[136-http://foo.com/blah_blah_'singlequoted'-http://foo.com/blah_blah_'singlequoted']", "test/test_linkify.py::test_links[138-(Scoped", "test/test_linkify.py::test_links[141-[Scoped", "test/test_linkify.py::test_links[144-{Scoped", "test/test_linkify.py::test_links[147-\"Quoted", "test/test_linkify.py::test_links[150-'Quoted", "test/test_linkify.py::test_links[156-http://example.com/foo_bar.jpg.-http://example.com/foo_bar.jpg]", "test/test_linkify.py::test_links[159-http://example.com/foo_bar/.-http://example.com/foo_bar/]", "test/test_linkify.py::test_links[162-http://example.com/foo_bar,-http://example.com/foo_bar]", "test/test_linkify.py::test_links[165-https://github.com/markdown-it/linkify-it/compare/360b13a733f521a8d4903d3a5e1e46c357e9d3ce...f580766349525150a80a32987bb47c2d592efc33-https://github.com/markdown-it/linkify-it/compare/360b13a733f521a8d4903d3a5e1e46c357e9d3ce...f580766349525150a80a32987bb47c2d592efc33]", "test/test_linkify.py::test_links[167-https://www.google.com/search?sxsrf=ACYBGNTJFmX-GjNJ8fM-2LCkqyNyxGU1Ng%3A1575534146332&ei=Qr7oXf7rE4rRrgSEgrmoAw&q=clover&oq=clover&gs_l=psy-ab.3..0i67j0l9.2986.3947..4187...0.2..0.281.1366.1j0j5......0....1..gws-wiz.......0i71j35i39j0i131.qWp1nz4IJVA&ved=0ahUKEwj-lP6Iip7mAhWKqIsKHQRBDjUQ4dUDCAs&uact=5-https://www.google.com/search?sxsrf=ACYBGNTJFmX-GjNJ8fM-2LCkqyNyxGU1Ng%3A1575534146332&ei=Qr7oXf7rE4rRrgSEgrmoAw&q=clover&oq=clover&gs_l=psy-ab.3..0i67j0l9.2986.3947..4187...0.2..0.281.1366.1j0j5......0....1..gws-wiz.......0i71j35i39j0i131.qWp1nz4IJVA&ved=0ahUKEwj-lP6Iip7mAhWKqIsKHQRBDjUQ4dUDCAs&uact=5]", "test/test_linkify.py::test_links[169-https://ourworldindata.org/grapher/covid-deaths-days-since-per-million?zoomToSelection=true&time=9..&country=FRA+DEU+ITA+ESP+GBR+USA+CAN-https://ourworldindata.org/grapher/covid-deaths-days-since-per-million?zoomToSelection=true&time=9..&country=FRA+DEU+ITA+ESP+GBR+USA+CAN]", "test/test_linkify.py::test_links[171-http://example.com/foo_bar...-http://example.com/foo_bar]", "test/test_linkify.py::test_links[174-http://172.26.142.48/viewerjs/#../0529/slides.pdf-http://172.26.142.48/viewerjs/#../0529/slides.pdf]", "test/test_linkify.py::test_links[176-http://example.com/foo_bar..-http://example.com/foo_bar]", "test/test_linkify.py::test_links[179-http://example.com/foo_bar?p=10.-http://example.com/foo_bar?p=10]", "test/test_linkify.py::test_links[182-https://www.google.ru/maps/@59.9393895,30.3165389,15z?hl=ru-https://www.google.ru/maps/@59.9393895,30.3165389,15z?hl=ru]", "test/test_linkify.py::test_links[184-https://www.google.com/maps/place/New+York,+NY,+USA/@40.702271,-73.9968471,11z/data=!4m2!3m1!1s0x89c24fa5d33f083b:0xc80b8f06e177fe62?hl=en-https://www.google.com/maps/place/New+York,+NY,+USA/@40.702271,-73.9968471,11z/data=!4m2!3m1!1s0x89c24fa5d33f083b:0xc80b8f06e177fe62?hl=en]", "test/test_linkify.py::test_links[186-https://www.google.com/analytics/web/?hl=ru&pli=1#report/visitors-overview/a26895874w20458057p96934174/-https://www.google.com/analytics/web/?hl=ru&pli=1#report/visitors-overview/a26895874w20458057p96934174/]", "test/test_linkify.py::test_links[188-http://business.timesonline.co.uk/article/0,,9065-2473189,00.html-http://business.timesonline.co.uk/article/0,,9065-2473189,00.html]", "test/test_linkify.py::test_links[190-https://google.com/mail/u/0/#label/!!!Today/15c9b8193da01e65-https://google.com/mail/u/0/#label/!!!Today/15c9b8193da01e65]", "test/test_linkify.py::test_links[192-http://example.com/123!-http://example.com/123]", "test/test_linkify.py::test_links[195-http://example.com/123!!!-http://example.com/123]", "test/test_linkify.py::test_links[198-http://example.com/foo--bar-http://example.com/foo--bar]", "test/test_linkify.py::test_links[201-http://www.bloomberg.com/news/articles/2015-06-26/from-deutsche-bank-to-siemens-what-s-troubling-germany-inc--http://www.bloomberg.com/news/articles/2015-06-26/from-deutsche-bank-to-siemens-what-s-troubling-germany-inc-]", "test/test_linkify.py::test_links[203-http://example.com/foo-with-trailing-dash-dot-.-http://example.com/foo-with-trailing-dash-dot-]", "test/test_linkify.py::test_links[206-<http://domain.com>-http://domain.com]", "test/test_linkify.py::test_links[209-<http://domain.com>.-http://domain.com]", "test/test_linkify.py::test_links[212-<http://domain.com/foo>-http://domain.com/foo]", "test/test_linkify.py::test_links[215-<http://domain.com/foo>.-http://domain.com/foo]", "test/test_linkify.py::test_links[233-<mailto:[email protected]>-mailto:[email protected]]", "test/test_linkify.py::test_links[252-mailto:[email protected]:[email protected]]", "test/test_linkify.py::test_links[254-MAILTO:[email protected]:[email protected]]", "test/test_linkify.py::test_links[256-mailto:[email protected]:[email protected]]", "test/test_linkify.py::test_links[262-mailto:foo@bar", "test/test_linkify.py::test_links[278-http://\\u272adf.ws/123-http://\\u272adf.ws/123]", "test/test_linkify.py::test_links[280-http://xn--df-oiy.ws/123-http://xn--df-oiy.ws/123]", "test/test_linkify.py::test_links[294-http://www.b\\xfcrgerentscheid-krankenh\\xe4user.de-http://www.b\\xfcrgerentscheid-krankenh\\xe4user.de]", "test/test_linkify.py::test_links[296-http://www.xn--brgerentscheid-krankenhuser-xkc78d.de-http://www.xn--brgerentscheid-krankenhuser-xkc78d.de]", "test/test_linkify.py::test_links[298-http://b\\xfcndnis-f\\xfcr-krankenh\\xe4user.de/wp-content/uploads/2011/11/cropped-logohp.jpg-http://b\\xfcndnis-f\\xfcr-krankenh\\xe4user.de/wp-content/uploads/2011/11/cropped-logohp.jpg]", "test/test_linkify.py::test_links[300-http://xn--bndnis-fr-krankenhuser-i5b27cha.de/wp-content/uploads/2011/11/cropped-logohp.jpg-http://xn--bndnis-fr-krankenhuser-i5b27cha.de/wp-content/uploads/2011/11/cropped-logohp.jpg]", "test/test_linkify.py::test_links[302-http://\\ufee1\\ufeee\\ufed8\\ufecb.\\ufeed\\ufeaf\\ufe8d\\ufead\\ufe93-\\ufe8d\\ufefc\\ufe98\\ufebb\\ufe8d\\ufefc\\ufe97.\\ufee2\\ufebb\\ufead/-http://\\ufee1\\ufeee\\ufed8\\ufecb.\\ufeed\\ufeaf\\ufe8d\\ufead\\ufe93-\\ufe8d\\ufefc\\ufe98\\ufebb\\ufe8d\\ufefc\\ufe97.\\ufee2\\ufebb\\ufead/]", "test/test_linkify.py::test_links[304-http://xn--4gbrim.xn----ymcbaaajlc6dj7bxne2c.xn--wgbh1c/-http://xn--4gbrim.xn----ymcbaaajlc6dj7bxne2c.xn--wgbh1c/]", "test/test_linkify.py::test_links[315-\\uff5chttp://google.com\\uff5cbar-http://google.com]", "test/test_linkify.py::test_links[322-https://5b0ee223b312746c1659db3f--thelounge-chat.netlify.com/docs/-https://5b0ee223b312746c1659db3f--thelounge-chat.netlify.com/docs/]", "test/test_linkify.py::test_links[328-http://a---b.com/-http://a---b.com/]", "test/test_linkify.py::test_not_links[4-example.invalid-example.invalid/]", "test/test_linkify.py::test_not_links[6-http://.example.com-http://-example.com]", "test/test_linkify.py::test_not_links[8-hppt://example.com-example.coma]", "test/test_linkify.py::test_not_links[10--example.coma-foo.123]", "test/test_linkify.py::test_not_links[12-localhost", "test/test_linkify.py::test_not_links[14-///localhost", "test/test_linkify.py::test_not_links[16-//test", "test/test_linkify.py::test_not_links[18-_http://example.com-_//example.com]", "test/test_linkify.py::test_not_links[20-_example.com-http://example.com_]", "test/test_linkify.py::test_not_links[[email protected]@example.com]", "test/test_linkify.py::test_not_links[24-node.js", "test/test_linkify.py::test_not_links[26-http://-http://.]", "test/test_linkify.py::test_not_links[28-http://..-http://#]", "test/test_linkify.py::test_not_links[30-http://##-http://?]", "test/test_linkify.py::test_not_links[32-http://??-google.com:500000", "test/test_linkify.py::test_not_links[34-show", "test/test_linkify.py::test_not_links[36-/path/to/file.pl-/path/to/file.pl]", "test/test_linkify.py::test_not_links[41-1.2.3.4.5-1.2.3]", "test/test_linkify.py::test_not_links[43-1.2.3.400-1000.2.3.4]", "test/test_linkify.py::test_not_links[45-a1.2.3.4-1.2.3.4a]", "test/test_linkify.py::test_not_links[51-foo@bar" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-19 07:54:04+00:00
mit
6,103
ttu__ruuvitag-sensor-41
diff --git a/ruuvitag_sensor/ruuvi.py b/ruuvitag_sensor/ruuvi.py index ffd6bc6..0dffc62 100644 --- a/ruuvitag_sensor/ruuvi.py +++ b/ruuvitag_sensor/ruuvi.py @@ -202,13 +202,12 @@ class RuuviTagSensor(object): Returns: string: Sensor data """ + # Search of FF990403 (Manufacturer Specific Data (FF) / Ruuvi Innovations ltd (9904) / Format 3 (03)) try: - if len(raw) != 54: + if "FF990403" not in raw: return None - if raw[16:18] != '03': - return None - - return raw[16:] + payload_start = raw.index("FF990403") + 6; + return raw[payload_start:] except: return None
ttu/ruuvitag-sensor
c0d986391149d31d60d9649cfd9f3946db92a50c
diff --git a/tests/test_decoder.py b/tests/test_decoder.py index cd92d1d..639b71a 100644 --- a/tests/test_decoder.py +++ b/tests/test_decoder.py @@ -51,6 +51,16 @@ class TestDecoder(TestCase): self.assertNotEqual(data['acceleration_y'], 0) self.assertNotEqual(data['acceleration_z'], 0) + data = decoder.decode_data('03291A1ECE1EFC18F94202CA0B53BB') + self.assertEqual(data['temperature'], 26.3) + self.assertEqual(data['pressure'], 1027.66) + self.assertEqual(data['humidity'], 20.5) + self.assertEqual(data['battery'], 2899) + self.assertNotEqual(data['acceleration'], 0) + self.assertEqual(data['acceleration_x'], -1000) + self.assertNotEqual(data['acceleration_y'], 0) + self.assertNotEqual(data['acceleration_z'], 0) + def test_df3decode_is_valid_max_values(self): decoder = Df3Decoder() humidity = 'C8' diff --git a/tests/test_ruuvitag_sensor.py b/tests/test_ruuvitag_sensor.py index ac9e3bb..16fcbc0 100644 --- a/tests/test_ruuvitag_sensor.py +++ b/tests/test_ruuvitag_sensor.py @@ -47,7 +47,8 @@ class TestRuuviTagSensor(TestCase): ('CC:2C:6A:1E:59:3D', '1E0201060303AAFE1616AAFE10EE037275752E76692F23416A7759414D4663CD'), ('DD:2C:6A:1E:59:3D', '1E0201060303AAFE1616AAFE10EE037275752E76692F23416A7759414D4663CD'), ('EE:2C:6A:1E:59:3D', '1F0201060303AAFE1716AAFE10F9037275752E76692F23416A5558314D417730C3'), - ('FF:2C:6A:1E:59:3D', '1902010415FF990403291A1ECE1E02DEF94202CA0B5300000000BB') + ('FF:2C:6A:1E:59:3D', '1902010415FF990403291A1ECE1E02DEF94202CA0B5300000000BB'), + ('00:2C:6A:1E:59:3D', '1902010415FF990403291A1ECE1E02DEF94202CA0B53BB') ] for data in datas: @@ -59,7 +60,7 @@ class TestRuuviTagSensor(TestCase): get_datas) def test_find_tags(self): tags = RuuviTagSensor.find_ruuvitags() - self.assertEqual(5, len(tags)) + self.assertEqual(6, len(tags)) @patch('ruuvitag_sensor.ble_communication.BleCommunicationDummy.get_datas', get_datas) @@ -87,7 +88,7 @@ class TestRuuviTagSensor(TestCase): def test_get_datas(self): datas = [] RuuviTagSensor.get_datas(lambda x: datas.append(x)) - self.assertEqual(5, len(datas)) + self.assertEqual(6, len(datas)) @patch('ruuvitag_sensor.ble_communication.BleCommunicationDummy.get_datas', get_datas)
Bug: incompatible with RuuviFW 1.2.8 The 1.2.8 update to Ruuvi Firmware trims extra NULLs at the end of transmission which breaks the data format type check. I can fix this and implement #29 .
0.0
c0d986391149d31d60d9649cfd9f3946db92a50c
[ "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_find_tags", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_get_datas" ]
[ "tests/test_decoder.py::TestDecoder::test_decode_is_valid", "tests/test_decoder.py::TestDecoder::test_decode_is_valid_case2", "tests/test_decoder.py::TestDecoder::test_decode_is_valid_weatherstation_2017_04_12", "tests/test_decoder.py::TestDecoder::test_df3decode_is_valid", "tests/test_decoder.py::TestDecoder::test_df3decode_is_valid_max_values", "tests/test_decoder.py::TestDecoder::test_df3decode_is_valid_min_values", "tests/test_decoder.py::TestDecoder::test_getcorrectdecoder", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_convert_data_not_valid", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_false_mac_raise_error", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_get_data_for_sensors", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_get_datas_with_macs", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_tag_correct_properties", "tests/test_ruuvitag_sensor.py::TestRuuviTagSensor::test_tag_update_is_valid" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2018-04-19 15:39:25+00:00
mit
6,104
twilio__twilio-python-477
diff --git a/twilio/request_validator.py b/twilio/request_validator.py index 72cdb6298..c24a52acd 100644 --- a/twilio/request_validator.py +++ b/twilio/request_validator.py @@ -21,19 +21,42 @@ def compare(string1, string2): result = True for c1, c2 in izip(string1, string2): result &= c1 == c2 + return result def remove_port(uri): """Remove the port number from a URI - :param uri: full URI that Twilio requested on your server + :param uri: parsed URI that Twilio requested on your server :returns: full URI without a port number :rtype: str """ + if not uri.port: + return uri.geturl() + new_netloc = uri.netloc.split(':')[0] new_uri = uri._replace(netloc=new_netloc) + + return new_uri.geturl() + + +def add_port(uri): + """Add the port number to a URI + + :param uri: parsed URI that Twilio requested on your server + + :returns: full URI with a port number + :rtype: str + """ + if uri.port: + return uri.geturl() + + port = 443 if uri.scheme == "https" else 80 + new_netloc = uri.netloc + ":" + str(port) + new_uri = uri._replace(netloc=new_netloc) + return new_uri.geturl() @@ -82,17 +105,21 @@ class RequestValidator(object): params = {} parsed_uri = urlparse(uri) - if parsed_uri.scheme == "https" and parsed_uri.port: - uri = remove_port(parsed_uri) + uri_with_port = add_port(parsed_uri) + uri_without_port = remove_port(parsed_uri) valid_signature = False # Default fail + valid_signature_with_port = False valid_body_hash = True # May not receive body hash, so default succeed query = parse_qs(parsed_uri.query) if "bodySHA256" in query and isinstance(params, string_types): valid_body_hash = compare(self.compute_hash(params), query["bodySHA256"][0]) - valid_signature = compare(self.compute_signature(uri, {}), signature) - else: - valid_signature = compare(self.compute_signature(uri, params), signature) + params = {} + + # check signature of uri with and without port, + # since sig generation on back end is inconsistent + valid_signature = compare(self.compute_signature(uri_without_port, params), signature) + valid_signature_with_port = compare(self.compute_signature(uri_with_port, params), signature) - return valid_signature and valid_body_hash + return valid_body_hash and (valid_signature or valid_signature_with_port)
twilio/twilio-python
77b44a5a18395bf09ae114d24ac9c4b3efb67e78
diff --git a/tests/unit/test_request_validator.py b/tests/unit/test_request_validator.py index c7f67d818..245c5ae43 100644 --- a/tests/unit/test_request_validator.py +++ b/tests/unit/test_request_validator.py @@ -53,6 +53,20 @@ class ValidationTest(unittest.TestCase): uri = self.uri.replace(".com", ".com:1234") assert_true(self.validator.validate(uri, self.params, self.expected)) + def test_validation_removes_port_on_http(self): + expected = "Zmvh+3yNM1Phv2jhDCwEM3q5ebU=" # hash of http uri with port 1234 + uri = self.uri.replace(".com", ".com:1234").replace("https", "http") + assert_true(self.validator.validate(uri, self.params, expected)) + + def test_validation_adds_port_on_https(self): + expected = "kvajT1Ptam85bY51eRf/AJRuM3w=" # hash of uri with port 443 + assert_true(self.validator.validate(self.uri, self.params, expected)) + + def test_validation_adds_port_on_http(self): + uri = self.uri.replace("https", "http") + expected = "0ZXoZLH/DfblKGATFgpif+LLRf4=" # hash of uri with port 80 + assert_true(self.validator.validate(uri, self.params, expected)) + def test_validation_of_body_succeeds(self): uri = self.uriWithBody is_valid = self.validator.validate(uri, self.body, "a9nBmqA0ju/hNViExpshrM61xv4=")
Incoming SMS webhook failing validation (non standard SSL port) Hi, I have an incoming SMS webhook using HTTPS but on a non standard port (4433). The incoming POST fails validation unless the changes made in #392 are reverted (i.e. the port number left in for validation). The [security notes](https://www.twilio.com/docs/api/security#notes) don't mention non standard ports. Should only the standard port be removed if using HTTPS? https://github.com/twilio/twilio-python/blob/119fe50863b2e9df89a56711e8d3410288709593/twilio/request_validator.py#L77
0.0
77b44a5a18395bf09ae114d24ac9c4b3efb67e78
[ "tests/unit/test_request_validator.py::ValidationTest::test_validation_adds_port_on_http", "tests/unit/test_request_validator.py::ValidationTest::test_validation_adds_port_on_https" ]
[ "tests/unit/test_request_validator.py::ValidationTest::test_compute_hash_unicode", "tests/unit/test_request_validator.py::ValidationTest::test_compute_signature", "tests/unit/test_request_validator.py::ValidationTest::test_compute_signature_bytecode", "tests/unit/test_request_validator.py::ValidationTest::test_validation", "tests/unit/test_request_validator.py::ValidationTest::test_validation_of_body_succeeds", "tests/unit/test_request_validator.py::ValidationTest::test_validation_removes_port_on_http", "tests/unit/test_request_validator.py::ValidationTest::test_validation_removes_port_on_https" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2019-09-20 17:49:59+00:00
mit
6,105
twisted__ldaptor-106
diff --git a/docs/source/NEWS.rst b/docs/source/NEWS.rst index 5744869..5a25d34 100644 --- a/docs/source/NEWS.rst +++ b/docs/source/NEWS.rst @@ -32,6 +32,7 @@ Bugfixes ^^^^^^^^ - DN matching is now case insensitive. +- Proxies now terminate the connection to the proxied server in case a client immediately closes the connection. Release 16.0 (2016-06-07) diff --git a/ldaptor/protocols/ldap/proxybase.py b/ldaptor/protocols/ldap/proxybase.py index ac5fe23..908481a 100755 --- a/ldaptor/protocols/ldap/proxybase.py +++ b/ldaptor/protocols/ldap/proxybase.py @@ -62,7 +62,13 @@ class ProxyBase(ldapserver.BaseLDAPServer): return d else: self.client = proto - self._processBacklog() + if not self.connected: + # Client no longer connected, proxy shouldn't be either + self.client.transport.loseConnection() + self.client = None + self.queuedRequests = [] + else: + self._processBacklog() def _establishedTLS(self, proto): """
twisted/ldaptor
7a51037ccf3ebe387766a3a91cf9ae79a3a3393d
diff --git a/ldaptor/test/test_proxybase.py b/ldaptor/test/test_proxybase.py index 34420eb..7667252 100644 --- a/ldaptor/test/test_proxybase.py +++ b/ldaptor/test/test_proxybase.py @@ -247,3 +247,23 @@ class ProxyBase(unittest.TestCase): self.assertEqual( server.transport.value(), str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=52), id=4))) + + def test_health_check_closes_connection_to_proxied_server(self): + """ + When the client disconnects immediately and before the connection to the proxied server has + been established, the proxy terminates the connection to the proxied server. + Messages sent by the client are discarded. + """ + request = pureldap.LDAPBindRequest() + message = pureldap.LDAPMessage(request, id=4) + server = self.createServer() + # Send a message, message is queued + server.dataReceived(str(message)) + self.assertEqual(len(server.queuedRequests), 1) + self.assertEqual(server.queuedRequests[0][0], request) + # Lose connection, message is discarded + server.connectionLost(error.ConnectionDone) + server.reactor.advance(1) + self.assertIsNone(server.client) + self.assertFalse(server.clientTestDriver.connected) + self.assertEqual(server.queuedRequests, []) \ No newline at end of file
Proxy may keep connection to proxied server open if client disconnects immediately Hello! We're developing an LDAP proxy application based on ldaptor which has worked pretty well so far, so thanks for the great library! We recently stumbled upon a small bug which can be reproduced as follows: * Use the current ldaptor master (7a51037ccf3ebe387766a3a91cf9ae79a3a3393d) * Run the exemplary logging proxy code from [the docs](https://ldaptor.readthedocs.io/en/latest/cookbook/ldap-proxy.html), proxying any LDAP server (AD at ``10.0.1.161:7389`` in our case) * Use netcat to perform a simple "health check": ``netcat -z localhost 10389``. The ``-z`` flag is [described](https://www.irongeek.com/i.php?page=backtrack-3-man/netcat) as follows: _In connect mode it means that as soon as the port is open it is immediately shutdown and closed._ * Even though netcat has disconnected, ``netstat -nto`` reports a connection from the LDAP proxy to the proxied server in the ESTABLISHED state: ``` tcp 0 0 10.1.0.4:60478 10.0.1.161:7389 ESTABLISHED off (0.00/0/0) ``` This socket is only closed when the LDAP proxy is shut down. This is unfortunate because some appliances may perform periodical "health checks" against the LDAP proxy, similar to the netcat call above ([see here](https://community.privacyidea.org/t/too-many-established-tcp-connections-from-the-ldap-proxy/718)). If every such health check persists one connection to the proxied server, the LDAP proxy will eventually run out of open files. I believe this is due to a race condition: * When netcat connects to the proxy, ``connectionMade`` is called, which initiates a connection to the proxied server. It uses a deferred to invoke ``_connectedToProxiedServer`` once the connection has been established: https://github.com/twisted/ldaptor/blob/7a51037ccf3ebe387766a3a91cf9ae79a3a3393d/ldaptor/protocols/ldap/proxybase.py#L40 * netcat closes the connection to the proxy, so ``connectionLost`` is called. However, as netcat does so *immediately*, the above deferred's callback has not been called yet, so ``self.client`` is still None. * After that, ``_connectedToProxiedServer`` is finally called. Because of that, the connection to the proxied server is never closed. I'll come up with a small PR to fix this, though it may not be the optimal solution as I'm not that familiar with the ldaptor codebase :)
0.0
7a51037ccf3ebe387766a3a91cf9ae79a3a3393d
[ "ldaptor/test/test_proxybase.py::ProxyBase::test_health_check_closes_connection_to_proxied_server" ]
[ "ldaptor/test/test_proxybase.py::ProxyBase::test_cannot_connect_to_proxied_server_no_pending_requests" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-06-18 16:25:48+00:00
mit
6,106
twisted__pydoctor-191
diff --git a/pydoctor/astbuilder.py b/pydoctor/astbuilder.py index bb60cc65..cb724835 100644 --- a/pydoctor/astbuilder.py +++ b/pydoctor/astbuilder.py @@ -312,6 +312,41 @@ class ModuleVistor(ast.NodeVisitor): if not self._handleAliasing(target, expr): self._handleClassVar(target, annotation, lineno) + def _handleDocstringUpdate(self, targetNode, expr, lineno): + def warn(msg): + self.system.msg('ast', "%s:%d: %s" % ( + getattr(self.builder.currentMod, 'filepath', '<unknown>'), + lineno, msg)) + + # Figure out target object. + full_name = node2fullname(targetNode, self.builder.current) + if full_name is None: + warn("Unable to figure out target for __doc__ assignment") + # Don't return yet: we might have to warn about the value too. + obj = None + else: + obj = self.system.objForFullName(full_name) + if obj is None: + warn("Unable to figure out target for __doc__ assignment: " + "computed full name not found: " + full_name) + + # Determine docstring value. + try: + docstring = ast.literal_eval(expr) + except ValueError: + warn("Unable to figure out value for __doc__ assignment, " + "maybe too complex") + return + if not isinstance(docstring, string_types): + warn("Ignoring value assigned to __doc__: not a string") + return + + if obj is not None: + obj.docstring = docstring + # TODO: It might be better to not perform docstring parsing until + # we have the final docstrings for all objects. + obj.parsed_docstring = None + def _handleAssignment(self, targetNode, annotation, expr, lineno): if isinstance(targetNode, ast.Name): target = targetNode.id @@ -323,7 +358,9 @@ class ModuleVistor(ast.NodeVisitor): self._handleAssignmentInClass(target, annotation, expr, lineno) elif isinstance(targetNode, ast.Attribute): value = targetNode.value - if isinstance(value, ast.Name) and value.id == 'self': + if targetNode.attr == '__doc__': + self._handleDocstringUpdate(value, expr, lineno) + elif isinstance(value, ast.Name) and value.id == 'self': self._handleInstanceVar(targetNode.attr, annotation, lineno) def visit_Assign(self, node):
twisted/pydoctor
f26e7be043bab85d47116289c280d49b371451ac
diff --git a/pydoctor/test/test_astbuilder.py b/pydoctor/test/test_astbuilder.py index ce99e9f4..dca78a4f 100644 --- a/pydoctor/test/test_astbuilder.py +++ b/pydoctor/test/test_astbuilder.py @@ -536,6 +536,57 @@ def test_inline_docstring_annotated_instancevar(): b = C.contents['b'] assert b.docstring == """inline doc for b""" +def test_docstring_assignment(capsys): + mod = fromText(''' + def fun(): + pass + + class CLS: + + def method1(): + """Temp docstring.""" + pass + + def method2(): + pass + + method1.__doc__ = "Updated docstring #1" + + fun.__doc__ = "Happy Happy Joy Joy" + CLS.__doc__ = "Clears the screen" + CLS.method2.__doc__ = "Updated docstring #2" + + None.__doc__ = "Free lunch!" + real.__doc__ = "Second breakfast" + fun.__doc__ = codecs.encode('Pnrfne fnynq', 'rot13') + CLS.method1.__doc__ = 4 + ''') + fun = mod.contents['fun'] + assert fun.kind == 'Function' + assert fun.docstring == """Happy Happy Joy Joy""" + CLS = mod.contents['CLS'] + assert CLS.kind == 'Class' + assert CLS.docstring == """Clears the screen""" + method1 = CLS.contents['method1'] + assert method1.kind == 'Method' + assert method1.docstring == "Updated docstring #1" + method2 = CLS.contents['method2'] + assert method2.kind == 'Method' + assert method2.docstring == "Updated docstring #2" + captured = capsys.readouterr() + lines = captured.out.split('\n') + assert len(lines) > 0 and lines[0] == \ + "<unknown>:20: Unable to figure out target for __doc__ assignment" + assert len(lines) > 1 and lines[1] == \ + "<unknown>:21: Unable to figure out target for __doc__ assignment: " \ + "computed full name not found: real" + assert len(lines) > 2 and lines[2] == \ + "<unknown>:22: Unable to figure out value for __doc__ assignment, " \ + "maybe too complex" + assert len(lines) > 3 and lines[3] == \ + "<unknown>:23: Ignoring value assigned to __doc__: not a string" + assert len(lines) == 5 and lines[-1] == '' + def test_variable_scopes(): mod = fromText(''' l = 1
Detect and use docstrings set after-the-fact. Twisted has some code that does something like ``` python if _PY3: def func(args): pass else: def func(args): pass func.__doc__ = """ func does some stuff. ``` to avoid duplicating a docstring. Unfortunately, pydoctor doesn't pick this up, so it appears that `func` is undocumented.
0.0
f26e7be043bab85d47116289c280d49b371451ac
[ "pydoctor/test/test_astbuilder.py::test_docstring_assignment" ]
[ "pydoctor/test/test_astbuilder.py::test_no_docstring", "pydoctor/test/test_astbuilder.py::test_simple", "pydoctor/test/test_astbuilder.py::test_function_argspec", "pydoctor/test/test_astbuilder.py::test_class", "pydoctor/test/test_astbuilder.py::test_class_with_base", "pydoctor/test/test_astbuilder.py::test_follow_renaming", "pydoctor/test/test_astbuilder.py::test_class_with_base_from_module", "pydoctor/test/test_astbuilder.py::test_aliasing", "pydoctor/test/test_astbuilder.py::test_more_aliasing", "pydoctor/test/test_astbuilder.py::test_aliasing_recursion", "pydoctor/test/test_astbuilder.py::test_documented_no_alias", "pydoctor/test/test_astbuilder.py::test_subclasses", "pydoctor/test/test_astbuilder.py::test_inherit_names", "pydoctor/test/test_astbuilder.py::test_nested_class_inheriting_from_same_module", "pydoctor/test/test_astbuilder.py::test_all_recognition", "pydoctor/test/test_astbuilder.py::test_all_in_class_non_recognition", "pydoctor/test/test_astbuilder.py::test_classmethod", "pydoctor/test/test_astbuilder.py::test_classdecorator", "pydoctor/test/test_astbuilder.py::test_classdecorator_with_args", "pydoctor/test/test_astbuilder.py::test_import_star", "pydoctor/test/test_astbuilder.py::test_inline_docstring_modulevar", "pydoctor/test/test_astbuilder.py::test_inline_docstring_classvar", "pydoctor/test/test_astbuilder.py::test_inline_docstring_annotated_classvar", "pydoctor/test/test_astbuilder.py::test_inline_docstring_instancevar", "pydoctor/test/test_astbuilder.py::test_inline_docstring_annotated_instancevar", "pydoctor/test/test_astbuilder.py::test_variable_scopes", "pydoctor/test/test_astbuilder.py::test_variable_types", "pydoctor/test/test_astbuilder.py::test_annotated_variables", "pydoctor/test/test_astbuilder.py::test_inferred_variable_types", "pydoctor/test/test_astbuilder.py::test_type_from_attrib", "pydoctor/test/test_astbuilder.py::test_detupling_assignment" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-03-06 00:15:07+00:00
bsd-2-clause
6,107
twisted__pydoctor-491
diff --git a/docs/source/docformat/list-restructuredtext-support.rst b/docs/source/docformat/list-restructuredtext-support.rst index 1aea3679..c4d184d6 100644 --- a/docs/source/docformat/list-restructuredtext-support.rst +++ b/docs/source/docformat/list-restructuredtext-support.rst @@ -60,7 +60,7 @@ List of ReST directives * - ``.. code::`` - `docutils <https://docutils.sourceforge.io/docs/ref/rst/directives.html#code>`__ - - Yes + - Yes (No options supported) * - ``.. python::`` - pydoctor @@ -144,7 +144,7 @@ List of ReST directives * - ``.. code-block::`` - `Sphinx <https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block>`__ - - No + - Yes (No options supported) * - ``.. literalinclude::`` - `Sphinx <https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude>`__ diff --git a/docs/source/docformat/restructuredtext.rst b/docs/source/docformat/restructuredtext.rst index ee5fb63f..7baf4d9f 100644 --- a/docs/source/docformat/restructuredtext.rst +++ b/docs/source/docformat/restructuredtext.rst @@ -88,10 +88,10 @@ Here is a list of the supported ReST directives by package of origin: - `docutils`: ``.. include::``, ``.. contents::``, ``.. image::``, ``.. figure::``, ``.. unicode::``, ``.. raw::``, ``.. math::``, - ``.. role::``, ``.. table::``, ``.. warning::``, ``.. note::`` + ``.. role::``, ``.. table::``, ``.. code::``, ``.. warning::``, ``.. note::`` and other admonitions, and a few others. -- `epydoc`: None -- `Sphinx`: ``.. deprecated::``, ``.. versionchanged::``, ``.. versionadded::`` +- `epydoc`: None yet. +- `Sphinx`: ``.. deprecated::``, ``.. versionchanged::``, ``.. versionadded::``, ``.. code-block::`` - `pydoctor`: ``.. python::`` `Full list of supported and unsupported directives <list-restructuredtext-support.html>`_ @@ -102,8 +102,12 @@ Colorized snippets directive Using reStructuredText markup it is possible to specify Python snippets in a `doctest block <https://docutils.sourceforge.io/docs/user/rst/quickref.html#doctest-blocks>`_. + If the Python prompt gets in your way when you try to copy and paste and you are not interested -in self-testing docstrings, the python directive will let you obtain a simple block of colorized text:: +in self-testing docstrings, the python directive will let you obtain a simple block of colorized text. +Directives ``.. code::`` and ``.. code-block::`` acts exactly the same. + +:: .. python:: diff --git a/pydoctor/epydoc/markup/restructuredtext.py b/pydoctor/epydoc/markup/restructuredtext.py index edb640fa..a189bec4 100644 --- a/pydoctor/epydoc/markup/restructuredtext.py +++ b/pydoctor/epydoc/markup/restructuredtext.py @@ -482,13 +482,35 @@ class PythonCodeDirective(Directive): """ has_content = True - + def run(self) -> List[nodes.Node]: text = '\n'.join(self.content) node = nodes.doctest_block(text, text, codeblock=True) return [ node ] +class DocutilsAndSphinxCodeBlockAdapter(PythonCodeDirective): + # Docutils and Sphinx code blocks have both one optional argument, + # so we accept it here as well but do nothing with it. + required_arguments = 0 + optional_arguments = 1 + + # Listing all options that docutils.parsers.rst.directives.body.CodeBlock provides + # And also sphinx.directives.code.CodeBlock. We don't care about their values, + # we just don't want to see them in self.content. + option_spec = {'class': directives.class_option, + 'name': directives.unchanged, + 'number-lines': directives.unchanged, # integer or None + 'force': directives.flag, + 'linenos': directives.flag, + 'dedent': directives.unchanged, # integer or None + 'lineno-start': int, + 'emphasize-lines': directives.unchanged_required, + 'caption': directives.unchanged_required, + } + directives.register_directive('python', PythonCodeDirective) +directives.register_directive('code', DocutilsAndSphinxCodeBlockAdapter) +directives.register_directive('code-block', DocutilsAndSphinxCodeBlockAdapter) directives.register_directive('versionadded', VersionChange) directives.register_directive('versionchanged', VersionChange) directives.register_directive('deprecated', VersionChange)
twisted/pydoctor
018971f1deda1af77bf6b07bc445c41c5c95cef2
diff --git a/pydoctor/test/epydoc/restructuredtext.doctest b/pydoctor/test/epydoc/restructuredtext.doctest index 9438f8c7..a9aee4e3 100644 --- a/pydoctor/test/epydoc/restructuredtext.doctest +++ b/pydoctor/test/epydoc/restructuredtext.doctest @@ -104,3 +104,30 @@ as colorized Python code. <span class="py-keyword">class</span> <span class="py-defname">Foo</span>: <span class="py-keyword">def</span> <span class="py-defname">__init__</span>(self): <span class="py-keyword">pass</span></pre> +>>> p = restructuredtext.parse_docstring( +... """The directives options are ignored and do not show up in the HTML. +... +... .. code:: python +... :number-lines: +... :linenos: +... +... # This is some Python code +... def foo(): +... pass +... +... class Foo: +... def __init__(self): +... pass +... """, err) +>>> err +[] +>>> print(flatten(p.to_stan(None))) +<p>The directives options are ignored and do not show up in the HTML.</p> +<pre class="py-doctest"> +<span class="py-comment"># This is some Python code</span> +<span class="py-keyword">def</span> <span class="py-defname">foo</span>(): + <span class="py-keyword">pass</span> +<BLANKLINE> +<span class="py-keyword">class</span> <span class="py-defname">Foo</span>: + <span class="py-keyword">def</span> <span class="py-defname">__init__</span>(self): + <span class="py-keyword">pass</span></pre> \ No newline at end of file
Colorize code inside ``..code ::`` directives The code currently only displayed as a literal block, but no syntax highlight is applied. I think we could re-use the doctest syntaxt highlight and apply it to the ``..code ::`` directive, too.
0.0
018971f1deda1af77bf6b07bc445c41c5c95cef2
[ "pydoctor/test/epydoc/restructuredtext.doctest::restructuredtext.doctest" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-11 18:32:57+00:00
apache-2.0
6,108
twisted__pydoctor-502
diff --git a/.github/workflows/system.yaml b/.github/workflows/system.yaml index f98c369d..f30105c6 100644 --- a/.github/workflows/system.yaml +++ b/.github/workflows/system.yaml @@ -12,7 +12,11 @@ jobs: strategy: matrix: - tox_target: [twisted-apidoc, cpython-summary, python-igraph-apidocs, cpython-apidocs] + tox_target: [twisted-apidoc, + cpython-summary, + python-igraph-apidocs, + cpython-apidocs, + numpy-apidocs,] steps: - uses: actions/checkout@v2 diff --git a/README.rst b/README.rst index 6c62894b..bfb1de3e 100644 --- a/README.rst +++ b/README.rst @@ -71,7 +71,11 @@ What's New? ~~~~~~~~~~~ in development -^^^^^^^^^^^^^^ +^^^^^^^^^^^^^^ + +pydoctor 22.2.1 +^^^^^^^^^^^^^^^ +* Fix crash of pydoctor when processing a reparented module. pydoctor 22.2.0 ^^^^^^^^^^^^^^^ diff --git a/pydoctor/model.py b/pydoctor/model.py index 2e7ceaa9..f6423992 100644 --- a/pydoctor/model.py +++ b/pydoctor/model.py @@ -626,7 +626,11 @@ class System: self.verboselevel = 0 self.needsnl = False self.once_msgs: Set[Tuple[str, str]] = set() - self.unprocessed_modules: Dict[str, _ModuleT] = OrderedDict() + + # We're using the id() of the modules as key, and not the fullName becaue modules can + # be reparented, generating KeyError. + self.unprocessed_modules: Dict[int, _ModuleT] = OrderedDict() + self.module_count = 0 self.processing_modules: List[str] = [] self.buildtime = datetime.datetime.now() @@ -826,10 +830,13 @@ class System: module to the system. """ assert mod.state is ProcessingState.UNPROCESSED - first = self.unprocessed_modules.setdefault(mod.fullName(), mod) - if mod is not first: + first = self.allobjects.get(mod.fullName()) + if first is not None: + # At this step of processing only modules exists + assert isinstance(first, Module) self._handleDuplicateModule(first, mod) else: + self.unprocessed_modules[id(mod)] = mod self.addObject(mod) self.progress( "analyzeModule", len(self.allobjects), @@ -855,7 +862,7 @@ class System: return else: # Else, the last added module wins - del self.unprocessed_modules[dup.fullName()] + del self.unprocessed_modules[id(dup)] self._addUnprocessedModule(dup) def _introspectThing(self, thing: object, parent: Documentable, parentMod: _ModuleT) -> None: @@ -1010,7 +1017,7 @@ class System: mod.state = ProcessingState.PROCESSED head = self.processing_modules.pop() assert head == mod.fullName() - del self.unprocessed_modules[mod.fullName()] + del self.unprocessed_modules[id(mod)] self.progress( 'process', self.module_count - len(self.unprocessed_modules), diff --git a/setup.cfg b/setup.cfg index d3237ed1..796b8a0c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = pydoctor -version = 22.2.0.dev0 +version = 22.2.1.dev0 author = Michael Hudson-Doyle author_email = [email protected] maintainer = Maarten ter Huurne diff --git a/tox.ini b/tox.ini index 56e3cab5..0f388a6c 100644 --- a/tox.ini +++ b/tox.ini @@ -82,6 +82,23 @@ commands = {toxworkdir}/cpython/Lib pytest -v docs/tests/test_standard_library_docs.py +[testenv:numpy-apidocs] +description = Build numpy API documentation. For now we don't check for any warnings or other errors. The only purpose of this test is to make sure pydoctor doesn't crash. +deps = + pytest +commands = + sh -c "if [ ! -d {toxworkdir}/numpy ]; then \ + git clone --depth 1 https://github.com/numpy/numpy.git {toxworkdir}/numpy; \ + fi" + sh -c "cd {toxworkdir}/numpy && git pull" + rm -rf {toxworkdir}/numpy-output + python3 -c "from pydoctor.driver import main; \ + code = main(['--html-summary-pages', '--quiet', \ + '--html-output={toxworkdir}/numpy-output', \ + '{toxworkdir}/numpy/numpy']); \ + # Code 2 error means bad docstrings, which is OK for this test. + assert code==2, 'pydoctor exited with code %s, expected code 2.'%code" + # Requires cmake [testenv:python-igraph-apidocs] description = Build python-igraph API documentation @@ -134,7 +151,9 @@ deps = sphinx>=3.4.0 git+https://github.com/twisted/twisted.git types-requests - types-docutils + # FIXME: https://github.com/twisted/pydoctor/issues/504 + # This is pinned for now as newer versions are breaking our static checks. + types-docutils==0.17.5 commands = mypy \
twisted/pydoctor
bfafbd720604de4fd5ced3f659b311db0c47d86c
diff --git a/pydoctor/test/test_packages.py b/pydoctor/test/test_packages.py index 9d2a3aa6..125fb396 100644 --- a/pydoctor/test/test_packages.py +++ b/pydoctor/test/test_packages.py @@ -89,4 +89,24 @@ def test_package_module_name_clash() -> None: """ system = processPackage('package_module_name_clash') pack = system.allobjects['package_module_name_clash.pack'] - assert 'package' == pack.contents.popitem()[0] \ No newline at end of file + assert 'package' == pack.contents.popitem()[0] + +def test_reparented_module() -> None: + """ + A module that is imported in a package as a different name and exported + in that package under the new name via C{__all__} is presented using the + new name. + """ + system = processPackage('reparented_module') + + mod = system.allobjects['reparented_module.module'] + top = system.allobjects['reparented_module'] + + assert mod.fullName() == 'reparented_module.module' + assert top.resolveName('module') is top.contents['module'] + assert top.resolveName('module.f') is mod.contents['f'] + + # The module old name is not in allobjects + assert 'reparented_module.mod' not in system.allobjects + # But can still be resolved with it's old name + assert top.resolveName('mod') is top.contents['module'] \ No newline at end of file diff --git a/pydoctor/test/testpackages/reparented_module/__init__.py b/pydoctor/test/testpackages/reparented_module/__init__.py new file mode 100644 index 00000000..a7c376d0 --- /dev/null +++ b/pydoctor/test/testpackages/reparented_module/__init__.py @@ -0,0 +1,6 @@ +""" +Here the module C{mod} is made available under an alias name +that is explicitly advertised under the alias name. +""" +from . import mod as module +__all__=('module',) diff --git a/pydoctor/test/testpackages/reparented_module/mod.py b/pydoctor/test/testpackages/reparented_module/mod.py new file mode 100644 index 00000000..ef076130 --- /dev/null +++ b/pydoctor/test/testpackages/reparented_module/mod.py @@ -0,0 +1,5 @@ +""" +This is the "origin" module which for testing purpose is used from the C{reparented_module} package. +""" +def f(): + pass
Crash when building numpy docs Pydoctor crashes when building numpy docs. This must be a regression introduced by #488 :/ I'll work on a fix and release a bugfix version of pydoctor, as well as a system test for numpy docs ``` File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/pydoctor/driver.py", line 431, in main system.process() File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/pydoctor/model.py", line 1024, in process self.processModule(mod) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/pydoctor/model.py", line 1013, in processModule del self.unprocessed_modules[mod.fullName()] KeyError: 'numpy.core.char' ```
0.0
bfafbd720604de4fd5ced3f659b311db0c47d86c
[ "pydoctor/test/test_packages.py::test_reparented_module" ]
[ "pydoctor/test/test_packages.py::test_relative_import", "pydoctor/test/test_packages.py::test_package_docstring", "pydoctor/test/test_packages.py::test_modnamedafterbuiltin", "pydoctor/test/test_packages.py::test_nestedconfusion", "pydoctor/test/test_packages.py::test_importingfrompackage", "pydoctor/test/test_packages.py::test_allgames", "pydoctor/test/test_packages.py::test_cyclic_imports", "pydoctor/test/test_packages.py::test_package_module_name_clash" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-23 01:44:44+00:00
bsd-2-clause
6,109
twisted__pydoctor-515
diff --git a/README.rst b/README.rst index b707e46d..bdbe5848 100644 --- a/README.rst +++ b/README.rst @@ -75,6 +75,7 @@ in development * Add client side search system based on lunr.js. * Fix broken links in docstring summaries. * Add cache for the xref linker, reduces the number of identical warnings. +* Fix crash when reparenting objects with duplicate names. pydoctor 22.2.2 ^^^^^^^^^^^^^^^ diff --git a/pydoctor/astbuilder.py b/pydoctor/astbuilder.py index 5242f4cb..594fc2f6 100644 --- a/pydoctor/astbuilder.py +++ b/pydoctor/astbuilder.py @@ -397,7 +397,9 @@ class ModuleVistor(ast.NodeVisitor): # Move re-exported objects into current module. if asname in exports and mod is not None: - ob = mod.resolveName(orgname) + # In case of duplicates names, we can't rely on resolveName, + # So we use content.get first to resolve non-alias names. + ob = mod.contents.get(orgname) or mod.resolveName(orgname) if ob is None: self.builder.warning("cannot resolve re-exported name", f'{modname}.{orgname}') diff --git a/pydoctor/model.py b/pydoctor/model.py index b92c2f53..018f7dce 100644 --- a/pydoctor/model.py +++ b/pydoctor/model.py @@ -251,7 +251,7 @@ class Documentable: # :/ self._handle_reparenting_pre() old_parent = self.parent - assert isinstance(old_parent, Module) + assert isinstance(old_parent, CanContainImportsDocumentable) old_name = self.name self.parent = self.parentMod = new_parent self.name = new_name
twisted/pydoctor
76d3b86424a9275046b7aa843179856bd5e46dcc
diff --git a/pydoctor/test/test_packages.py b/pydoctor/test/test_packages.py index 25f6e967..1051c294 100644 --- a/pydoctor/test/test_packages.py +++ b/pydoctor/test/test_packages.py @@ -1,5 +1,6 @@ from pathlib import Path from typing import Type +import pytest from pydoctor import model @@ -154,3 +155,14 @@ def test_reparenting_follows_aliases() -> None: return else: raise AssertionError("Congratulation!") + [email protected]('modname', ['reparenting_crash','reparenting_crash_alt']) +def test_reparenting_crash(modname: str) -> None: + """ + Test for https://github.com/twisted/pydoctor/issues/513 + """ + system = processPackage(modname) + mod = system.allobjects[modname] + assert isinstance(mod.contents[modname], model.Class) + assert isinstance(mod.contents['reparented_func'], model.Function) + assert isinstance(mod.contents[modname].contents['reparented_func'], model.Function) diff --git a/pydoctor/test/testpackages/reparenting_crash/__init__.py b/pydoctor/test/testpackages/reparenting_crash/__init__.py new file mode 100644 index 00000000..d7b9a5bb --- /dev/null +++ b/pydoctor/test/testpackages/reparenting_crash/__init__.py @@ -0,0 +1,3 @@ +from .reparenting_crash import reparenting_crash, reparented_func + +__all__ = ['reparenting_crash', 'reparented_func'] \ No newline at end of file diff --git a/pydoctor/test/testpackages/reparenting_crash/reparenting_crash.py b/pydoctor/test/testpackages/reparenting_crash/reparenting_crash.py new file mode 100644 index 00000000..e5de4bb0 --- /dev/null +++ b/pydoctor/test/testpackages/reparenting_crash/reparenting_crash.py @@ -0,0 +1,8 @@ + +class reparenting_crash: + ... + def reparented_func(): + ... + +def reparented_func(): + ... \ No newline at end of file diff --git a/pydoctor/test/testpackages/reparenting_crash_alt/__init__.py b/pydoctor/test/testpackages/reparenting_crash_alt/__init__.py new file mode 100644 index 00000000..9397062c --- /dev/null +++ b/pydoctor/test/testpackages/reparenting_crash_alt/__init__.py @@ -0,0 +1,3 @@ +from .reparenting_crash_alt import reparenting_crash_alt, reparented_func + +__all__ = ['reparenting_crash_alt', 'reparented_func'] diff --git a/pydoctor/test/testpackages/reparenting_crash_alt/_impl.py b/pydoctor/test/testpackages/reparenting_crash_alt/_impl.py new file mode 100644 index 00000000..fb0a6552 --- /dev/null +++ b/pydoctor/test/testpackages/reparenting_crash_alt/_impl.py @@ -0,0 +1,6 @@ +class reparenting_crash_alt: + ... + def reparented_func(): + ... +def reparented_func(): + ... diff --git a/pydoctor/test/testpackages/reparenting_crash_alt/reparenting_crash_alt.py b/pydoctor/test/testpackages/reparenting_crash_alt/reparenting_crash_alt.py new file mode 100644 index 00000000..119fd4ee --- /dev/null +++ b/pydoctor/test/testpackages/reparenting_crash_alt/reparenting_crash_alt.py @@ -0,0 +1,2 @@ + +from ._impl import reparenting_crash_alt, reparented_func
Regression after 22.2.2 - reparenting confusion crash When reparenting a class to a module of the same name, then, the next reparent might to move the object to the class instead of moving it to the module. Leading to AssertionError. Looks like it's a bug introduced by a combinaison trying to comply with mypy in [this commit](https://github.com/twisted/pydoctor/commit/2a0f98e272842ce1c4a78adbba086ef804ef80be) and me changing `ob.contents.get` by `ob.resoveName` to fix #505 ```python # We should not read: assert isinstance(old_parent, Module) # But actually: assert isinstance(old_parent, CanContainImportsDocumentable) ``` ```python moving 'Wappalyzer.Wappalyzer.WebPage' into 'Wappalyzer' moving 'Wappalyzer.Wappalyzer.Wappalyzer' into 'Wappalyzer' moving 'Wappalyzer.Wappalyzer.analyze' into 'Wappalyzer' Traceback (most recent call last): File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/bin/pydoctor", line 8, in <module> sys.exit(main()) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/driver.py", line 431, in main system.process() File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/model.py", line 1031, in process self.processModule(mod) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/model.py", line 1016, in processModule builder.processModuleAST(ast, mod) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/astbuilder.py", line 1[18](https://github.com/chorsley/python-Wappalyzer/runs/5469341311?check_suite_focus=true#step:5:18)2, in processModuleAST self.ModuleVistor(self, mod).visit(mod_ast) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/ast.py", line 371, in visit return visitor(node) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/astbuilder.py", line 239, in visit_Module self.default(node) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/astbuilder.py", line 2[19](https://github.com/chorsley/python-Wappalyzer/runs/5469341311?check_suite_focus=true#step:5:19), in default self.visit(child) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/ast.py", line 371, in visit return visitor(node) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/astbuilder.py", line 343, in visit_ImportFrom self._importNames(modname, node.names) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/astbuilder.py", line 412, in _importNames ob.reparent(current, asname) File "/home/runner/work/python-Wappalyzer/python-Wappalyzer/.tox/docs/lib/python3.8/site-packages/pydoctor/model.py", line [25](https://github.com/chorsley/python-Wappalyzer/runs/5469341311?check_suite_focus=true#step:5:25)2, in reparent assert isinstance(old_parent, Module) AssertionError ``` I'll add a system test with `python-Wappalyzer`.
0.0
76d3b86424a9275046b7aa843179856bd5e46dcc
[ "pydoctor/test/test_packages.py::test_reparenting_crash[reparenting_crash]" ]
[ "pydoctor/test/test_packages.py::test_relative_import", "pydoctor/test/test_packages.py::test_package_docstring", "pydoctor/test/test_packages.py::test_modnamedafterbuiltin", "pydoctor/test/test_packages.py::test_nestedconfusion", "pydoctor/test/test_packages.py::test_importingfrompackage", "pydoctor/test/test_packages.py::test_allgames", "pydoctor/test/test_packages.py::test_cyclic_imports", "pydoctor/test/test_packages.py::test_package_module_name_clash", "pydoctor/test/test_packages.py::test_reparented_module", "pydoctor/test/test_packages.py::test_reparenting_follows_aliases", "pydoctor/test/test_packages.py::test_reparenting_crash[reparenting_crash_alt]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-03-09 23:02:52+00:00
bsd-2-clause
6,110
twisted__towncrier-453
diff --git a/docs/cli.rst b/docs/cli.rst index bf3665f..b32db63 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -50,6 +50,10 @@ Build the combined news file from news fragments. Do not ask for confirmations. Useful for automated tasks. +.. option:: --keep + + Don't delete news fragments after the build and don't ask for confirmation whether to delete or keep the fragments. + ``towncrier create`` -------------------- diff --git a/src/towncrier/_git.py b/src/towncrier/_git.py index c436087..a0f9aee 100644 --- a/src/towncrier/_git.py +++ b/src/towncrier/_git.py @@ -7,22 +7,9 @@ import os from subprocess import STDOUT, call, check_output -import click - -def remove_files(fragment_filenames: list[str], answer_yes: bool) -> None: - if not fragment_filenames: - return - - if answer_yes: - click.echo("Removing the following files:") - else: - click.echo("I want to remove the following files:") - - for filename in fragment_filenames: - click.echo(filename) - - if answer_yes or click.confirm("Is it okay if I remove those files?", default=True): +def remove_files(fragment_filenames: list[str]) -> None: + if fragment_filenames: call(["git", "rm", "--quiet"] + fragment_filenames) diff --git a/src/towncrier/build.py b/src/towncrier/build.py index 6dd87ae..3518940 100644 --- a/src/towncrier/build.py +++ b/src/towncrier/build.py @@ -15,8 +15,11 @@ from datetime import date import click +from click import Context, Option + +from towncrier import _git + from ._builder import find_fragments, render_fragments, split_fragments -from ._git import remove_files, stage_newsfile from ._project import get_project_name, get_version from ._settings import ConfigError, config_option_help, load_config_from_options from ._writer import append_to_newsfile @@ -26,6 +29,18 @@ def _get_date() -> str: return date.today().isoformat() +def _validate_answer(ctx: Context, param: Option, value: bool) -> bool: + value_check = ( + ctx.params.get("answer_yes") + if param.name == "answer_keep" + else ctx.params.get("answer_keep") + ) + if value_check and value: + click.echo("You can not choose both --yes and --keep at the same time") + ctx.abort() + return value + + @click.command(name="build") @click.option( "--draft", @@ -67,9 +82,18 @@ def _get_date() -> str: @click.option( "--yes", "answer_yes", - default=False, + default=None, flag_value=True, help="Do not ask for confirmation to remove news fragments.", + callback=_validate_answer, +) [email protected]( + "--keep", + "answer_keep", + default=None, + flag_value=True, + help="Do not ask for confirmations. But keep news fragments.", + callback=_validate_answer, ) def _main( draft: bool, @@ -79,6 +103,7 @@ def _main( project_version: str | None, project_date: str | None, answer_yes: bool, + answer_keep: bool, ) -> None: """ Build a combined news file from news fragment. @@ -92,6 +117,7 @@ def _main( project_version, project_date, answer_yes, + answer_keep, ) except ConfigError as e: print(e, file=sys.stderr) @@ -106,6 +132,7 @@ def __main( project_version: str | None, project_date: str | None, answer_yes: bool, + answer_keep: bool, ) -> None: """ The main entry point. @@ -234,13 +261,43 @@ def __main( ) click.echo("Staging newsfile...", err=to_err) - stage_newsfile(base_directory, news_file) + _git.stage_newsfile(base_directory, news_file) click.echo("Removing news fragments...", err=to_err) - remove_files(fragment_filenames, answer_yes) + if should_remove_fragment_files( + fragment_filenames, + answer_yes, + answer_keep, + ): + _git.remove_files(fragment_filenames) click.echo("Done!", err=to_err) +def should_remove_fragment_files( + fragment_filenames: list[str], + answer_yes: bool, + answer_keep: bool, +) -> bool: + try: + if answer_keep: + click.echo("Keeping the following files:") + # Not proceeding with the removal of the files. + return False + + if answer_yes: + click.echo("Removing the following files:") + else: + click.echo("I want to remove the following files:") + finally: + # Will always be printed, even for answer_keep to help with possible troubleshooting + for filename in fragment_filenames: + click.echo(filename) + + if answer_yes or click.confirm("Is it okay if I remove those files?", default=True): + return True + return False + + if __name__ == "__main__": # pragma: no cover _main() diff --git a/src/towncrier/newsfragments/129.feature b/src/towncrier/newsfragments/129.feature new file mode 100644 index 0000000..b36c8fb --- /dev/null +++ b/src/towncrier/newsfragments/129.feature @@ -0,0 +1,2 @@ +Added ``--keep`` option to the ``build`` command that allows to generate a newsfile, but keeps the newsfragments in place. +This option can not be used together with ``--yes``.
twisted/towncrier
9554985492bb023482f0596b668d11bc7351c6ab
diff --git a/src/towncrier/test/test_build.py b/src/towncrier/test/test_build.py index 5821342..0a76d91 100644 --- a/src/towncrier/test/test_build.py +++ b/src/towncrier/test/test_build.py @@ -407,6 +407,66 @@ class TestCli(TestCase): self.assertFalse(os.path.isfile(fragment_path1)) self.assertFalse(os.path.isfile(fragment_path2)) + @with_isolated_runner + def test_keep_fragments(self, runner): + """ + The `--keep` option will build the full final news file + without deleting the fragment files and without + any extra CLI interaction or confirmation. + """ + setup_simple_project() + fragment_path1 = "foo/newsfragments/123.feature" + fragment_path2 = "foo/newsfragments/124.feature.rst" + with open(fragment_path1, "w") as f: + f.write("Adds levitation") + with open(fragment_path2, "w") as f: + f.write("Extends levitation") + + call(["git", "init"]) + call(["git", "config", "user.name", "user"]) + call(["git", "config", "user.email", "[email protected]"]) + call(["git", "add", "."]) + call(["git", "commit", "-m", "Initial Commit"]) + + result = runner.invoke(_main, ["--date", "01-01-2001", "--keep"]) + + self.assertEqual(0, result.exit_code) + # The NEWS file is created. + # So this is not just `--draft`. + self.assertTrue(os.path.isfile("NEWS.rst")) + self.assertTrue(os.path.isfile(fragment_path1)) + self.assertTrue(os.path.isfile(fragment_path2)) + + @with_isolated_runner + def test_yes_keep_error(self, runner): + """ + It will fail to perform any action when the + conflicting --keep and --yes options are provided. + + Called twice with the different order of --keep and --yes options + to make sure both orders are validated since click triggers the validator + in the order it parses the command line. + """ + setup_simple_project() + fragment_path1 = "foo/newsfragments/123.feature" + fragment_path2 = "foo/newsfragments/124.feature.rst" + with open(fragment_path1, "w") as f: + f.write("Adds levitation") + with open(fragment_path2, "w") as f: + f.write("Extends levitation") + + call(["git", "init"]) + call(["git", "config", "user.name", "user"]) + call(["git", "config", "user.email", "[email protected]"]) + call(["git", "add", "."]) + call(["git", "commit", "-m", "Initial Commit"]) + + result = runner.invoke(_main, ["--date", "01-01-2001", "--yes", "--keep"]) + self.assertEqual(1, result.exit_code) + + result = runner.invoke(_main, ["--date", "01-01-2001", "--keep", "--yes"]) + self.assertEqual(1, result.exit_code) + def test_confirmation_says_no(self): """ If the user says "no" to removing the newsfragements, we end up with @@ -429,7 +489,7 @@ class TestCli(TestCase): call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) - with patch("towncrier._git.click.confirm") as m: + with patch("towncrier.build.click.confirm") as m: m.return_value = False result = runner.invoke(_main, [])
Add option `--no` For batch-processing (e.g. when testing), an option `--no` would be helpful: ``` --no Do not ask for confirmation to remove news fragments, assume "no". ```
0.0
9554985492bb023482f0596b668d11bc7351c6ab
[ "src/towncrier/test/test_build.py::TestCli::test_keep_fragments", "src/towncrier/test/test_build.py::TestCli::test_yes_keep_error" ]
[ "src/towncrier/test/test_build.py::TestCli::test_all_version_notes_in_a_single_file", "src/towncrier/test/test_build.py::TestCli::test_bullet_points_false", "src/towncrier/test/test_build.py::TestCli::test_collision", "src/towncrier/test/test_build.py::TestCli::test_command", "src/towncrier/test/test_build.py::TestCli::test_confirmation_says_no", "src/towncrier/test/test_build.py::TestCli::test_draft_no_date", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_config_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_dir_option", "src/towncrier/test/test_build.py::TestCli::test_needs_config", "src/towncrier/test/test_build.py::TestCli::test_no_confirmation", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragment_directory", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments_draft", "src/towncrier/test/test_build.py::TestCli::test_no_package_changelog", "src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_projectless_changelog", "src/towncrier/test/test_build.py::TestCli::test_release_notes_in_separate_files", "src/towncrier/test/test_build.py::TestCli::test_section_and_type_sorting", "src/towncrier/test/test_build.py::TestCli::test_singlefile_errors_and_explains_cleanly", "src/towncrier/test/test_build.py::TestCli::test_start_string", "src/towncrier/test/test_build.py::TestCli::test_subcommand", "src/towncrier/test/test_build.py::TestCli::test_title_format_custom", "src/towncrier/test/test_build.py::TestCli::test_title_format_false", "src/towncrier/test/test_build.py::TestCli::test_version_in_config", "src/towncrier/test/test_build.py::TestCli::test_with_topline_and_template_and_draft" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-11-24 20:29:50+00:00
mit
6,111
twisted__towncrier-507
diff --git a/src/towncrier/build.py b/src/towncrier/build.py index bb01644..ef7c5f3 100644 --- a/src/towncrier/build.py +++ b/src/towncrier/build.py @@ -15,7 +15,7 @@ from datetime import date import click -from click import Context, Option +from click import Context, Option, UsageError from towncrier import _git @@ -151,6 +151,18 @@ def __main( base_directory, config = load_config_from_options(directory, config_file) to_err = draft + if project_version is None: + project_version = config.version + if project_version is None: + if not config.package: + raise UsageError( + "'--version' is required since the config file does " + "not contain 'version' or 'package'." + ) + project_version = get_version( + os.path.join(base_directory, config.package_dir), config.package + ).strip() + click.echo("Loading template...", err=to_err) if isinstance(config.template, tuple): template = resources.read_text(*config.template) @@ -182,13 +194,6 @@ def __main( fragment_contents, config.types, all_bullets=config.all_bullets ) - if project_version is None: - project_version = config.version - if project_version is None: - project_version = get_version( - os.path.join(base_directory, config.package_dir), config.package - ).strip() - if project_name is None: project_name = config.name if not project_name: diff --git a/src/towncrier/newsfragments/507.misc b/src/towncrier/newsfragments/507.misc new file mode 100644 index 0000000..b8f0478 --- /dev/null +++ b/src/towncrier/newsfragments/507.misc @@ -0,0 +1,1 @@ +A friendly message is now provided, when it's necessary to pass the ``--version`` option explicitly.
twisted/towncrier
a8f4630c126f31bf1066569406de57b00cc8bb33
diff --git a/src/towncrier/test/test_build.py b/src/towncrier/test/test_build.py index 4dbc07c..d456126 100644 --- a/src/towncrier/test/test_build.py +++ b/src/towncrier/test/test_build.py @@ -511,6 +511,19 @@ class TestCli(TestCase): self.assertEqual(1, result.exit_code, result.output) self.assertTrue(result.output.startswith("No configuration file found.")) + @with_isolated_runner + def test_needs_version(self, runner: CliRunner): + """ + If the configuration file doesn't specify a version or a package, the version + option is required. + """ + write("towncrier.toml", "[tool.towncrier]") + + result = runner.invoke(_main, ["--draft"], catch_exceptions=False) + + self.assertEqual(2, result.exit_code) + self.assertIn("Error: '--version' is required", result.output) + def test_projectless_changelog(self): """In which a directory containing news files is built into a changelog
Unfriendly error when the version can't be determined Given this setup: ```console $ ls changes towncrier.toml $ cat towncrier.toml [tool.towncrier] directory = "changes" ``` running `towncrier build` yields this error message: ``` Loading template... Finding news fragments... Rendering news fragments... Traceback (most recent call last): File "/home/dpb/.local/bin/towncrier", line 8, in <module> sys.exit(cli()) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/towncrier/build.py", line 89, in _main return __main( File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/towncrier/build.py", line 147, in __main project_version = get_version( File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/towncrier/_project.py", line 40, in get_version module = _get_package(package_dir, package) File "/home/dpb/.local/pipx/venvs/towncrier/lib/python3.10/site-packages/towncrier/_project.py", line 19, in _get_package module = import_module(package) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1047, in _gcd_import File "<frozen importlib._bootstrap>", line 981, in _sanity_check ValueError: Empty module name ``` This in no way describes the actual problem, which is that towncrier couldn't determine the project version. It would be nice if it could display a friendlier message, e.g. "Unable to determine the project version. Use the --version option."
0.0
a8f4630c126f31bf1066569406de57b00cc8bb33
[ "src/towncrier/test/test_build.py::TestCli::test_needs_version" ]
[ "src/towncrier/test/test_build.py::TestCli::test_all_version_notes_in_a_single_file", "src/towncrier/test/test_build.py::TestCli::test_bullet_points_false", "src/towncrier/test/test_build.py::TestCli::test_collision", "src/towncrier/test/test_build.py::TestCli::test_command", "src/towncrier/test/test_build.py::TestCli::test_confirmation_says_no", "src/towncrier/test/test_build.py::TestCli::test_default_start_string", "src/towncrier/test/test_build.py::TestCli::test_default_start_string_markdown", "src/towncrier/test/test_build.py::TestCli::test_draft_no_date", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_config_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_dir_option", "src/towncrier/test/test_build.py::TestCli::test_keep_fragments", "src/towncrier/test/test_build.py::TestCli::test_needs_config", "src/towncrier/test/test_build.py::TestCli::test_no_confirmation", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragment_directory", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments_draft", "src/towncrier/test/test_build.py::TestCli::test_no_package_changelog", "src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_projectless_changelog", "src/towncrier/test/test_build.py::TestCli::test_release_notes_in_separate_files", "src/towncrier/test/test_build.py::TestCli::test_section_and_type_sorting", "src/towncrier/test/test_build.py::TestCli::test_singlefile_errors_and_explains_cleanly", "src/towncrier/test/test_build.py::TestCli::test_start_string", "src/towncrier/test/test_build.py::TestCli::test_subcommand", "src/towncrier/test/test_build.py::TestCli::test_title_format_custom", "src/towncrier/test/test_build.py::TestCli::test_title_format_false", "src/towncrier/test/test_build.py::TestCli::test_version_in_config", "src/towncrier/test/test_build.py::TestCli::test_with_topline_and_template_and_draft", "src/towncrier/test/test_build.py::TestCli::test_yes_keep_error" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-05-03 02:17:57+00:00
mit
6,112
twisted__towncrier-557
diff --git a/docs/cli.rst b/docs/cli.rst index 90b5c89..7af5a3a 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -24,6 +24,13 @@ The following options can be passed to all of the commands that explained below: Build the combined news file from news fragments. ``build`` is also assumed if no command is passed. +If there are no news fragments (including an empty fragments directory or a +non-existent directory), a notice of "no significant changes" will be added to +the news file. + +By default, the processed news fragments are removed using ``git``, which will +also remove the fragments directory if now empty. + .. option:: --draft Only render news fragments to standard output. @@ -67,6 +74,8 @@ Create a news fragment in the directory that ``towncrier`` is configured to look ``towncrier create`` will enforce that the passed type (e.g. ``bugfix``) is valid. +If the fragments directory does not exist, it will be created. + If the filename exists already, ``towncrier create`` will add (and then increment) a number after the fragment type until it finds a filename that does not exist yet. In the above example, it will generate ``123.bugfix.1.rst`` if ``123.bugfix.rst`` already exists. diff --git a/src/towncrier/_builder.py b/src/towncrier/_builder.py index 6f8f166..3f72f1f 100644 --- a/src/towncrier/_builder.py +++ b/src/towncrier/_builder.py @@ -6,15 +6,12 @@ from __future__ import annotations import os import textwrap -import traceback from collections import defaultdict from typing import Any, DefaultDict, Iterable, Iterator, Mapping, Sequence from jinja2 import Template -from ._settings import ConfigError - def strip_if_integer_string(s: str) -> str: try: @@ -102,11 +99,8 @@ def find_fragments( try: files = os.listdir(section_dir) - except FileNotFoundError as e: - message = "Failed to list the news fragment files.\n{}".format( - "".join(traceback.format_exception_only(type(e), e)), - ) - raise ConfigError(message) + except FileNotFoundError: + files = [] file_content = {} diff --git a/src/towncrier/newsfragments/538.bugfix b/src/towncrier/newsfragments/538.bugfix new file mode 100644 index 0000000..3a6fbf3 --- /dev/null +++ b/src/towncrier/newsfragments/538.bugfix @@ -0,0 +1,1 @@ +``build`` now treats a missing fragments directory the same as an empty one, consistent with other operations.
twisted/towncrier
f6809f031fce9fe3568166247f8ccf8f7a6c4aaf
diff --git a/src/towncrier/test/test_build.py b/src/towncrier/test/test_build.py index f15cd9a..780a3c8 100644 --- a/src/towncrier/test/test_build.py +++ b/src/towncrier/test/test_build.py @@ -182,8 +182,8 @@ class TestCli(TestCase): result = runner.invoke(_main, ["--draft", "--date", "01-01-2001"]) - self.assertEqual(1, result.exit_code, result.output) - self.assertIn("Failed to list the news fragment files.\n", result.output) + self.assertEqual(0, result.exit_code) + self.assertIn("No significant changes.\n", result.output) def test_no_newsfragments_draft(self): """
FileNotFoundError, Failed to list the news fragment files After [adopting towncrier](https://github.com/jaraco/skeleton/pull/84) for the hundreds of projects that depend on [jaraco/skeleton](/jaraco/skeleton), I've been pleased to say that it has helped streamline the changelog generation. I've tried as much as possible to minimize the amount of config required (relying on towncrier to provide best practices by default). Unfortunately, if I try to cut a release when there are no newsfragments, the "[finalize](https://github.com/jaraco/jaraco.develop/blob/9061f3bfc77c39fa2c3b1e06ea0c7695edb753ef/jaraco/develop/finalize.py#L9-L13)" step fails: ``` pytest-checkdocs main @ tox -e finalize finalize: commands[0]> python -m jaraco.develop.finalize Loading template... Finding news fragments... Failed to list the news fragment files. FileNotFoundError: [Errno 2] No such file or directory: '/Users/jaraco/code/jaraco/pytest-checkdocs/newsfragments' ``` I can work around the issue by first running `mkdir -p newsfragments`, but I'd rather not have to add that step. I know I can create a permanent `newsfragments` directory in every project, but that requires adding a sentinel file to keep it present. And given that towncrier already works well to create that directory when it doesn't exist, I'd like it to fall back to the degenerate behavior when running `build`. Can you update towncrier build to treat a missing fragments directory as the same as an empty directory, same as towcrier create?
0.0
f6809f031fce9fe3568166247f8ccf8f7a6c4aaf
[ "src/towncrier/test/test_build.py::TestCli::test_no_newsfragment_directory" ]
[ "src/towncrier/test/test_build.py::TestCli::test_all_version_notes_in_a_single_file", "src/towncrier/test/test_build.py::TestCli::test_bullet_points_false", "src/towncrier/test/test_build.py::TestCli::test_collision", "src/towncrier/test/test_build.py::TestCli::test_command", "src/towncrier/test/test_build.py::TestCli::test_confirmation_says_no", "src/towncrier/test/test_build.py::TestCli::test_default_start_string", "src/towncrier/test/test_build.py::TestCli::test_default_start_string_markdown", "src/towncrier/test/test_build.py::TestCli::test_draft_no_date", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_config_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_dir_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_with_nondefault_newsfragments_directory", "src/towncrier/test/test_build.py::TestCli::test_keep_fragments", "src/towncrier/test/test_build.py::TestCli::test_needs_config", "src/towncrier/test/test_build.py::TestCli::test_needs_version", "src/towncrier/test/test_build.py::TestCli::test_no_confirmation", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments_draft", "src/towncrier/test/test_build.py::TestCli::test_no_package_changelog", "src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_projectless_changelog", "src/towncrier/test/test_build.py::TestCli::test_release_notes_in_separate_files", "src/towncrier/test/test_build.py::TestCli::test_section_and_type_sorting", "src/towncrier/test/test_build.py::TestCli::test_singlefile_errors_and_explains_cleanly", "src/towncrier/test/test_build.py::TestCli::test_start_string", "src/towncrier/test/test_build.py::TestCli::test_subcommand", "src/towncrier/test/test_build.py::TestCli::test_title_format_custom", "src/towncrier/test/test_build.py::TestCli::test_title_format_false", "src/towncrier/test/test_build.py::TestCli::test_version_in_config", "src/towncrier/test/test_build.py::TestCli::test_with_topline_and_template_and_draft", "src/towncrier/test/test_build.py::TestCli::test_yes_keep_error" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-24 01:08:39+00:00
mit
6,113
twisted__towncrier-564
diff --git a/.gitignore b/.gitignore index fa4a8cd..e101cbb 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ .vs/ .vscode Justfile +*egg-info/ _trial_temp*/ apidocs/ dist/ diff --git a/src/towncrier/_builder.py b/src/towncrier/_builder.py index 3f72f1f..3d86354 100644 --- a/src/towncrier/_builder.py +++ b/src/towncrier/_builder.py @@ -32,24 +32,20 @@ def parse_newfragment_basename( if len(parts) == 1: return invalid - if len(parts) == 2: - ticket, category = parts - ticket = strip_if_integer_string(ticket) - return (ticket, category, 0) if category in frag_type_names else invalid - # There are at least 3 parts. Search for a valid category from the second - # part onwards. + # There are at least 2 parts. Search for a valid category from the second + # part onwards starting at the back. # The category is used as the reference point in the parts list to later # infer the issue number and counter value. - for i in range(1, len(parts)): + for i in reversed(range(1, len(parts))): if parts[i] in frag_type_names: # Current part is a valid category according to given definitions. category = parts[i] - # Use the previous part as the ticket number. + # Use all previous parts as the ticket number. # NOTE: This allows news fragment names like fix-1.2.3.feature or # something-cool.feature.ext for projects that don't use ticket # numbers in news fragment names. - ticket = strip_if_integer_string(parts[i - 1]) + ticket = strip_if_integer_string(".".join(parts[0:i])) counter = 0 # Use the following part as the counter if it exists and is a valid # digit. diff --git a/src/towncrier/newsfragments/562.bugfix b/src/towncrier/newsfragments/562.bugfix new file mode 100644 index 0000000..623ceab --- /dev/null +++ b/src/towncrier/newsfragments/562.bugfix @@ -0,0 +1,1 @@ +Orphan newsfragments containing numeric values are no longer accidentally associated to tickets. In previous versions the orphan marker was ignored and the newsfragment was associated to a ticket having the last numerical value from the filename. diff --git a/src/towncrier/newsfragments/562.bugfix.1 b/src/towncrier/newsfragments/562.bugfix.1 new file mode 100644 index 0000000..d751ebe --- /dev/null +++ b/src/towncrier/newsfragments/562.bugfix.1 @@ -0,0 +1,2 @@ +Fragments with filenames like `fix-1.2.3.feature` are now associated with the ticket `fix-1.2.3`. +In previous versions they were incorrectly associated to ticket `3`.
twisted/towncrier
a275be976216b7e11b896b63df7fd9fcbccc0023
diff --git a/src/towncrier/test/test_build.py b/src/towncrier/test/test_build.py index 780a3c8..938814c 100644 --- a/src/towncrier/test/test_build.py +++ b/src/towncrier/test/test_build.py @@ -43,6 +43,14 @@ class TestCli(TestCase): f.write("Orphaned feature") with open("foo/newsfragments/+xxx.feature", "w") as f: f.write("Another orphaned feature") + with open("foo/newsfragments/+123_orphaned.feature", "w") as f: + f.write("An orphaned feature starting with a number") + with open("foo/newsfragments/+12.3_orphaned.feature", "w") as f: + f.write("An orphaned feature starting with a dotted number") + with open("foo/newsfragments/+orphaned_123.feature", "w") as f: + f.write("An orphaned feature ending with a number") + with open("foo/newsfragments/+orphaned_12.3.feature", "w") as f: + f.write("An orphaned feature ending with a dotted number") # Towncrier ignores files that don't have a dot with open("foo/newsfragments/README", "w") as f: f.write("Blah blah") @@ -52,7 +60,7 @@ class TestCli(TestCase): result = runner.invoke(command, ["--draft", "--date", "01-01-2001"]) - self.assertEqual(0, result.exit_code) + self.assertEqual(0, result.exit_code, result.output) self.assertEqual( result.output, dedent( @@ -70,9 +78,13 @@ class TestCli(TestCase): -------- - Baz levitation (baz) - - Baz fix levitation (#2) + - Baz fix levitation (fix-1.2) - Adds levitation (#123) - Extends levitation (#124) + - An orphaned feature ending with a dotted number + - An orphaned feature ending with a number + - An orphaned feature starting with a dotted number + - An orphaned feature starting with a number - Another orphaned feature - Orphaned feature @@ -405,6 +417,7 @@ class TestCli(TestCase): call(["git", "init"]) call(["git", "config", "user.name", "user"]) call(["git", "config", "user.email", "[email protected]"]) + call(["git", "config", "commit.gpgSign", "false"]) call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) @@ -429,6 +442,7 @@ class TestCli(TestCase): call(["git", "init"]) call(["git", "config", "user.name", "user"]) call(["git", "config", "user.email", "[email protected]"]) + call(["git", "config", "commit.gpgSign", "false"]) call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) @@ -458,6 +472,7 @@ class TestCli(TestCase): call(["git", "init"]) call(["git", "config", "user.name", "user"]) call(["git", "config", "user.email", "[email protected]"]) + call(["git", "config", "commit.gpgSign", "false"]) call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) @@ -491,6 +506,7 @@ class TestCli(TestCase): call(["git", "init"]) call(["git", "config", "user.name", "user"]) call(["git", "config", "user.email", "[email protected]"]) + call(["git", "config", "commit.gpgSign", "false"]) call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) @@ -519,6 +535,7 @@ class TestCli(TestCase): call(["git", "init"]) call(["git", "config", "user.name", "user"]) call(["git", "config", "user.email", "[email protected]"]) + call(["git", "config", "commit.gpgSign", "false"]) call(["git", "add", "."]) call(["git", "commit", "-m", "Initial Commit"]) diff --git a/src/towncrier/test/test_builder.py b/src/towncrier/test/test_builder.py index 62630af..b62033a 100644 --- a/src/towncrier/test/test_builder.py +++ b/src/towncrier/test/test_builder.py @@ -8,63 +8,73 @@ from .._builder import parse_newfragment_basename class TestParseNewsfragmentBasename(TestCase): def test_simple(self): + """<number>.<category> generates a counter value of 0.""" self.assertEqual( parse_newfragment_basename("123.feature", ["feature"]), ("123", "feature", 0), ) def test_invalid_category(self): + """Files without a valid category are rejected.""" self.assertEqual( parse_newfragment_basename("README.ext", ["feature"]), (None, None, None), ) def test_counter(self): + """<number>.<category>.<counter> generates a custom counter value.""" self.assertEqual( parse_newfragment_basename("123.feature.1", ["feature"]), ("123", "feature", 1), ) def test_counter_with_extension(self): + """File extensions are ignored.""" self.assertEqual( parse_newfragment_basename("123.feature.1.ext", ["feature"]), ("123", "feature", 1), ) def test_ignores_extension(self): + """File extensions are ignored.""" self.assertEqual( parse_newfragment_basename("123.feature.ext", ["feature"]), ("123", "feature", 0), ) def test_non_numeric_ticket(self): + """Non-numeric issue identifiers are preserved verbatim.""" self.assertEqual( parse_newfragment_basename("baz.feature", ["feature"]), ("baz", "feature", 0), ) def test_non_numeric_ticket_with_extension(self): + """File extensions are ignored.""" self.assertEqual( parse_newfragment_basename("baz.feature.ext", ["feature"]), ("baz", "feature", 0), ) def test_dots_in_ticket_name(self): + """Non-numeric issue identifiers are preserved verbatim.""" self.assertEqual( parse_newfragment_basename("baz.1.2.feature", ["feature"]), - ("2", "feature", 0), + ("baz.1.2", "feature", 0), ) def test_dots_in_ticket_name_invalid_category(self): + """Files without a valid category are rejected.""" self.assertEqual( parse_newfragment_basename("baz.1.2.notfeature", ["feature"]), (None, None, None), ) def test_dots_in_ticket_name_and_counter(self): + """Non-numeric issue identifiers are preserved verbatim.""" self.assertEqual( parse_newfragment_basename("baz.1.2.feature.3", ["feature"]), - ("2", "feature", 3), + ("baz.1.2", "feature", 3), ) def test_strip(self): @@ -77,7 +87,41 @@ class TestParseNewsfragmentBasename(TestCase): ) def test_strip_with_counter(self): + """Leading spaces and subsequent leading zeros are stripped + when parsing newsfragment names into ticket numbers etc. + """ self.assertEqual( parse_newfragment_basename(" 007.feature.3", ["feature"]), ("7", "feature", 3), ) + + def test_orphan(self): + """Orphaned snippets must remain the orphan marker in the issue + identifier.""" + self.assertEqual( + parse_newfragment_basename("+orphan.feature", ["feature"]), + ("+orphan", "feature", 0), + ) + + def test_orphan_with_number(self): + """Orphaned snippets can contain numbers in the identifier.""" + self.assertEqual( + parse_newfragment_basename("+123_orphan.feature", ["feature"]), + ("+123_orphan", "feature", 0), + ) + self.assertEqual( + parse_newfragment_basename("+orphan_123.feature", ["feature"]), + ("+orphan_123", "feature", 0), + ) + + def test_orphan_with_dotted_number(self): + """Orphaned snippets can contain numbers with dots in the + identifier.""" + self.assertEqual( + parse_newfragment_basename("+12.3_orphan.feature", ["feature"]), + ("+12.3_orphan", "feature", 0), + ) + self.assertEqual( + parse_newfragment_basename("+orphan_12.3.feature", ["feature"]), + ("+orphan_12.3", "feature", 0), + )
orphan fragments that contain a number in the filename are linked to issues. e.g. calling the fragment `CHANGES/+compat.somelib_1.12.feature` will link the supposed orphan snippet to the issue `#12`.
0.0
a275be976216b7e11b896b63df7fd9fcbccc0023
[ "src/towncrier/test/test_build.py::TestCli::test_command", "src/towncrier/test/test_build.py::TestCli::test_subcommand", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name_and_counter", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan_with_dotted_number" ]
[ "src/towncrier/test/test_build.py::TestCli::test_all_version_notes_in_a_single_file", "src/towncrier/test/test_build.py::TestCli::test_bullet_points_false", "src/towncrier/test/test_build.py::TestCli::test_collision", "src/towncrier/test/test_build.py::TestCli::test_confirmation_says_no", "src/towncrier/test/test_build.py::TestCli::test_default_start_string", "src/towncrier/test/test_build.py::TestCli::test_default_start_string_markdown", "src/towncrier/test/test_build.py::TestCli::test_draft_no_date", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_config_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_dir_option", "src/towncrier/test/test_build.py::TestCli::test_in_different_dir_with_nondefault_newsfragments_directory", "src/towncrier/test/test_build.py::TestCli::test_keep_fragments", "src/towncrier/test/test_build.py::TestCli::test_needs_config", "src/towncrier/test/test_build.py::TestCli::test_needs_version", "src/towncrier/test/test_build.py::TestCli::test_no_confirmation", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragment_directory", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments", "src/towncrier/test/test_build.py::TestCli::test_no_newsfragments_draft", "src/towncrier/test/test_build.py::TestCli::test_no_package_changelog", "src/towncrier/test/test_build.py::TestCli::test_project_name_in_config", "src/towncrier/test/test_build.py::TestCli::test_projectless_changelog", "src/towncrier/test/test_build.py::TestCli::test_release_notes_in_separate_files", "src/towncrier/test/test_build.py::TestCli::test_section_and_type_sorting", "src/towncrier/test/test_build.py::TestCli::test_singlefile_errors_and_explains_cleanly", "src/towncrier/test/test_build.py::TestCli::test_start_string", "src/towncrier/test/test_build.py::TestCli::test_title_format_custom", "src/towncrier/test/test_build.py::TestCli::test_title_format_false", "src/towncrier/test/test_build.py::TestCli::test_version_in_config", "src/towncrier/test/test_build.py::TestCli::test_with_topline_and_template_and_draft", "src/towncrier/test/test_build.py::TestCli::test_yes_keep_error", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_counter", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_counter_with_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name_invalid_category", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_ignores_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_invalid_category", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_non_numeric_ticket", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_non_numeric_ticket_with_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan_with_number", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_simple", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip_with_counter" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-11-07 08:46:46+00:00
mit
6,114
twisted__towncrier-588
diff --git a/src/towncrier/_builder.py b/src/towncrier/_builder.py index 3d86354..a72a398 100644 --- a/src/towncrier/_builder.py +++ b/src/towncrier/_builder.py @@ -13,15 +13,6 @@ from typing import Any, DefaultDict, Iterable, Iterator, Mapping, Sequence from jinja2 import Template -def strip_if_integer_string(s: str) -> str: - try: - i = int(s) - except ValueError: - return s - - return str(i) - - # Returns ticket, category and counter or (None, None, None) if the basename # could not be parsed or doesn't contain a valid category. def parse_newfragment_basename( @@ -45,7 +36,11 @@ def parse_newfragment_basename( # NOTE: This allows news fragment names like fix-1.2.3.feature or # something-cool.feature.ext for projects that don't use ticket # numbers in news fragment names. - ticket = strip_if_integer_string(".".join(parts[0:i])) + ticket = ".".join(parts[0:i]).strip() + # If the ticket is an integer, remove any leading zeros (to resolve + # issue #126). + if ticket.isdigit(): + ticket = str(int(ticket)) counter = 0 # Use the following part as the counter if it exists and is a valid # digit. diff --git a/src/towncrier/newsfragments/588.bugfix b/src/towncrier/newsfragments/588.bugfix new file mode 100644 index 0000000..f1c3e8e --- /dev/null +++ b/src/towncrier/newsfragments/588.bugfix @@ -0,0 +1,1 @@ +Orphan news fragments, fragments not associated with an issue, consisting of only digits (e.g. '+12345678.feature') now retain their leading marker character.
twisted/towncrier
2908a62d15843597d6ab1dae9cb06ab39dafa3c3
diff --git a/src/towncrier/test/test_builder.py b/src/towncrier/test/test_builder.py index b62033a..9608e0a 100644 --- a/src/towncrier/test/test_builder.py +++ b/src/towncrier/test/test_builder.py @@ -125,3 +125,10 @@ class TestParseNewsfragmentBasename(TestCase): parse_newfragment_basename("+orphan_12.3.feature", ["feature"]), ("+orphan_12.3", "feature", 0), ) + + def test_orphan_all_digits(self): + """Orphaned snippets can consist of only digits.""" + self.assertEqual( + parse_newfragment_basename("+123.feature", ["feature"]), + ("+123", "feature", 0), + )
Issue number incorrectly inferred when hash is all digits I've been using towncrier with [mostly default configuration](https://github.com/jaraco/skeleton/blob/6ff02e0eefcd90e271cefd326b460ecfa0e3eb9e/towncrier.toml) to generate news entries. I'll sometimes give a filename with an issue number (`{issue}.{scope}.rst`) and other times use `+.{scope}.rst`, and that works well. When I supply an issue number, it's included in the changelog and when I don't, it's omitted. However, today when using towncrier 23.11, my expectation was violated when the generated hash was all digits: ``` backports.tarfile main @ towncrier create -c "Initial release based on tarfile from Python 3.12.2." +.removal.rst Created news fragment at /Users/jaraco/code/jaraco/backports.tarfile/newsfragments/+96333363.removal.rst backports.tarfile main @ git add newsfragments; git commit -a -m "Add news fragment." [main ec51166] Add news fragment. 1 file changed, 1 insertion(+) create mode 100644 newsfragments/+96333363.removal.rst backports.tarfile main @ tox -e finalize finalize: install_deps> python -I -m pip install 'jaraco.develop>=7.23' towncrier finalize: commands[0]> python -m jaraco.develop.finalize Loading template... /Users/jaraco/code/jaraco/backports.tarfile/.tox/finalize/lib/python3.12/site-packages/towncrier/build.py:169: EncodingWarning: 'encoding' argument not specified resources.files(config.template[0]).joinpath(config.template[1]).read_text() Finding news fragments... Rendering news fragments... Writing to newsfile... Staging newsfile... Removing the following files: /Users/jaraco/code/jaraco/backports.tarfile/newsfragments/+96333363.removal.rst Removing news fragments... Done! [main 786b22e] Finalize 2 files changed, 7 insertions(+), 1 deletion(-) delete mode 100644 newsfragments/+96333363.removal.rst finalize: OK (5.36=setup[4.58]+cmd[0.78] seconds) congratulations :) (5.42 seconds) backports.tarfile main @ head NEWS.rst v1.0.0 ====== Deprecations and Removals ------------------------- - Initial release based on tarfile from Python 3.12.2. (#96333363) ``` It seems that if the hex hash happens not to have any digits greater than 9, the hash is inferred to be an issue number. That feels like a bug, since the same behavior would not produce an issue number if there were hex digits greater than 9. Perhaps towncrier should provide a way to distinguish between a hash and a typical issue number.
0.0
2908a62d15843597d6ab1dae9cb06ab39dafa3c3
[ "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan_all_digits" ]
[ "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_counter", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_counter_with_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name_and_counter", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_dots_in_ticket_name_invalid_category", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_ignores_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_invalid_category", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_non_numeric_ticket", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_non_numeric_ticket_with_extension", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan_with_dotted_number", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_orphan_with_number", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_simple", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip", "src/towncrier/test/test_builder.py::TestParseNewsfragmentBasename::test_strip_with_counter" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2024-04-23 22:57:18+00:00
mit
6,115
twisted__treq-298
diff --git a/changelog.d/294.removal.rst b/changelog.d/294.removal.rst new file mode 100644 index 0000000..deac5df --- /dev/null +++ b/changelog.d/294.removal.rst @@ -0,0 +1,1 @@ +Deprecate tolerance of non-string values when passing headers as a dict. They have historically been silently dropped, but will raise TypeError in the next treq release. Also deprecate passing headers other than :class:`dict`, :class:`~twisted.web.http_headers.Headers`, or ``None``. Historically falsy values like ``[]`` or ``()`` were accepted. diff --git a/src/treq/client.py b/src/treq/client.py index 113d6bb..ba4f0a1 100644 --- a/src/treq/client.py +++ b/src/treq/client.py @@ -171,27 +171,13 @@ class HTTPClient(object): url = parsed_url.to_uri().to_text().encode('ascii') - # Convert headers dictionary to - # twisted raw headers format. - headers = kwargs.pop('headers', None) - if headers: - if isinstance(headers, dict): - h = Headers({}) - for k, v in headers.items(): - if isinstance(v, (bytes, six.text_type)): - h.addRawHeader(k, v) - elif isinstance(v, list): - h.setRawHeaders(k, v) - - headers = h - else: - headers = Headers({}) + headers = self._request_headers(kwargs.pop('headers', None), stacklevel + 1) bodyProducer, contentType = self._request_body( data=kwargs.pop('data', None), files=kwargs.pop('files', None), json=kwargs.pop('json', _NOTHING), - stacklevel=stacklevel, + stacklevel=stacklevel + 1, ) if contentType is not None: headers.setRawHeaders(b'Content-Type', [contentType]) @@ -252,6 +238,47 @@ class HTTPClient(object): return d.addCallback(_Response, cookies) + def _request_headers(self, headers, stacklevel): + """ + Convert the *headers* argument to a :class:`Headers` instance + + :returns: + :class:`twisted.web.http_headers.Headers` + """ + if isinstance(headers, dict): + h = Headers({}) + for k, v in headers.items(): + if isinstance(v, (bytes, six.text_type)): + h.addRawHeader(k, v) + elif isinstance(v, list): + h.setRawHeaders(k, v) + else: + warnings.warn( + ( + "The value of headers key {!r} has non-string type {}" + " and will be dropped." + " This will raise TypeError in the next treq release." + ).format(k, type(v)), + DeprecationWarning, + stacklevel=stacklevel, + ) + return h + if isinstance(headers, Headers): + return headers + if headers is None: + return Headers({}) + + warnings.warn( + ( + "headers must be a dict, twisted.web.http_headers.Headers, or None," + " but found {}, which will be ignored." + " This will raise TypeError in the next treq release." + ).format(type(headers)), + DeprecationWarning, + stacklevel=stacklevel, + ) + return Headers({}) + def _request_body(self, data, files, json, stacklevel): """ Here we choose a right producer based on the parameters passed in. @@ -287,7 +314,7 @@ class HTTPClient(object): " This will raise TypeError in the next treq release." ).format("data" if data else "files"), DeprecationWarning, - stacklevel=stacklevel + 1, + stacklevel=stacklevel, ) if files:
twisted/treq
d45cad202a5b4650213c170725b2a0b0577f94ee
diff --git a/src/treq/test/test_client.py b/src/treq/test/test_client.py index 51a316d..a4dc957 100644 --- a/src/treq/test/test_client.py +++ b/src/treq/test/test_client.py @@ -1,4 +1,5 @@ # -*- encoding: utf-8 -*- +from collections import OrderedDict from io import BytesIO import mock @@ -517,6 +518,43 @@ class HTTPClientTests(TestCase): b'Accept': [b'application/json', b'text/plain']}), None) + def test_request_headers_invalid_type(self): + """ + `HTTPClient.request()` warns that headers of an unexpected type are + invalid and that this behavior is deprecated. + """ + self.client.request('GET', 'http://example.com', headers=[]) + + [w] = self.flushWarnings([self.test_request_headers_invalid_type]) + self.assertEqual(DeprecationWarning, w['category']) + self.assertIn( + "headers must be a dict, twisted.web.http_headers.Headers, or None,", + w['message'], + ) + + def test_request_dict_headers_invalid_values(self): + """ + `HTTPClient.request()` warns that non-string header values are dropped + and that this behavior is deprecated. + """ + self.client.request('GET', 'http://example.com', headers=OrderedDict([ + ('none', None), + ('one', 1), + ('ok', 'string'), + ])) + + [w1, w2] = self.flushWarnings([self.test_request_dict_headers_invalid_values]) + self.assertEqual(DeprecationWarning, w1['category']) + self.assertEqual(DeprecationWarning, w2['category']) + self.assertIn( + "The value of headers key 'none' has non-string type", + w1['message'], + ) + self.assertIn( + "The value of headers key 'one' has non-string type", + w2['message'], + ) + def test_request_invalid_param(self): """ `HTTPClient.request()` warns that invalid parameters are ignored and
treq will silently ignore invalid non-string header values If a header value is something other than a string, bytes, or list, treq will silently drop the header. It should raise an error instead. For example this request would not send `Some-Header`: ```py treq.get('http://example.com', headers={'Some-Header': uuid.uuid4()}) ``` This if statement needs a final `else` to raise an error. https://github.com/twisted/treq/blob/7a8f45af471d172254176e4d71c8d2c0cbc5a7ae/src/treq/client.py#L171-L175
0.0
d45cad202a5b4650213c170725b2a0b0577f94ee
[ "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_headers_invalid_values", "src/treq/test/test_client.py::HTTPClientTests::test_request_headers_invalid_type" ]
[ "src/treq/test/test_client.py::HTTPClientTests::test_post", "src/treq/test/test_client.py::HTTPClientTests::test_request_browser_like_redirects", "src/treq/test/test_client.py::HTTPClientTests::test_request_case_insensitive_methods", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_file", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_single_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_tuple", "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_headers", "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_single_value_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_invalid_param", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_bool", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_none", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_number", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_string", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_tuple", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_with_data", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_with_files", "src/treq/test/test_client.py::HTTPClientTests::test_request_merge_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_merge_tuple_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_mixed_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_mixed_params_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_named_attachment", "src/treq/test/test_client.py::HTTPClientTests::test_request_named_attachment_and_ctype", "src/treq/test/test_client.py::HTTPClientTests::test_request_no_name_attachment", "src/treq/test/test_client.py::HTTPClientTests::test_request_post_redirect_denied", "src/treq/test/test_client.py::HTTPClientTests::test_request_query_param_seps", "src/treq/test/test_client.py::HTTPClientTests::test_request_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_timeout_cancelled", "src/treq/test/test_client.py::HTTPClientTests::test_request_timeout_fired", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_param_coercion", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_value_coercion", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_values", "src/treq/test/test_client.py::HTTPClientTests::test_request_unsupported_params_combination", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_decodedurl", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_encodedurl", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_hyperlink_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_idn", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_idn_params", "src/treq/test/test_client.py::HTTPClientTests::test_response_buffering_is_disabled_with_unbufferred_arg", "src/treq/test/test_client.py::HTTPClientTests::test_response_is_buffered", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_buffers_data", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_fires_finished_deferred", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_propagates_data_to_destination", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_propogates_connectionLost_reason", "src/treq/test/test_client.py::BufferedResponseTests::test_concurrent_receivers", "src/treq/test/test_client.py::BufferedResponseTests::test_receiver_after_finished", "src/treq/test/test_client.py::BufferedResponseTests::test_wraps_protocol" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-09-30 05:09:11+00:00
mit
6,116
twisted__treq-319
diff --git a/src/treq/client.py b/src/treq/client.py index 7924d11..48fdc7f 100644 --- a/src/treq/client.py +++ b/src/treq/client.py @@ -143,12 +143,29 @@ class HTTPClient: kwargs.setdefault('_stacklevel', 3) return self.request('DELETE', url, **kwargs) - def request(self, method, url, **kwargs): + def request( + self, + method, + url, + *, + params=None, + headers=None, + data=None, + files=None, + json=_NOTHING, + auth=None, + cookies=None, + allow_redirects=True, + browser_like_redirects=False, + unbuffered=False, + reactor=None, + timeout=None, + _stacklevel=2, + ): """ See :func:`treq.request()`. """ method = method.encode('ascii').upper() - stacklevel = kwargs.pop('_stacklevel', 2) if isinstance(url, DecodedURL): parsed_url = url.encoded_url @@ -163,7 +180,6 @@ class HTTPClient: # Join parameters provided in the URL # and the ones passed as argument. - params = kwargs.pop('params', None) if params: parsed_url = parsed_url.replace( query=parsed_url.query + tuple(_coerced_query_params(params)) @@ -171,27 +187,20 @@ class HTTPClient: url = parsed_url.to_uri().to_text().encode('ascii') - headers = self._request_headers(kwargs.pop('headers', None), stacklevel + 1) + headers = self._request_headers(headers, _stacklevel + 1) - bodyProducer, contentType = self._request_body( - data=kwargs.pop('data', None), - files=kwargs.pop('files', None), - json=kwargs.pop('json', _NOTHING), - stacklevel=stacklevel + 1, - ) + bodyProducer, contentType = self._request_body(data, files, json, + stacklevel=_stacklevel + 1) if contentType is not None: headers.setRawHeaders(b'Content-Type', [contentType]) - cookies = kwargs.pop('cookies', {}) - if not isinstance(cookies, CookieJar): cookies = cookiejar_from_dict(cookies) cookies = merge_cookies(self._cookiejar, cookies) wrapped_agent = CookieAgent(self._agent, cookies) - browser_like_redirects = kwargs.pop('browser_like_redirects', False) - if kwargs.pop('allow_redirects', True): + if allow_redirects: if browser_like_redirects: wrapped_agent = BrowserLikeRedirectAgent(wrapped_agent) else: @@ -200,7 +209,6 @@ class HTTPClient: wrapped_agent = ContentDecoderAgent(wrapped_agent, [(b'gzip', GzipDecoder)]) - auth = kwargs.pop('auth', None) if auth: wrapped_agent = add_auth(wrapped_agent, auth) @@ -208,10 +216,8 @@ class HTTPClient: method, url, headers=headers, bodyProducer=bodyProducer) - reactor = kwargs.pop('reactor', None) if reactor is None: from twisted.internet import reactor - timeout = kwargs.pop('timeout', None) if timeout: delayedCall = reactor.callLater(timeout, d.cancel) @@ -222,20 +228,9 @@ class HTTPClient: d.addBoth(gotResult) - if not kwargs.pop('unbuffered', False): + if not unbuffered: d.addCallback(_BufferedResponse) - if kwargs: - warnings.warn( - ( - "Got unexpected keyword argument: {}." - " treq will ignore this argument," - " but will raise TypeError in the next treq release." - ).format(", ".join(repr(k) for k in kwargs)), - DeprecationWarning, - stacklevel=stacklevel, - ) - return d.addCallback(_Response, cookies) def _request_headers(self, headers, stacklevel):
twisted/treq
321fb6e015bfcb806fe06d04a49a03965601a49b
diff --git a/src/treq/test/test_api.py b/src/treq/test/test_api.py index f7f9e09..2d9a1a1 100644 --- a/src/treq/test/test_api.py +++ b/src/treq/test/test_api.py @@ -101,25 +101,15 @@ class TreqAPITests(TestCase): This test verifies that stacklevel is set appropriately when issuing the warning. """ - self.failureResultOf( + with self.assertRaises(TypeError) as c: treq.request( "GET", "https://foo.bar", invalid=True, pool=SyntacticAbominationHTTPConnectionPool(), ) - ) - [w] = self.flushWarnings([self.test_request_invalid_param]) - self.assertEqual(DeprecationWarning, w["category"]) - self.assertEqual( - ( - "Got unexpected keyword argument: 'invalid'." - " treq will ignore this argument," - " but will raise TypeError in the next treq release." - ), - w["message"], - ) + self.assertIn("invalid", str(c.exception)) def test_post_json_with_data(self): """ diff --git a/src/treq/test/test_client.py b/src/treq/test/test_client.py index ee9f3fd..52897ce 100644 --- a/src/treq/test/test_client.py +++ b/src/treq/test/test_client.py @@ -655,19 +655,15 @@ class HTTPClientTests(TestCase): def test_request_invalid_param(self): """ - `HTTPClient.request()` warns that invalid parameters are ignored and - that this is deprecated. + `HTTPClient.request()` rejects invalid keyword parameters with + `TypeError`. """ - self.client.request('GET', b'http://example.com', invalid=True) - - [w] = self.flushWarnings([self.test_request_invalid_param]) - self.assertEqual( - ( - "Got unexpected keyword argument: 'invalid'." - " treq will ignore this argument," - " but will raise TypeError in the next treq release." - ), - w['message'], + self.assertRaises( + TypeError, + self.client.request, + "GET", + b"http://example.com", + invalid=True, ) @with_clock diff --git a/src/treq/test/test_multipart.py b/src/treq/test/test_multipart.py index fd170e3..d193037 100644 --- a/src/treq/test/test_multipart.py +++ b/src/treq/test/test_multipart.py @@ -78,20 +78,26 @@ class MultiPartProducerTestCase(unittest.TestCase): passed as a parameter without either a C{seek} or C{tell} method, its C{length} attribute is set to C{UNKNOWN_LENGTH}. """ - class HasSeek: + class CantTell: def seek(self, offset, whence): - pass + """ + A C{seek} method that is never called because there is no + matching C{tell} method. + """ - class HasTell: + class CantSeek: def tell(self): - pass + """ + A C{tell} method that is never called because there is no + matching C{seek} method. + """ producer = MultiPartProducer( - {"f": ("name", None, FileBodyProducer(HasSeek()))}) + {"f": ("name", None, FileBodyProducer(CantTell()))}) self.assertEqual(UNKNOWN_LENGTH, producer.length) producer = MultiPartProducer( - {"f": ("name", None, FileBodyProducer(HasTell()))}) + {"f": ("name", None, FileBodyProducer(CantSeek()))}) self.assertEqual(UNKNOWN_LENGTH, producer.length) def test_knownLengthOnFile(self):
public APIs should not swallow arbitrary invalid keyword arguments This needs to be done in three steps: - [x] emit a deprecation warning when emitting unused keyword arguments - [x] do a release with the deprecation warning - [x] remove the `**kwargs` entirely #251 was both the initial report of this as well as a proposed implementation, but its author lost interest.
0.0
321fb6e015bfcb806fe06d04a49a03965601a49b
[ "src/treq/test/test_api.py::TreqAPITests::test_request_invalid_param", "src/treq/test/test_client.py::HTTPClientTests::test_request_invalid_param" ]
[ "src/treq/test/test_api.py::TreqAPITests::test_cached_pool", "src/treq/test/test_api.py::TreqAPITests::test_custom_agent", "src/treq/test/test_api.py::TreqAPITests::test_custom_pool", "src/treq/test/test_api.py::TreqAPITests::test_default_pool", "src/treq/test/test_api.py::TreqAPITests::test_post_json_with_data", "src/treq/test/test_api.py::DefaultReactorTests::test_passes_reactor", "src/treq/test/test_api.py::DefaultReactorTests::test_uses_default_reactor", "src/treq/test/test_api.py::DefaultPoolTests::test_cached_global_pool", "src/treq/test/test_api.py::DefaultPoolTests::test_persistent_false", "src/treq/test/test_api.py::DefaultPoolTests::test_persistent_false_new", "src/treq/test/test_api.py::DefaultPoolTests::test_persistent_false_not_stored", "src/treq/test/test_api.py::DefaultPoolTests::test_pool_none_persistent_none", "src/treq/test/test_api.py::DefaultPoolTests::test_pool_none_persistent_true", "src/treq/test/test_api.py::DefaultPoolTests::test_specified_pool", "src/treq/test/test_client.py::HTTPClientTests::test_post", "src/treq/test/test_client.py::HTTPClientTests::test_request_browser_like_redirects", "src/treq/test/test_client.py::HTTPClientTests::test_request_case_insensitive_methods", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_file", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_single_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_data_tuple", "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_headers", "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_headers_invalid_values", "src/treq/test/test_client.py::HTTPClientTests::test_request_dict_single_value_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_files_tuple_too_long", "src/treq/test/test_client.py::HTTPClientTests::test_request_files_tuple_too_short", "src/treq/test/test_client.py::HTTPClientTests::test_request_headers_invalid_type", "src/treq/test/test_client.py::HTTPClientTests::test_request_headers_object", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_bool", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_none", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_number", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_string", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_tuple", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_with_data", "src/treq/test/test_client.py::HTTPClientTests::test_request_json_with_files", "src/treq/test/test_client.py::HTTPClientTests::test_request_merge_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_merge_tuple_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_mixed_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_mixed_params_dict", "src/treq/test/test_client.py::HTTPClientTests::test_request_named_attachment", "src/treq/test/test_client.py::HTTPClientTests::test_request_named_attachment_and_ctype", "src/treq/test/test_client.py::HTTPClientTests::test_request_no_name_attachment", "src/treq/test/test_client.py::HTTPClientTests::test_request_post_redirect_denied", "src/treq/test/test_client.py::HTTPClientTests::test_request_query_param_seps", "src/treq/test/test_client.py::HTTPClientTests::test_request_query_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_timeout_cancelled", "src/treq/test/test_client.py::HTTPClientTests::test_request_timeout_fired", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_param_coercion", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_value_coercion", "src/treq/test/test_client.py::HTTPClientTests::test_request_tuple_query_values", "src/treq/test/test_client.py::HTTPClientTests::test_request_unsupported_params_combination", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_bytes_pass", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_decodedurl", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_encodedurl", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_hyperlink_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_idn", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_idn_params", "src/treq/test/test_client.py::HTTPClientTests::test_request_uri_plus_pass", "src/treq/test/test_client.py::HTTPClientTests::test_response_buffering_is_disabled_with_unbufferred_arg", "src/treq/test/test_client.py::HTTPClientTests::test_response_is_buffered", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_buffers_data", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_fires_finished_deferred", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_propagates_data_to_destination", "src/treq/test/test_client.py::BodyBufferingProtocolTests::test_propogates_connectionLost_reason", "src/treq/test/test_client.py::BufferedResponseTests::test_concurrent_receivers", "src/treq/test/test_client.py::BufferedResponseTests::test_receiver_after_finished", "src/treq/test/test_client.py::BufferedResponseTests::test_wraps_protocol", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_defaultCooperator", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_failOnByteStrings", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_failOnUnknownParams", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_failedReadWhileProducing", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_fieldsAndAttachment", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_inputClosedAtEOF", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_interface", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_knownLengthOnFile", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_missingAttachmentName", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_multipleFieldsAndAttachments", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_newLinesInParams", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_pauseProducing", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_resumeProducing", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_startProducing", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_stopProducing", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_twoFields", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_unicodeAttachmentName", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_unicodeString", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_unknownLength", "src/treq/test/test_multipart.py::MultiPartProducerTestCase::test_worksWithCgi", "src/treq/test/test_multipart.py::LengthConsumerTestCase::test_scalarsUpdateCounter", "src/treq/test/test_multipart.py::LengthConsumerTestCase::test_stringUpdatesCounter" ]
{ "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-01-16 20:18:27+00:00
mit
6,117
twisted__treq-348
diff --git a/changelog.d/347.feature.rst b/changelog.d/347.feature.rst new file mode 100644 index 0000000..05bff3b --- /dev/null +++ b/changelog.d/347.feature.rst @@ -0,0 +1,1 @@ +When the collector passed to ``treq.collect(response, collector)`` throws an exception, that error will now be returned to the caller of ``collect()`` via the result ``Deferred``, and the underlying HTTP transport will be closed. diff --git a/src/treq/content.py b/src/treq/content.py index 36219f5..8982ce9 100644 --- a/src/treq/content.py +++ b/src/treq/content.py @@ -2,7 +2,7 @@ import cgi import json from twisted.internet.defer import Deferred, succeed - +from twisted.python.failure import Failure from twisted.internet.protocol import Protocol from twisted.web.client import ResponseDone from twisted.web.http import PotentialDataLoss @@ -30,9 +30,16 @@ class _BodyCollector(Protocol): self.collector = collector def dataReceived(self, data): - self.collector(data) + try: + self.collector(data) + except BaseException: + self.transport.loseConnection() + self.finished.errback(Failure()) + self.finished = None def connectionLost(self, reason): + if self.finished is None: + return if reason.check(ResponseDone): self.finished.callback(None) elif reason.check(PotentialDataLoss): @@ -48,9 +55,13 @@ def collect(response, collector): This function may only be called **once** for a given response. + If the ``collector`` raises an exception, it will be set as the error value + on response ``Deferred`` returned from this function, and the underlying + HTTP transport will be closed. + :param IResponse response: The HTTP response to collect the body from. - :param collector: A callable to be called each time data is available - from the response body. + :param collector: A callable to be called each time data is available from + the response body. :type collector: single argument callable :rtype: Deferred that fires with None when the entire body has been read.
twisted/treq
4b09044b38f4502de3d3dd00b62d6d9717b2fbc1
diff --git a/src/treq/test/test_content.py b/src/treq/test/test_content.py index 9acb9d7..0d83ddf 100644 --- a/src/treq/test/test_content.py +++ b/src/treq/test/test_content.py @@ -2,13 +2,17 @@ from unittest import mock from twisted.python.failure import Failure +from twisted.internet.error import ConnectionDone from twisted.trial.unittest import TestCase from twisted.web.http_headers import Headers from twisted.web.client import ResponseDone, ResponseFailed from twisted.web.http import PotentialDataLoss +from twisted.web.resource import Resource +from twisted.web.server import NOT_DONE_YET from treq import collect, content, json_content, text_content from treq.client import _BufferedResponse +from treq.testing import StubTreq class ContentTests(TestCase): @@ -215,3 +219,54 @@ class ContentTests(TestCase): self.protocol.connectionLost(Failure(ResponseDone())) self.assertEqual(self.successResultOf(d), u'ᚠᚡ') + + +class UnfinishedResponse(Resource): + """Write some data, but never finish.""" + + isLeaf = True + + def __init__(self): + Resource.__init__(self) + # Track how requests finished. + self.request_finishes = [] + + def render(self, request): + request.write(b"HELLO") + request.notifyFinish().addBoth(self.request_finishes.append) + return NOT_DONE_YET + + +class MoreRealisticContentTests(TestCase): + """Tests involving less mocking.""" + + def test_exception_handling(self): + """ + An exception in the collector function: + + 1. Always gets returned in the result ``Deferred`` from + ``treq.collect()``. + + 2. Closes the transport. + """ + resource = UnfinishedResponse() + stub = StubTreq(resource) + response = self.successResultOf(stub.request("GET", "http://127.0.0.1/")) + self.assertEqual(response.code, 200) + + def error(data): + 1 / 0 + + d = collect(response, error) + + # Exceptions in the collector are passed on to the caller via the + # response Deferred: + self.failureResultOf(d, ZeroDivisionError) + + # An exception in the protocol results in the transport for the request + # being closed. + stub.flush() + self.assertEqual(len(resource.request_finishes), 1) + self.assertIsInstance( + resource.request_finishes[0].value, ConnectionDone + )
treq.collect() should close the HTTP transport when the collector function throws an exception If the collector function throws an exception, that means there is no way to handle remaining body data. In some cases this may actually be a deliberate indication that the response is no good; for example, I implemented a length-constrained variant of `treq.content()`, and if the body exceeds that it's indication of a buggy or malicious server. As such, the only reasonable thing to do in this situation is to close the transport.
0.0
4b09044b38f4502de3d3dd00b62d6d9717b2fbc1
[ "src/treq/test/test_content.py::MoreRealisticContentTests::test_exception_handling" ]
[ "src/treq/test/test_content.py::ContentTests::test_collect", "src/treq/test/test_content.py::ContentTests::test_collect_0_length", "src/treq/test/test_content.py::ContentTests::test_collect_failure", "src/treq/test/test_content.py::ContentTests::test_collect_failure_potential_data_loss", "src/treq/test/test_content.py::ContentTests::test_content", "src/treq/test/test_content.py::ContentTests::test_content_application_json_default_encoding", "src/treq/test/test_content.py::ContentTests::test_content_cached", "src/treq/test/test_content.py::ContentTests::test_content_multiple_waiters", "src/treq/test/test_content.py::ContentTests::test_json_content", "src/treq/test/test_content.py::ContentTests::test_json_content_unicode", "src/treq/test/test_content.py::ContentTests::test_json_content_utf16", "src/treq/test/test_content.py::ContentTests::test_text_content", "src/treq/test/test_content.py::ContentTests::test_text_content_default_encoding_no_header", "src/treq/test/test_content.py::ContentTests::test_text_content_default_encoding_no_param", "src/treq/test/test_content.py::ContentTests::test_text_content_unicode_headers" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-07-15 15:29:57+00:00
mit
6,118
twisted__tubes-78
diff --git a/tubes/protocol.py b/tubes/protocol.py index a5212fb..ec82031 100644 --- a/tubes/protocol.py +++ b/tubes/protocol.py @@ -20,8 +20,11 @@ from .itube import StopFlowCalled, IDrain, IFount, ISegment from .listening import Flow from twisted.python.failure import Failure -from twisted.internet.interfaces import IPushProducer, IListeningPort +from twisted.internet.interfaces import ( + IPushProducer, IListeningPort, IHalfCloseableProtocol +) from twisted.internet.protocol import Protocol as _Protocol +from twisted.internet.error import ConnectionDone if 0: # Workaround for inability of pydoctor to resolve references. @@ -206,6 +209,7 @@ class _TransportFount(object): +@implementer(IHalfCloseableProtocol) class _ProtocolPlumbing(_Protocol): """ An adapter between an L{ITransport} and L{IFount} / L{IDrain} interfaces. @@ -274,6 +278,22 @@ class _ProtocolPlumbing(_Protocol): self._drain.fount.stopFlow() + def readConnectionLost(self): + """ + An end-of-file was received. + """ + self._fount.drain.flowStopped(Failure(ConnectionDone())) + self._fount.drain = None + + + def writeConnectionLost(self): + """ + The write output was closed. + """ + self._drain.fount.stopFlow() + self._drain.fount = None + + def _factoryFromFlow(flow): """
twisted/tubes
685a112141021b52b4f51d91c4bf11773cc6911b
diff --git a/tubes/test/test_protocol.py b/tubes/test/test_protocol.py index 7eb4b3e..5450278 100644 --- a/tubes/test/test_protocol.py +++ b/tubes/test/test_protocol.py @@ -7,12 +7,16 @@ Tests for L{tubes.protocol}. """ from zope.interface import implementer +from zope.interface.verify import verifyObject from twisted.trial.unittest import SynchronousTestCase as TestCase from twisted.python.failure import Failure from twisted.test.proto_helpers import StringTransport -from twisted.internet.interfaces import IStreamServerEndpoint +from twisted.internet.interfaces import ( + IStreamServerEndpoint, IHalfCloseableProtocol +) +from twisted.internet.error import ConnectionDone from ..protocol import flowFountFromEndpoint, flowFromEndpoint from ..tube import tube, series @@ -404,6 +408,72 @@ class FlowListenerTests(TestCase): self.assertEqual(ports[0].currentlyProducing, True) + def test_readConnectionLost(self): + """ + The protocol created by L{flowFountFromEndpoint} provides half-close + support, and when it receives an EOF (i.e.: C{readConnectionLost}) it + will signal the end of the flow to its fount's drain, but not to its + drain's fount. + """ + endpoint, ports = fakeEndpointWithPorts() + fffep = flowFountFromEndpoint(endpoint) + fffep.callback(None) + flowFount = self.successResultOf(fffep) + protocol = ports[0].factory.buildProtocol(None) + verifyObject(IHalfCloseableProtocol, protocol) + aTransport = StringTransport() + protocol.makeConnection(aTransport) + accepted = FakeDrain() + flowFount.flowTo(accepted) + [flow] = accepted.received + receivedData = FakeDrain() + dataSender = FakeFount() + flow.fount.flowTo(receivedData) + dataSender.flowTo(flow.drain) + self.assertEqual(len(receivedData.stopped), 0) + self.assertEqual(dataSender.flowIsStopped, False) + protocol.readConnectionLost() + self.assertEqual(len(receivedData.stopped), 1) + self.assertIsInstance(receivedData.stopped[0], Failure) + receivedData.stopped[0].trap(ConnectionDone) + self.assertEqual(dataSender.flowIsStopped, False) + protocol.connectionLost(ConnectionDone()) + self.assertEqual(len(receivedData.stopped), 1) + self.assertEqual(dataSender.flowIsStopped, True) + + + def test_writeConnectionLost(self): + """ + The protocol created by L{flowFountFromEndpoint} provides half-close + support, and when it receives an EOF (i.e.: C{writeConnectionLost}) it + will signal the end of the flow to its drain's fount, but not to its + fount's drain. + """ + endpoint, ports = fakeEndpointWithPorts() + fffep = flowFountFromEndpoint(endpoint) + fffep.callback(None) + flowFount = self.successResultOf(fffep) + protocol = ports[0].factory.buildProtocol(None) + verifyObject(IHalfCloseableProtocol, protocol) + aTransport = StringTransport() + protocol.makeConnection(aTransport) + accepted = FakeDrain() + flowFount.flowTo(accepted) + [flow] = accepted.received + receivedData = FakeDrain() + dataSender = FakeFount() + flow.fount.flowTo(receivedData) + dataSender.flowTo(flow.drain) + self.assertEqual(len(receivedData.stopped), 0) + self.assertEqual(dataSender.flowIsStopped, False) + protocol.writeConnectionLost() + self.assertEqual(len(receivedData.stopped), 0) + self.assertEqual(dataSender.flowIsStopped, 1) + protocol.connectionLost(ConnectionDone()) + self.assertEqual(len(receivedData.stopped), 1) + self.assertEqual(dataSender.flowIsStopped, 1) + + def test_backpressure(self): """ When the L{IFount} returned by L{flowFountFromEndpoint} is paused, it diff --git a/tubes/test/util.py b/tubes/test/util.py index 054a928..9e291d1 100644 --- a/tubes/test/util.py +++ b/tubes/test/util.py @@ -137,6 +137,7 @@ class FakeFount(object): flowIsPaused = 0 flowIsStopped = False + def __init__(self, outputType=None): self._pauser = Pauser(self._actuallyPause, self._actuallyResume) self.outputType = outputType @@ -170,9 +171,9 @@ class FakeFount(object): def stopFlow(self): """ - Record that the flow was stopped by setting C{flowIsStopped}. + Record that the flow was stopped by incrementing C{flowIsStopped}. """ - self.flowIsStopped = True + self.flowIsStopped += 1 def _actuallyPause(self):
_ProtocolPlumbing does not implement IHalfCloseableProtocol, leading to the misleading appearance of horrifying race conditions during testing If you were to make a script of JSON commands for `fanchat` and use the `stdio` endpoint to hook them together into a little test, then do something like ```console $ cat fcscript.txt | python fanchat.py ``` you would get very weird non-deterministic behavior where half of the output would vanish. This is because, in the absence of a protocol providing `IHalfCloseableProtocol` as the protocol, "EOF" means "shut down both read *and write* halves of the connection". Understandably, further writes to the `StandardIO` would be lost. To remedy this, `IHalfCloseableProtocol` should be implemented - which, by the way, would also allow us to separate the `fount` and `drain` termination on transports which support such a distinction.
0.0
685a112141021b52b4f51d91c4bf11773cc6911b
[ "tubes/test/test_protocol.py::FlowListenerTests::test_readConnectionLost", "tubes/test/test_protocol.py::FlowListenerTests::test_writeConnectionLost" ]
[ "tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsFlowStopped", "tubes/test/test_protocol.py::FlowConnectorTests::test_connectionLostSendsStopFlow", "tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowing", "tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedBeforeFlowingThenFlowTo", "tubes/test/test_protocol.py::FlowConnectorTests::test_dataReceivedWhenFlowingToNone", "tubes/test/test_protocol.py::FlowConnectorTests::test_drainReceivingWritesToTransport", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowStoppedStopsConnection", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowToDeliversData", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowToSetsDrain", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFrom", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFromAttribute", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowingFromTwice", "tubes/test/test_protocol.py::FlowConnectorTests::test_flowingToNoneAfterFlowingToSomething", "tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromOtherDrain", "tubes/test/test_protocol.py::FlowConnectorTests::test_pauseUnpauseFromTransport", "tubes/test/test_protocol.py::FlowConnectorTests::test_stopFlowStopsConnection", "tubes/test/test_protocol.py::FlowConnectorTests::test_stopProducing", "tubes/test/test_protocol.py::FlowListenerTests::test_acceptAfterDeferredButBeforeFlowTo", "tubes/test/test_protocol.py::FlowListenerTests::test_acceptBeforeActuallyListening", "tubes/test/test_protocol.py::FlowListenerTests::test_backpressure", "tubes/test/test_protocol.py::FlowListenerTests::test_fromEndpoint", "tubes/test/test_protocol.py::FlowListenerTests::test_oneConnectionAccepted", "tubes/test/test_protocol.py::FlowListenerTests::test_stopping" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-11-12 07:19:42+00:00
mit
6,119
twisted__twisted-11603
diff --git a/src/twisted/internet/base.py b/src/twisted/internet/base.py index 1cd2c98ee4..4aab1c70d2 100644 --- a/src/twisted/internet/base.py +++ b/src/twisted/internet/base.py @@ -80,6 +80,9 @@ class DelayedCall: debug = False _repr: Optional[str] = None + # In debug mode, the call stack at the time of instantiation. + creator: Optional[Sequence[str]] = None + def __init__( self, time: float, @@ -265,7 +268,7 @@ class DelayedCall: ) L.append(")") - if self.debug: + if self.creator is not None: L.append("\n\ntraceback at creation: \n\n%s" % (" ".join(self.creator))) L.append(">") @@ -990,8 +993,8 @@ class ReactorBase(PluggableResolverMixin): call.called = 1 call.func(*call.args, **call.kw) except BaseException: - log.deferr() - if hasattr(call, "creator"): + log.err() + if call.creator is not None: e = "\n" e += ( " C: previous exception occurred in " diff --git a/src/twisted/newsfragments/8306.bugfix b/src/twisted/newsfragments/8306.bugfix new file mode 100644 index 0000000000..455bc56485 --- /dev/null +++ b/src/twisted/newsfragments/8306.bugfix @@ -0,0 +1,1 @@ +``twisted.internet.base.DelayedCall.__repr__`` will no longer raise ``AttributeError`` if the ``DelayedCall`` was created before debug mode was enabled. As a side-effect, ``twisted.internet.base.DelayedCall.creator`` is now defined as ``None`` in cases where previously it was undefined.
twisted/twisted
8ebcdc2f5a414a5ac1fdf5ee4aed62116af219e3
diff --git a/src/twisted/internet/test/test_base.py b/src/twisted/internet/test/test_base.py index 3f8ecf08c2..31a32362e8 100644 --- a/src/twisted/internet/test/test_base.py +++ b/src/twisted/internet/test/test_base.py @@ -356,6 +356,17 @@ class DelayedCallNoDebugTests(DelayedCallMixin, TestCase): ) self.assertEqual(str(dc), expected) + def test_switchToDebug(self): + """ + If L{DelayedCall.debug} changes from C{0} to C{1} between + L{DelayeCall.__init__} and L{DelayedCall.__repr__} then + L{DelayedCall.__repr__} returns a string that does not include the + creator stack. + """ + dc = DelayedCall(3, lambda: None, (), {}, nothing, nothing, lambda: 2) + dc.debug = 1 + self.assertNotIn("traceback at creation", repr(dc)) + class DelayedCallDebugTests(DelayedCallMixin, TestCase): """ @@ -383,6 +394,17 @@ class DelayedCallDebugTests(DelayedCallMixin, TestCase): ) self.assertRegex(str(dc), expectedRegexp) + def test_switchFromDebug(self): + """ + If L{DelayedCall.debug} changes from C{1} to C{0} between + L{DelayeCall.__init__} and L{DelayedCall.__repr__} then + L{DelayedCall.__repr__} returns a string that includes the creator + stack (we captured it, we might as well display it). + """ + dc = DelayedCall(3, lambda: None, (), {}, nothing, nothing, lambda: 2) + dc.debug = 0 + self.assertIn("traceback at creation", repr(dc)) + class TestSpySignalCapturingReactor(ReactorBase):
AttributeError: 'DelayedCall' object has no attribute 'creator' |<img alt="allenap's avatar" src="https://avatars.githubusercontent.com/u/0?s=50" width="50" height="50">| allenap reported| |-|-| |Trac ID|trac#8306| |Type|defect| |Created|2016-04-26 16:04:05Z| ``` Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from twisted.internet.base import DelayedCall >>> dc = DelayedCall(1, lambda: None, (), {}, lambda dc: None, lambda dc: None) >>> dc.debug = True >>> str(dc) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ".../twisted/internet/base.py", line 206, in __str__ L.append("\n\ntraceback at creation: \n\n%s" % (' '.join(self.creator))) AttributeError: 'DelayedCall' object has no attribute 'creator' ``` ``` $ tail -n1 twisted/_version.py version = versions.Version('twisted', 16, 1, 1) ``` <details><summary>Searchable metadata</summary> ``` trac-id__8306 8306 type__defect defect reporter__allenap allenap priority__normal normal milestone__None None branch__ branch_author__ status__new new resolution__None None component__core core keywords__None None time__1461686645106304 1461686645106304 changetime__1462290530743285 1462290530743285 version__None None owner__None None ``` </details>
0.0
8ebcdc2f5a414a5ac1fdf5ee4aed62116af219e3
[ "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_switchToDebug", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_switchFromDebug" ]
[ "src/twisted/internet/test/test_base.py::ThreadedResolverTests::test_failure", "src/twisted/internet/test/test_base.py::ThreadedResolverTests::test_resolverGivenStr", "src/twisted/internet/test/test_base.py::ThreadedResolverTests::test_success", "src/twisted/internet/test/test_base.py::ThreadedResolverTests::test_timeout", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_eq", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_ge", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_gt", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_le", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_lt", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_ne", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_repr", "src/twisted/internet/test/test_base.py::DelayedCallNoDebugTests::test_str", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_eq", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_ge", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_gt", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_le", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_lt", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_ne", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_repr", "src/twisted/internet/test/test_base.py::DelayedCallDebugTests::test_str", "src/twisted/internet/test/test_base.py::ReactorBaseSignalTests::test_captureSIGINT", "src/twisted/internet/test/test_base.py::ReactorBaseSignalTests::test_captureSIGTERM", "src/twisted/internet/test/test_base.py::ReactorBaseSignalTests::test_exitSignalDefaultsToNone" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-08-18 15:51:30+00:00
mit
6,120
twisted__twisted-11639
diff --git a/src/twisted/conch/manhole.py b/src/twisted/conch/manhole.py index f26e5de974..5bf2f817a4 100644 --- a/src/twisted/conch/manhole.py +++ b/src/twisted/conch/manhole.py @@ -17,11 +17,15 @@ import code import sys import tokenize from io import BytesIO +from traceback import format_exception +from types import TracebackType +from typing import Type from twisted.conch import recvline from twisted.internet import defer from twisted.python.compat import _get_async_param from twisted.python.htmlizer import TokenPrinter +from twisted.python.monkey import MonkeyPatcher class FileWrapper: @@ -71,6 +75,11 @@ class ManholeInterpreter(code.InteractiveInterpreter): self.filename = filename self.resetBuffer() + self.monkeyPatcher = MonkeyPatcher() + self.monkeyPatcher.addPatch(sys, "displayhook", self.displayhook) + self.monkeyPatcher.addPatch(sys, "excepthook", self.excepthook) + self.monkeyPatcher.addPatch(sys, "stdout", FileWrapper(self.handler)) + def resetBuffer(self): """ Reset the input buffer. @@ -104,15 +113,20 @@ class ManholeInterpreter(code.InteractiveInterpreter): return more def runcode(self, *a, **kw): - orighook, sys.displayhook = sys.displayhook, self.displayhook - try: - origout, sys.stdout = sys.stdout, FileWrapper(self.handler) - try: - code.InteractiveInterpreter.runcode(self, *a, **kw) - finally: - sys.stdout = origout - finally: - sys.displayhook = orighook + with self.monkeyPatcher: + code.InteractiveInterpreter.runcode(self, *a, **kw) + + def excepthook( + self, + excType: Type[BaseException], + excValue: BaseException, + excTraceback: TracebackType, + ) -> None: + """ + Format exception tracebacks and write them to the output handler. + """ + lines = format_exception(excType, excValue, excTraceback.tb_next) + self.write("".join(lines)) def displayhook(self, obj): self.locals["_"] = obj diff --git a/src/twisted/conch/newsfragments/11638.bugfix b/src/twisted/conch/newsfragments/11638.bugfix new file mode 100644 index 0000000000..d97998919b --- /dev/null +++ b/src/twisted/conch/newsfragments/11638.bugfix @@ -0,0 +1,1 @@ +twisted.conch.manhole.ManholeInterpreter now captures tracebacks even if sys.excepthook has been modified. diff --git a/src/twisted/python/monkey.py b/src/twisted/python/monkey.py index dbf2dca7d8..08ccef2ac1 100644 --- a/src/twisted/python/monkey.py +++ b/src/twisted/python/monkey.py @@ -48,6 +48,8 @@ class MonkeyPatcher: self._originals.append((obj, name, getattr(obj, name))) setattr(obj, name, value) + __enter__ = patch + def restore(self): """ Restore all original values to any patched objects. @@ -56,6 +58,9 @@ class MonkeyPatcher: obj, name, value = self._originals.pop() setattr(obj, name, value) + def __exit__(self, excType=None, excValue=None, excTraceback=None): + self.restore() + def runWithPatches(self, f, *args, **kw): """ Apply each patch already specified. Then run the function f with the
twisted/twisted
d415545aca4697ad033f5bc135d9afa8fe470309
diff --git a/src/twisted/conch/test/test_manhole.py b/src/twisted/conch/test/test_manhole.py index ef07bd24bc..54159af8af 100644 --- a/src/twisted/conch/test/test_manhole.py +++ b/src/twisted/conch/test/test_manhole.py @@ -8,6 +8,7 @@ Tests for L{twisted.conch.manhole}. """ +import sys import traceback from typing import Optional @@ -148,9 +149,6 @@ class WriterTests(unittest.TestCase): class ManholeLoopbackMixin: serverProtocol = manhole.ColoredManhole - def wfd(self, d): - return defer.waitForDeferred(d) - def test_SimpleExpression(self): """ Evaluate simple expression. @@ -244,10 +242,21 @@ class ManholeLoopbackMixin: + defaultFunctionName.encode("utf-8"), b"Exception: foo bar baz", b">>> done", - ] + ], ) - return done.addCallback(finished) + done.addCallback(finished) + return done + + def test_ExceptionWithCustomExcepthook( + self, + ): + """ + Raised exceptions are handled the same way even if L{sys.excepthook} + has been modified from its original value. + """ + self.patch(sys, "excepthook", lambda *args: None) + return self.test_Exception() def test_ControlC(self): """ diff --git a/src/twisted/conch/test/test_recvline.py b/src/twisted/conch/test/test_recvline.py index 03ac465988..3fd0157e2d 100644 --- a/src/twisted/conch/test/test_recvline.py +++ b/src/twisted/conch/test/test_recvline.py @@ -473,15 +473,7 @@ class _BaseMixin: def _assertBuffer(self, lines): receivedLines = self.recvlineClient.__bytes__().splitlines() expectedLines = lines + ([b""] * (self.HEIGHT - len(lines) - 1)) - self.assertEqual(len(receivedLines), len(expectedLines)) - for i in range(len(receivedLines)): - self.assertEqual( - receivedLines[i], - expectedLines[i], - b"".join(receivedLines[max(0, i - 1) : i + 1]) - + b" != " - + b"".join(expectedLines[max(0, i - 1) : i + 1]), - ) + self.assertEqual(receivedLines, expectedLines) def _trivialTest(self, inputLine, output): done = self.recvlineClient.expect(b"done") diff --git a/src/twisted/test/test_monkey.py b/src/twisted/test/test_monkey.py index 6bae7170cc..40bae09527 100644 --- a/src/twisted/test/test_monkey.py +++ b/src/twisted/test/test_monkey.py @@ -152,3 +152,22 @@ class MonkeyPatcherTests(unittest.SynchronousTestCase): self.assertRaises(RuntimeError, self.monkeyPatcher.runWithPatches, _) self.assertEqual(self.testObject.foo, self.originalObject.foo) self.assertEqual(self.testObject.bar, self.originalObject.bar) + + def test_contextManager(self): + """ + L{MonkeyPatcher} is a context manager that applies its patches on + entry and restore original values on exit. + """ + self.monkeyPatcher.addPatch(self.testObject, "foo", "patched value") + with self.monkeyPatcher: + self.assertEqual(self.testObject.foo, "patched value") + self.assertEqual(self.testObject.foo, self.originalObject.foo) + + def test_contextManagerPropagatesExceptions(self): + """ + Exceptions propagate through the L{MonkeyPatcher} context-manager + exit method. + """ + with self.assertRaises(RuntimeError): + with self.monkeyPatcher: + raise RuntimeError("something")
twisted.conch.manhole fails to display tracebacks correctly if sys.excepthook has been modified manhole inherits from `code.InteractiveInterpreter` to handle some of its REPL-y behavior. `code.InteractiveInterpreter` varies some of its behavior on whether `sys.excepthook` has been fiddled with. manhole assumes it will _always_ get the behavior you get if `sys.excepthook` hasn't been tampered with so it breaks (and so does one of its unit tests) if it has been tampered with. This is an obscure hook that's mostly left alone (which is why so many years passed before it was a problem, I suppose). An example of a library that does stuff with `sys.excepthook` is `exceptiongroup`. It turns out Hypothesis depends on `exceptiongroup` so if we try to use Hypothesis in Twisted then `sys.excepthook` gets tampered with an manhole tests start failing. Here's an exceptiongroup bug report - https://github.com/agronholm/exceptiongroup/issues/26 - but whether this is fixable in exceptiongroup or not is unclear (seems like perhaps not). Probably the stdlib should stop having this wonky conditional but ...
0.0
d415545aca4697ad033f5bc135d9afa8fe470309
[ "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_Exception", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_ExceptionWithCustomExcepthook", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_contextManager", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_contextManagerPropagatesExceptions" ]
[ "src/twisted/conch/test/test_manhole.py::ManholeInterpreterTests::test_resetBuffer", "src/twisted/conch/test/test_manhole.py::ManholeProtocolTests::test_interruptResetsInterpreterBuffer", "src/twisted/conch/test/test_manhole.py::WriterTests::test_ClassDefinition", "src/twisted/conch/test/test_manhole.py::WriterTests::test_DoubleQuoteString", "src/twisted/conch/test/test_manhole.py::WriterTests::test_FunctionDefinition", "src/twisted/conch/test/test_manhole.py::WriterTests::test_Integer", "src/twisted/conch/test/test_manhole.py::WriterTests::test_SingleQuoteString", "src/twisted/conch/test/test_manhole.py::WriterTests::test_TripleDoubleQuotedString", "src/twisted/conch/test/test_manhole.py::WriterTests::test_TripleSingleQuotedString", "src/twisted/conch/test/test_manhole.py::WriterTests::test_bytes", "src/twisted/conch/test/test_manhole.py::WriterTests::test_identicalOutput", "src/twisted/conch/test/test_manhole.py::WriterTests::test_unicode", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_ClassDefinition", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_ControlBackslash", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_ControlC", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_ControlL", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_FunctionDefinition", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_SimpleExpression", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_TripleQuoteLineContinuation", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_controlA", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_controlD", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_controlE", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_deferred", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackTelnetTests::test_interruptDuringContinuation", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_ClassDefinition", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_ControlBackslash", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_ControlC", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_ControlL", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_Exception", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_ExceptionWithCustomExcepthook", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_FunctionDefinition", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_SimpleExpression", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_TripleQuoteLineContinuation", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_controlA", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_controlD", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_controlE", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_deferred", "src/twisted/conch/test/test_manhole.py::ManholeLoopbackStdioTests::test_interruptDuringContinuation", "src/twisted/conch/test/test_manhole.py::ManholeMainTests::test_mainClassNotFound", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_backspace", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_delete", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_end", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_home", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_horizontalArrows", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_insert", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_newline", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_printableCharacters", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_typeover", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_unprintableCharacters", "src/twisted/conch/test/test_recvline.py::ArrowsTests::test_verticalArrows", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testBackspace", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testDelete", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testEnd", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testHome", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testInsert", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testLeftArrow", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testRightArrow", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testSimple", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackTelnetTests::testTypeover", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testBackspace", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testDelete", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testEnd", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testHome", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testInsert", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testLeftArrow", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testRightArrow", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testSimple", "src/twisted/conch/test/test_recvline.py::RecvlineLoopbackStdioTests::testTypeover", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackTelnetTests::testDownArrow", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackTelnetTests::testUpArrow", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackTelnetTests::test_DownArrowToPartialLineInHistory", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackStdioTests::testDownArrow", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackStdioTests::testUpArrow", "src/twisted/conch/test/test_recvline.py::HistoricRecvlineLoopbackStdioTests::test_DownArrowToPartialLineInHistory", "src/twisted/conch/test/test_recvline.py::TransportSequenceTests::test_invalidSequence", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_constructWithPatches", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_empty", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_patchAlreadyPatched", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_patchExisting", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_patchNonExisting", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_repeatedRunWithPatches", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_restoreTwiceIsANoOp", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_runWithPatchesDecoration", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_runWithPatchesRestores", "src/twisted/test/test_monkey.py::MonkeyPatcherTests::test_runWithPatchesRestoresOnException" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-09-06 18:24:17+00:00
mit
6,121
twisted__twisted-11662
diff --git a/src/twisted/trial/_dist/stream.py b/src/twisted/trial/_dist/stream.py new file mode 100644 index 0000000000..3a87c2ee1d --- /dev/null +++ b/src/twisted/trial/_dist/stream.py @@ -0,0 +1,99 @@ +""" +Buffer string streams +""" + +from itertools import count +from typing import Dict, Iterator, List, TypeVar + +from attrs import Factory, define + +from twisted.protocols.amp import AMP, Command, Integer, Unicode + +T = TypeVar("T") + + +class StreamOpen(Command): + """ + Open a new stream. + """ + + response = [(b"streamId", Integer())] + + +class StreamWrite(Command): + """ + Write a chunk of data to a stream. + """ + + arguments = [ + (b"streamId", Integer()), + (b"data", Unicode()), + ] + + +@define +class StreamReceiver: + """ + Buffering de-multiplexing string stream receiver. + """ + + _counter: Iterator[int] = count() + _streams: Dict[int, List[str]] = Factory(dict) + + def open(self) -> int: + """ + Open a new stream and return its unique identifier. + """ + newId = next(self._counter) + self._streams[newId] = [] + return newId + + def write(self, streamId: int, chunk: str) -> None: + """ + Write to an open stream using its unique identifier. + + :raise KeyError: If there is no such open stream. + """ + self._streams[streamId].append(chunk) + + def finish(self, streamId: int) -> List[str]: + """ + Indicate an open stream may receive no further data and return all of + its current contents. + + :raise KeyError: If there is no such open stream. + """ + return self._streams.pop(streamId) + + +def chunk(data: str, chunkSize: int) -> Iterator[str]: + """ + Break a string into pieces of no more than ``chunkSize`` length. + + :param data: The string. + + :param chunkSize: The maximum length of the resulting pieces. All pieces + except possibly the last will be this length. + + :return: The pieces. + """ + pos = 0 + while pos < len(data): + yield data[pos : pos + chunkSize] + pos += chunkSize + + +async def stream(amp: AMP, chunks: Iterator[str]) -> int: + """ + Send the given stream chunks, one by one, over the given connection. + + The chunks are sent using L{StreamWrite} over a stream opened using + L{StreamOpen}. + + :return: The identifier of the stream over which the chunks were sent. + """ + streamId = (await amp.callRemote(StreamOpen))["streamId"] + + for oneChunk in chunks: + await amp.callRemote(StreamWrite, streamId=streamId, data=oneChunk) + return streamId # type: ignore[no-any-return]
twisted/twisted
7c00738a0c24032070ce92304b4c8b887666c0fc
diff --git a/src/twisted/trial/_dist/test/test_stream.py b/src/twisted/trial/_dist/test/test_stream.py new file mode 100644 index 0000000000..2c506e08a0 --- /dev/null +++ b/src/twisted/trial/_dist/test/test_stream.py @@ -0,0 +1,206 @@ +""" +Tests for L{twisted.trial._dist.stream}. +""" + +from random import Random +from typing import Awaitable, Dict, List, TypeVar, Union + +from hamcrest import ( + all_of, + assert_that, + calling, + equal_to, + has_length, + is_, + less_than_or_equal_to, + raises, +) +from hypothesis import given +from hypothesis.strategies import integers, just, lists, randoms, text + +from twisted.internet.defer import Deferred, fail +from twisted.internet.interfaces import IProtocol +from twisted.internet.protocol import Protocol +from twisted.protocols.amp import AMP +from twisted.python.failure import Failure +from twisted.test.iosim import FakeTransport, connect +from twisted.trial.unittest import SynchronousTestCase +from ..stream import StreamOpen, StreamReceiver, StreamWrite, chunk, stream +from .matchers import HasSum, IsSequenceOf + +T = TypeVar("T") + + +class StreamReceiverTests(SynchronousTestCase): + """ + Tests for L{StreamReceiver} + """ + + @given(lists(lists(text())), randoms()) + def test_streamReceived(self, streams: List[str], random: Random) -> None: + """ + All data passed to L{StreamReceiver.write} is returned by a call to + L{StreamReceiver.finish} with a matching C{streamId} . + """ + receiver = StreamReceiver() + streamIds = [receiver.open() for _ in streams] + + # uncorrelate the results with open() order + random.shuffle(streamIds) + + expectedData = dict(zip(streamIds, streams)) + for streamId, strings in expectedData.items(): + for s in strings: + receiver.write(streamId, s) + + # uncorrelate the results with write() order + random.shuffle(streamIds) + + actualData = {streamId: receiver.finish(streamId) for streamId in streamIds} + + assert_that(actualData, is_(equal_to(expectedData))) + + @given(integers(), just("data")) + def test_writeBadStreamId(self, streamId: int, data: str) -> None: + """ + L{StreamReceiver.write} raises L{KeyError} if called with a + streamId not associated with an open stream. + """ + receiver = StreamReceiver() + assert_that(calling(receiver.write).with_args(streamId, data), raises(KeyError)) + + @given(integers()) + def test_badFinishStreamId(self, streamId: int) -> None: + """ + L{StreamReceiver.finish} raises L{KeyError} if called with a + streamId not associated with an open stream. + """ + receiver = StreamReceiver() + assert_that(calling(receiver.finish).with_args(streamId), raises(KeyError)) + + def test_finishRemovesStream(self) -> None: + """ + L{StreamReceiver.finish} removes the identified stream. + """ + receiver = StreamReceiver() + streamId = receiver.open() + receiver.finish(streamId) + assert_that(calling(receiver.finish).with_args(streamId), raises(KeyError)) + + +class ChunkTests(SynchronousTestCase): + """ + Tests for ``chunk``. + """ + + @given(data=text(), chunkSize=integers(min_value=1)) + def test_chunk(self, data, chunkSize): + """ + L{chunk} returns an iterable of L{str} where each element is no + longer than the given limit. The concatenation of the strings is also + equal to the original input string. + """ + chunks = list(chunk(data, chunkSize)) + assert_that( + chunks, + all_of( + IsSequenceOf( + has_length(less_than_or_equal_to(chunkSize)), + ), + HasSum(equal_to(data), data[:0]), + ), + ) + + +class AMPStreamReceiver(AMP): + """ + A simple AMP interface to L{StreamReceiver}. + """ + + def __init__(self, streams: StreamReceiver) -> None: + self.streams = streams + + @StreamOpen.responder + def streamOpen(self) -> Dict[str, object]: + return {"streamId": self.streams.open()} + + @StreamWrite.responder + def streamWrite(self, streamId: int, data: str) -> Dict[str, object]: + self.streams.write(streamId, data) + return {} + + +def interact(server: IProtocol, client: IProtocol, interaction: Awaitable[T]) -> T: + """ + Let C{server} and C{client} exchange bytes while C{interaction} runs. + """ + finished = False + result: Union[Failure, T] + + async def to_coroutine() -> T: + return await interaction + + def collect_result(r: Union[Failure, T]) -> None: + nonlocal result, finished + finished = True + result = r + + pump = connect( + server, + FakeTransport(server, isServer=True), + client, + FakeTransport(client, isServer=False), + ) + interacting = Deferred.fromCoroutine(to_coroutine()) + interacting.addBoth(collect_result) + + pump.flush() + + if finished: + if isinstance(result, Failure): + result.raiseException() + return result + raise Exception("Interaction failed to produce a result.") + + +class InteractTests(SynchronousTestCase): + """ + Tests for the test helper L{interact}. + """ + + def test_failure(self): + """ + If the interaction results in a failure then L{interact} raises an + exception. + """ + + class ArbitraryException(Exception): + pass + + with self.assertRaises(ArbitraryException): + interact(Protocol(), Protocol(), fail(ArbitraryException())) + + def test_incomplete(self): + """ + If the interaction fails to produce a result then L{interact} raises + an exception. + """ + with self.assertRaises(Exception): + interact(Protocol(), Protocol(), Deferred()) + + +class StreamTests(SynchronousTestCase): + """ + Tests for L{stream}. + """ + + @given(lists(text())) + def test_stream(self, chunks): + """ + All of the chunks passed to L{stream} are sent in order over a + stream using the given AMP connection. + """ + sender = AMP() + streams = StreamReceiver() + streamId = interact(AMPStreamReceiver(streams), sender, stream(sender, chunks)) + assert_that(streams.finish(streamId), is_(equal_to(chunks)))
disttrial needs some streaming helpers The fix for #10314 will involve streaming arbitrarily long strings over an AMP connection. There is no functionality in Twisted yet to support this. Add some for trial to use.
0.0
7c00738a0c24032070ce92304b4c8b887666c0fc
[ "src/twisted/trial/_dist/test/test_stream.py::StreamReceiverTests::test_badFinishStreamId", "src/twisted/trial/_dist/test/test_stream.py::StreamReceiverTests::test_finishRemovesStream", "src/twisted/trial/_dist/test/test_stream.py::StreamReceiverTests::test_streamReceived", "src/twisted/trial/_dist/test/test_stream.py::StreamReceiverTests::test_writeBadStreamId", "src/twisted/trial/_dist/test/test_stream.py::ChunkTests::test_chunk", "src/twisted/trial/_dist/test/test_stream.py::InteractTests::test_failure", "src/twisted/trial/_dist/test/test_stream.py::InteractTests::test_incomplete", "src/twisted/trial/_dist/test/test_stream.py::StreamTests::test_stream" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-09-13 12:45:19+00:00
mit
6,122
twisted__twisted-11688
diff --git a/src/twisted/web/error.py b/src/twisted/web/error.py index a741949735..cc151d4205 100644 --- a/src/twisted/web/error.py +++ b/src/twisted/web/error.py @@ -22,22 +22,20 @@ __all__ = [ from collections.abc import Sequence -from typing import cast +from typing import Optional, Union, cast from twisted.python.compat import nativeString from twisted.web._responses import RESPONSES -def _codeToMessage(code): +def _codeToMessage(code: Union[int, bytes]) -> Optional[bytes]: """ Returns the response message corresponding to an HTTP code, or None if the code is unknown or unrecognized. - @type code: L{bytes} - @param code: Refers to an HTTP status code, for example C{http.NOT_FOUND}. + @param code: HTTP status code, for example C{http.NOT_FOUND}. @return: A string message or none - @rtype: L{bytes} """ try: return RESPONSES.get(int(code)) @@ -49,17 +47,23 @@ class Error(Exception): """ A basic HTTP error. - @type status: L{bytes} @ivar status: Refers to an HTTP status code, for example C{http.NOT_FOUND}. - @type message: L{bytes} @param message: A short error message, for example "NOT FOUND". - @type response: L{bytes} @ivar response: A complete HTML document for an error page. """ - def __init__(self, code, message=None, response=None): + status: bytes + message: Optional[bytes] + response: Optional[bytes] + + def __init__( + self, + code: Union[int, bytes], + message: Optional[bytes] = None, + response: Optional[bytes] = None, + ) -> None: """ Initializes a basic exception. @@ -70,11 +74,12 @@ class Error(Exception): instead. @type message: L{bytes} - @param message: A short error message, for example "NOT FOUND". + @param message: A short error message, for example C{b"NOT FOUND"}. @type response: L{bytes} @param response: A complete HTML document for an error page. """ + message = message or _codeToMessage(code) Exception.__init__(self, code, message, response) @@ -84,24 +89,38 @@ class Error(Exception): # downloadPage gives a bytes, Agent gives an int, and it worked by # accident previously, so just make it keep working. code = b"%d" % (code,) + elif len(code) != 3 or not code.isdigit(): + # Status codes must be 3 digits. See + # https://httpwg.org/specs/rfc9110.html#status.code.extensibility + raise ValueError(f"Not a valid HTTP status code: {code!r}") self.status = code self.message = message self.response = response def __str__(self) -> str: - return nativeString(self.status + b" " + self.message) + s = self.status + if self.message: + s += b" " + self.message + return nativeString(s) class PageRedirect(Error): """ A request resulted in an HTTP redirect. - @type location: L{bytes} @ivar location: The location of the redirect which was not followed. """ - def __init__(self, code, message=None, response=None, location=None): + location: Optional[bytes] + + def __init__( + self, + code: Union[int, bytes], + message: Optional[bytes] = None, + response: Optional[bytes] = None, + location: Optional[bytes] = None, + ) -> None: """ Initializes a page redirect exception. @@ -111,7 +130,7 @@ class PageRedirect(Error): descriptive string that is used instead. @type message: L{bytes} - @param message: A short error message, for example "NOT FOUND". + @param message: A short error message, for example C{b"NOT FOUND"}. @type response: L{bytes} @param response: A complete HTML document for an error page. @@ -131,27 +150,30 @@ class InfiniteRedirection(Error): """ HTTP redirection is occurring endlessly. - @type location: L{bytes} @ivar location: The first URL in the series of redirections which was not followed. """ - def __init__(self, code, message=None, response=None, location=None): + location: Optional[bytes] + + def __init__( + self, + code: Union[int, bytes], + message: Optional[bytes] = None, + response: Optional[bytes] = None, + location: Optional[bytes] = None, + ) -> None: """ Initializes an infinite redirection exception. - @type code: L{bytes} @param code: Refers to an HTTP status code, for example C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a descriptive string that is used instead. - @type message: L{bytes} - @param message: A short error message, for example "NOT FOUND". + @param message: A short error message, for example C{b"NOT FOUND"}. - @type response: L{bytes} @param response: A complete HTML document for an error page. - @type location: L{bytes} @param location: The location response-header field value. It is an absolute URI used to redirect the receiver to a location other than the Request-URI so the request can be completed. @@ -174,7 +196,10 @@ class RedirectWithNoLocation(Error): @since: 11.1 """ - def __init__(self, code, message, uri): + message: bytes + uri: bytes + + def __init__(self, code: Union[bytes, int], message: bytes, uri: bytes) -> None: """ Initializes a page redirect exception when no location is given. diff --git a/src/twisted/web/newsfragments/10271.bugfix b/src/twisted/web/newsfragments/10271.bugfix new file mode 100644 index 0000000000..93d872fe32 --- /dev/null +++ b/src/twisted/web/newsfragments/10271.bugfix @@ -0,0 +1,1 @@ +twisted.web.error.Error.__str__ no longer raises an exception when the error's message attribute is None. Additionally, it validates that code is a plausible 3-digit HTTP status code.
twisted/twisted
59a713107d507a0e042af829ed90e6bff8a463dd
diff --git a/src/twisted/web/test/test_error.py b/src/twisted/web/test/test_error.py index d8e2b65634..f4953adddf 100644 --- a/src/twisted/web/test/test_error.py +++ b/src/twisted/web/test/test_error.py @@ -42,19 +42,29 @@ class ErrorTests(unittest.TestCase): def test_noMessageValidStatus(self): """ If no C{message} argument is passed to the L{Error} constructor and the - C{code} argument is a valid HTTP status code, C{code} is mapped to a - descriptive string to which C{message} is assigned. + C{code} argument is a valid HTTP status code, C{message} is set to the + HTTP reason phrase for C{code}. """ e = error.Error(b"200") self.assertEqual(e.message, b"OK") + self.assertEqual(str(e), "200 OK") - def test_noMessageInvalidStatus(self): + def test_noMessageForStatus(self): """ If no C{message} argument is passed to the L{Error} constructor and - C{code} isn't a valid HTTP status code, C{message} stays L{None}. + C{code} isn't a known HTTP status code, C{message} stays L{None}. """ - e = error.Error(b"InvalidCode") + e = error.Error(b"999") self.assertEqual(e.message, None) + self.assertEqual(str(e), "999") + + def test_invalidStatus(self): + """ + If C{code} isn't plausibly an HTTP status code (i.e., composed of + digits) it is rejected with L{ValueError}. + """ + with self.assertRaises(ValueError): + error.Error(b"InvalidStatus") def test_messageExists(self): """ @@ -63,6 +73,7 @@ class ErrorTests(unittest.TestCase): """ e = error.Error(b"200", b"My own message") self.assertEqual(e.message, b"My own message") + self.assertEqual(str(e), "200 My own message") def test_str(self): """ @@ -107,7 +118,7 @@ class PageRedirectTests(unittest.TestCase): If no C{message} argument is passed to the L{PageRedirect} constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}. """ - e = error.PageRedirect(b"InvalidCode", location=b"/foo") + e = error.PageRedirect(b"999", location=b"/foo") self.assertEqual(e.message, None) def test_messageExistsLocationExists(self): @@ -160,8 +171,9 @@ class InfiniteRedirectionTests(unittest.TestCase): constructor and C{code} isn't a valid HTTP status code, C{message} stays L{None}. """ - e = error.InfiniteRedirection(b"InvalidCode", location=b"/foo") + e = error.InfiniteRedirection(b"999", location=b"/foo") self.assertEqual(e.message, None) + self.assertEqual(str(e), "999") def test_messageExistsLocationExists(self): """
Problem in web.error str conversion |[<img alt="technic's avatar" src="https://avatars.githubusercontent.com/u/1092613?s=50" width="50" height="50">](https://github.com/technic)| @technic reported| |-|-| |Trac ID|trac#10271| |Type|defect| |Created|2021-10-31 22:06:47Z| Hi, This method returns an error https://github.com/twisted/twisted/blob/3d0be31827585ade5078624e17a1c15240eece02/src/twisted/web/error.py#L92 "can't concat str and None" because self.message is None. in __init__() message is empty string, and the code is 520, then _codeToMessage() returns None, and finally self.message is None. I suggest to change the code to something like `self.message = message or "Unknown"` <details><summary>Searchable metadata</summary> ``` trac-id__10271 10271 type__defect defect reporter__technic technic priority__normal normal milestone__None None branch__ branch_author__ status__new new resolution__None None component__web web keywords__None None time__1635718007391402 1635718007391402 changetime__1635718007391402 1635718007391402 version__None None owner__None None ``` </details>
0.0
59a713107d507a0e042af829ed90e6bff8a463dd
[ "src/twisted/web/test/test_error.py::ErrorTests::test_invalidStatus", "src/twisted/web/test/test_error.py::ErrorTests::test_noMessageForStatus", "src/twisted/web/test/test_error.py::InfiniteRedirectionTests::test_noMessageInvalidStatusLocationExists" ]
[ "src/twisted/web/test/test_error.py::CodeToMessageTests::test_invalidCode", "src/twisted/web/test/test_error.py::CodeToMessageTests::test_nonintegerCode", "src/twisted/web/test/test_error.py::CodeToMessageTests::test_validCode", "src/twisted/web/test/test_error.py::ErrorTests::test_messageExists", "src/twisted/web/test/test_error.py::ErrorTests::test_noMessageValidStatus", "src/twisted/web/test/test_error.py::ErrorTests::test_str", "src/twisted/web/test/test_error.py::PageRedirectTests::test_messageExistsLocationExists", "src/twisted/web/test/test_error.py::PageRedirectTests::test_messageExistsNoLocation", "src/twisted/web/test/test_error.py::PageRedirectTests::test_noMessageInvalidStatusLocationExists", "src/twisted/web/test/test_error.py::PageRedirectTests::test_noMessageValidStatus", "src/twisted/web/test/test_error.py::PageRedirectTests::test_noMessageValidStatusNoLocation", "src/twisted/web/test/test_error.py::InfiniteRedirectionTests::test_messageExistsLocationExists", "src/twisted/web/test/test_error.py::InfiniteRedirectionTests::test_messageExistsNoLocation", "src/twisted/web/test/test_error.py::InfiniteRedirectionTests::test_noMessageValidStatus", "src/twisted/web/test/test_error.py::InfiniteRedirectionTests::test_noMessageValidStatusNoLocation", "src/twisted/web/test/test_error.py::RedirectWithNoLocationTests::test_validMessage", "src/twisted/web/test/test_error.py::MissingRenderMethodTests::test_constructor", "src/twisted/web/test/test_error.py::MissingRenderMethodTests::test_repr", "src/twisted/web/test/test_error.py::MissingTemplateLoaderTests::test_constructor", "src/twisted/web/test/test_error.py::MissingTemplateLoaderTests::test_repr", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_constructor", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootLongByteString", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootLongUnicodeString", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootShortByteString", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootShortUnicodeString", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootTagNoFilename", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_formatRootTagWithFilename", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_reprWithRootsAndWithTraceback", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_reprWithoutRootsAndWithTraceback", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_reprWithoutRootsAndWithoutTraceback", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_str", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_string", "src/twisted/web/test/test_error.py::FlattenerErrorTests::test_unicode", "src/twisted/web/test/test_error.py::UnsupportedMethodTests::test_str" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-09-24 21:04:11+00:00
mit
6,123
twisted__twisted-11831
diff --git a/src/twisted/internet/process.py b/src/twisted/internet/process.py index 51d4bcf00d..89e71b6fef 100644 --- a/src/twisted/internet/process.py +++ b/src/twisted/internet/process.py @@ -18,7 +18,8 @@ import signal import stat import sys import traceback -from typing import TYPE_CHECKING, Callable, Dict, Optional +from collections import defaultdict +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple _PS_CLOSE: int _PS_DUP2: int @@ -629,6 +630,83 @@ def _listOpenFDs(): return detector._listOpenFDs() +def _getFileActions( + fdState: List[Tuple[int, bool]], + childToParentFD: Dict[int, int], + doClose: int, + doDup2: int, +) -> List[Tuple[int, ...]]: + """ + Get the C{file_actions} parameter for C{posix_spawn} based on the + parameters describing the current process state. + + @param fdState: A list of 2-tuples of (file descriptor, close-on-exec + flag). + + @param doClose: the integer to use for the 'close' instruction + + @param doDup2: the integer to use for the 'dup2' instruction + """ + fdStateDict = dict(fdState) + parentToChildren: Dict[int, List[int]] = defaultdict(list) + for inChild, inParent in childToParentFD.items(): + parentToChildren[inParent].append(inChild) + allocated = set(fdStateDict) + allocated |= set(childToParentFD.values()) + allocated |= set(childToParentFD.keys()) + nextFD = 0 + + def allocateFD() -> int: + nonlocal nextFD + while nextFD in allocated: + nextFD += 1 + allocated.add(nextFD) + return nextFD + + result: List[Tuple[int, ...]] = [] + relocations = {} + for inChild, inParent in sorted(childToParentFD.items()): + # The parent FD will later be reused by a child FD. + parentToChildren[inParent].remove(inChild) + if parentToChildren[inChild]: + new = relocations[inChild] = allocateFD() + result.append((doDup2, inChild, new)) + if inParent in relocations: + result.append((doDup2, relocations[inParent], inChild)) + if not parentToChildren[inParent]: + result.append((doClose, relocations[inParent])) + else: + if inParent == inChild: + if fdStateDict[inParent]: + # If the child is attempting to inherit the parent as-is, + # and it is not close-on-exec, the job is already done; we + # can bail. Otherwise... + + tempFD = allocateFD() + # The child wants to inherit the parent as-is, so the + # handle must be heritable.. dup2 makes the new descriptor + # inheritable by default, *but*, per the man page, “if + # fildes and fildes2 are equal, then dup2() just returns + # fildes2; no other changes are made to the existing + # descriptor”, so we need to dup it somewhere else and dup + # it back before closing the temporary place we put it. + result.extend( + [ + (doDup2, inParent, tempFD), + (doDup2, tempFD, inChild), + (doClose, tempFD), + ] + ) + else: + result.append((doDup2, inParent, inChild)) + + for eachFD, uninheritable in fdStateDict.items(): + if eachFD not in childToParentFD and not uninheritable: + result.append((doClose, eachFD)) + + return result + + @implementer(IProcessTransport) class Process(_BaseProcess): """ @@ -791,34 +869,17 @@ class Process(_BaseProcess): ): return False fdmap = kwargs.get("fdmap") - dupSources = set(fdmap.values()) - shouldEventuallyClose = _listOpenFDs() - closeBeforeDup = [] - closeAfterDup = [] - for eachFD in shouldEventuallyClose: + fdState = [] + for eachFD in _listOpenFDs(): try: isCloseOnExec = fcntl.fcntl(eachFD, fcntl.F_GETFD, fcntl.FD_CLOEXEC) except OSError: pass else: - if eachFD not in fdmap and not isCloseOnExec: - (closeAfterDup if eachFD in dupSources else closeBeforeDup).append( - (_PS_CLOSE, eachFD) - ) - + fdState.append((eachFD, isCloseOnExec)) if environment is None: environment = {} - fileActions = ( - closeBeforeDup - + [ - (_PS_DUP2, parentFD, childFD) - for (childFD, parentFD) in fdmap.items() - if childFD != parentFD - ] - + closeAfterDup - ) - setSigDef = [ everySignal for everySignal in range(1, signal.NSIG) @@ -829,7 +890,9 @@ class Process(_BaseProcess): executable, args, environment, - file_actions=fileActions, + file_actions=_getFileActions( + fdState, fdmap, doClose=_PS_CLOSE, doDup2=_PS_DUP2 + ), setsigdef=setSigDef, ) self.status = -1
twisted/twisted
c0bd6baf7b4c4a8901a23d0ddaf54a05f3fe3a15
diff --git a/src/twisted/internet/test/test_process.py b/src/twisted/internet/test/test_process.py index 48bd9e0eb3..0b8cdee750 100644 --- a/src/twisted/internet/test/test_process.py +++ b/src/twisted/internet/test/test_process.py @@ -29,7 +29,7 @@ from twisted.python.compat import networkString from twisted.python.filepath import FilePath, _asFilesystemBytes from twisted.python.log import err, msg from twisted.python.runtime import platform -from twisted.trial.unittest import TestCase +from twisted.trial.unittest import SynchronousTestCase, TestCase # Get the current Python executable as a bytestring. pyExe = FilePath(sys.executable)._asBytesPath() @@ -39,21 +39,35 @@ _uidgidSkipReason = "" properEnv = dict(os.environ) properEnv["PYTHONPATH"] = os.pathsep.join(sys.path) try: - import resource as _resource - from twisted.internet import process as _process if os.getuid() != 0: _uidgidSkip = True _uidgidSkipReason = "Cannot change UID/GID except as root" except ImportError: - resource = None process = None _uidgidSkip = True _uidgidSkipReason = "Cannot change UID/GID on Windows" else: - resource = _resource process = _process + from twisted.internet.process import _getFileActions + + +def _getRealMaxOpenFiles() -> int: + from resource import RLIMIT_NOFILE, getrlimit + + potentialLimits = [getrlimit(RLIMIT_NOFILE)[0], os.sysconf("SC_OPEN_MAX")] + if platform.isMacOSX(): + # The OPEN_MAX macro is still used on macOS. Sometimes, you can open + # file descriptors that go all the way up to SC_OPEN_MAX or + # RLIMIT_NOFILE (which *should* be the same) but OPEN_MAX still trumps + # in some circumstances. In particular, when using the posix_spawn + # family of functions, file_actions on files greater than OPEN_MAX + # return a EBADF errno. Since this macro is deprecated on every other + # UNIX, it's not exposed by Python, since you're really supposed to get + # these values somewhere else... + potentialLimits.append(0x2800) + return min(potentialLimits) def onlyOnPOSIX(testMethod): @@ -64,7 +78,7 @@ def onlyOnPOSIX(testMethod): @return: the C{testMethod} argument. """ - if resource is None: + if os.name != "posix": testMethod.skip = "Test only applies to POSIX platforms." return testMethod @@ -99,6 +113,7 @@ class ProcessTestsBuilderBase(ReactorBuilder): """ requiredInterfaces = [IReactorProcess] + usePTY: bool def test_processTransportInterface(self): """ @@ -381,14 +396,6 @@ class ProcessTestsBuilderBase(ReactorBuilder): self.assertEqual(result, [b"Foo" + os.linesep.encode("ascii")]) @skipIf(platform.isWindows(), "Test only applies to POSIX platforms.") - # If you see this comment and are running on macOS, try to see if this pass on your environment. - # Only run this test on Linux and macOS local tests and Linux CI platforms. - # This should be used for POSIX tests that are expected to pass on macOS but which fail due to lack of macOS developers. - # We still want to run it on local development macOS environments to help developers discover and fix this issue. - @skipIf( - platform.isMacOSX() and os.environ.get("CI", "").lower() == "true", - "Skipped on macOS CI env.", - ) def test_openFileDescriptors(self): """ Processes spawned with spawnProcess() close all extraneous file @@ -431,7 +438,8 @@ sys.stdout.flush()""" # might at least hypothetically select.) fudgeFactor = 17 - unlikelyFD = resource.getrlimit(resource.RLIMIT_NOFILE)[0] - fudgeFactor + hardResourceLimit = _getRealMaxOpenFiles() + unlikelyFD = hardResourceLimit - fudgeFactor os.dup2(w, unlikelyFD) self.addCleanup(os.close, unlikelyFD) @@ -886,7 +894,7 @@ class ProcessTestsBuilder(ProcessTestsBuilderBase): """ us = b"twisted.internet.test.process_cli" - args = [b"hello", b'"', b" \t|<>^&", br'"\\"hello\\"', br'"foo\ bar baz\""'] + args = [b"hello", b'"', b" \t|<>^&", rb'"\\"hello\\"', rb'"foo\ bar baz\""'] # Ensure that all non-NUL characters can be passed too. allChars = "".join(map(chr, range(1, 255))) if isinstance(allChars, str): @@ -1102,3 +1110,97 @@ class ReapingNonePidsLogsProperly(TestCase): self.expected_message, "Wrong error message logged", ) + + +CLOSE = 9999 +DUP2 = 10101 + + +@onlyOnPOSIX +class GetFileActionsTests(SynchronousTestCase): + """ + Tests to make sure that the file actions computed for posix_spawn are + correct. + """ + + def test_nothing(self) -> None: + """ + If there are no open FDs and no requested child FDs, there's nothing to + do. + """ + self.assertEqual(_getFileActions([], {}, CLOSE, DUP2), []) + + def test_closeNoCloexec(self) -> None: + """ + If a file descriptor is not requested but it is not close-on-exec, it + should be closed. + """ + self.assertEqual(_getFileActions([(0, False)], {}, CLOSE, DUP2), [(CLOSE, 0)]) + + def test_closeWithCloexec(self) -> None: + """ + If a file descriptor is close-on-exec and it is not requested, no + action should be taken. + """ + self.assertEqual(_getFileActions([(0, True)], {}, CLOSE, DUP2), []) + + def test_moveWithCloexec(self) -> None: + """ + If a file descriptor is close-on-exec and it is moved, then there should be a dup2 but no close. + """ + self.assertEqual( + _getFileActions([(0, True)], {3: 0}, CLOSE, DUP2), [(DUP2, 0, 3)] + ) + + def test_moveNoCloexec(self) -> None: + """ + If a file descriptor is not close-on-exec and it is moved, then there + should be a dup2 followed by a close. + """ + self.assertEqual( + _getFileActions([(0, False)], {3: 0}, CLOSE, DUP2), + [(DUP2, 0, 3), (CLOSE, 0)], + ) + + def test_stayPut(self) -> None: + """ + If a file descriptor is not close-on-exec and it's left in the same + place, then there should be no actions taken. + """ + self.assertEqual(_getFileActions([(0, False)], {0: 0}, CLOSE, DUP2), []) + + def test_cloexecStayPut(self) -> None: + """ + If a file descriptor is close-on-exec and it's left in the same place, + then we need to DUP2 it elsewhere, close the original, then DUP2 it + back so it doesn't get closed by the implicit exec at the end of + posix_spawn's file actions. + """ + self.assertEqual( + _getFileActions([(0, True)], {0: 0}, CLOSE, DUP2), + [(DUP2, 0, 1), (DUP2, 1, 0), (CLOSE, 1)], + ) + + def test_inheritableConflict(self) -> None: + """ + If our file descriptor mapping requests that file descriptors change + places, we must DUP2 them to a new location before DUP2ing them back. + """ + self.assertEqual( + _getFileActions( + [(0, False), (1, False)], + { + 0: 1, + 1: 0, + }, + CLOSE, + DUP2, + ), + [ + (DUP2, 0, 2), # we're working on the desired fd 0 for the + # child, so we are about to overwrite 0. + (DUP2, 1, 0), # move 1 to 0, also closing 0 + (DUP2, 2, 1), # move 2 to 1, closing previous 1 + (CLOSE, 2), # done with 2 + ], + )
process tests are flaky Tests which call spawnProcess, particularly recently `twisted.python.test.test_sendmsg`, have become flaky enough that they're interfering with the downstream CI of the Cryptography project. This has recently become worse with the introduction of posix_spawn, although it hints at a similar bug underlying our own file-descriptor logic. This is a fix for the former since I couldn't find anything as obviously wrong with the latter.
0.0
c0bd6baf7b4c4a8901a23d0ddaf54a05f3fe3a15
[ "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PotentialZombieWarningTests::test_deprecated", "src/twisted/internet/test/test_process.py::ReapingNonePidsLogsProperly::test__BaseProcess_reapProcess", "src/twisted/internet/test/test_process.py::ReapingNonePidsLogsProperly::test_registerReapProcessHandler", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_cloexecStayPut", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_closeNoCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_closeWithCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_inheritableConflict", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_moveNoCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_moveWithCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_nothing", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_stayPut" ]
[]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-21 08:36:42+00:00
mit
6,124
twisted__twisted-11886
diff --git a/src/twisted/internet/defer.py b/src/twisted/internet/defer.py index d311adda5b..f3ae97060b 100644 --- a/src/twisted/internet/defer.py +++ b/src/twisted/internet/defer.py @@ -1919,6 +1919,33 @@ class _CancellationStatus(Generic[_SelfResultT]): waitingOn: Optional[Deferred[_SelfResultT]] = None +def _gotResultInlineCallbacks( + r: object, + waiting: List[Any], + gen: Union[ + Generator[Deferred[object], object, _T], + Coroutine[Deferred[object], object, _T], + ], + status: _CancellationStatus[_T], + context: _Context, +) -> None: + """ + Helper for L{_inlineCallbacks} to handle a nested L{Deferred} firing. + + @param r: The result of the L{Deferred} + @param waiting: Whether the L{_inlineCallbacks} was waiting, and the result. + @param gen: a generator object returned by calling a function or method + decorated with C{@}L{inlineCallbacks} + @param status: a L{_CancellationStatus} tracking the current status of C{gen} + @param context: the contextvars context to run `gen` in + """ + if waiting[0]: + waiting[0] = False + waiting[1] = r + else: + _inlineCallbacks(r, gen, status, context) + + @_extraneous def _inlineCallbacks( result: object, @@ -2060,14 +2087,7 @@ def _inlineCallbacks( if isinstance(result, Deferred): # a deferred was yielded, get the result. - def gotResult(r: object) -> None: - if waiting[0]: - waiting[0] = False - waiting[1] = r - else: - _inlineCallbacks(r, gen, status, context) - - result.addBoth(gotResult) + result.addBoth(_gotResultInlineCallbacks, waiting, gen, status, context) if waiting[0]: # Haven't called back yet, set flag so that we get reinvoked # and return from the loop @@ -2085,6 +2105,48 @@ def _inlineCallbacks( waiting[1] = None +def _addCancelCallbackToDeferred( + it: Deferred[_T], status: _CancellationStatus[_T] +) -> None: + """ + Helper for L{_cancellableInlineCallbacks} to add + L{_handleCancelInlineCallbacks} as the first errback. + + @param it: The L{Deferred} to add the errback to. + @param status: a L{_CancellationStatus} tracking the current status of C{gen} + """ + it.callbacks, tmp = [], it.callbacks + it.addErrback(_handleCancelInlineCallbacks, status) + it.callbacks.extend(tmp) + it.errback(_InternalInlineCallbacksCancelledError()) + + +def _handleCancelInlineCallbacks( + result: Failure, + status: _CancellationStatus[_T], +) -> Deferred[_T]: + """ + Propagate the cancellation of an C{@}L{inlineCallbacks} to the + L{Deferred} it is waiting on. + + @param result: An L{_InternalInlineCallbacksCancelledError} from + C{cancel()}. + @param status: a L{_CancellationStatus} tracking the current status of C{gen} + @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator + can callback or errback through. + """ + result.trap(_InternalInlineCallbacksCancelledError) + status.deferred = Deferred(lambda d: _addCancelCallbackToDeferred(d, status)) + + # We would only end up here if the inlineCallback is waiting on + # another Deferred. It needs to be cancelled. + awaited = status.waitingOn + assert awaited is not None + awaited.cancel() + + return status.deferred + + def _cancellableInlineCallbacks( gen: Union[ Generator["Deferred[object]", object, _T], @@ -2100,36 +2162,9 @@ def _cancellableInlineCallbacks( @return: L{Deferred} for the C{@}L{inlineCallbacks} that is cancellable. """ - def cancel(it: Deferred[_T]) -> None: - it.callbacks, tmp = [], it.callbacks - it.addErrback(handleCancel) - it.callbacks.extend(tmp) - it.errback(_InternalInlineCallbacksCancelledError()) - - deferred: Deferred[_T] = Deferred(cancel) + deferred: Deferred[_T] = Deferred(lambda d: _addCancelCallbackToDeferred(d, status)) status = _CancellationStatus(deferred) - def handleCancel(result: Failure) -> Deferred[_T]: - """ - Propagate the cancellation of an C{@}L{inlineCallbacks} to the - L{Deferred} it is waiting on. - - @param result: An L{_InternalInlineCallbacksCancelledError} from - C{cancel()}. - @return: A new L{Deferred} that the C{@}L{inlineCallbacks} generator - can callback or errback through. - """ - result.trap(_InternalInlineCallbacksCancelledError) - status.deferred = Deferred(cancel) - - # We would only end up here if the inlineCallback is waiting on - # another Deferred. It needs to be cancelled. - awaited = status.waitingOn - assert awaited is not None - awaited.cancel() - - return status.deferred - _inlineCallbacks(None, gen, status, _copy_context()) return deferred diff --git a/src/twisted/newsfragments/11885.feature b/src/twisted/newsfragments/11885.feature new file mode 100644 index 0000000000..6b2dfb6b86 --- /dev/null +++ b/src/twisted/newsfragments/11885.feature @@ -0,0 +1,1 @@ +When using `CPython`, functions wrapped by `twisted.internet.defer.inlineCallbacks` can have their arguments and return values freed immediately after completion (due to there no longer being circular references).
twisted/twisted
8cd855a7459d044978ae8bc50b49c30cdca72b1d
diff --git a/src/twisted/test/test_defer.py b/src/twisted/test/test_defer.py index f29a31ae00..f1debc6821 100644 --- a/src/twisted/test/test_defer.py +++ b/src/twisted/test/test_defer.py @@ -32,6 +32,7 @@ from typing import ( Mapping, NoReturn, Optional, + Set, Tuple, Type, TypeVar, @@ -1684,57 +1685,6 @@ class DeferredTests(unittest.SynchronousTestCase, ImmediateFailureMixin): self.assertNotEqual([], localz) self.assertNotEqual([], globalz) - def test_inlineCallbacksTracebacks(self) -> None: - """ - L{defer.inlineCallbacks} that re-raise tracebacks into their deferred - should not lose their tracebacks. - """ - f = getDivisionFailure() - d: Deferred[None] = Deferred() - try: - f.raiseException() - except BaseException: - d.errback() - - def ic(d: object) -> Generator[Any, Any, None]: - yield d - - defer.inlineCallbacks(ic) - newFailure = self.failureResultOf(d) - tb = traceback.extract_tb(newFailure.getTracebackObject()) - - self.assertEqual(len(tb), 3) - self.assertIn("test_defer", tb[2][0]) - self.assertEqual("getDivisionFailure", tb[2][2]) - self.assertEqual("1 / 0", tb[2][3]) - - self.assertIn("test_defer", tb[0][0]) - self.assertEqual("test_inlineCallbacksTracebacks", tb[0][2]) - self.assertEqual("f.raiseException()", tb[0][3]) - - def test_fromCoroutineRequiresCoroutine(self) -> None: - """ - L{Deferred.fromCoroutine} requires a coroutine object or a generator, - and will reject things that are not that. - """ - thingsThatAreNotCoroutines = [ - # Lambda - lambda x: x, - # Int - 1, - # Boolean - True, - # Function - self.test_fromCoroutineRequiresCoroutine, - # None - None, - # Module - defer, - ] - - for thing in thingsThatAreNotCoroutines: - self.assertRaises(defer.NotACoroutineError, Deferred.fromCoroutine, thing) - @pyunit.skipIf(_PYPY, "GC works differently on PyPy.") def test_canceller_circular_reference_callback(self) -> None: """ @@ -3950,3 +3900,176 @@ class CoroutineContextVarsTests(unittest.TestCase): clock.advance(1) self.assertEqual(self.successResultOf(d), True) + + +class InlineCallbackTests(unittest.SynchronousTestCase): + def test_inlineCallbacksTracebacks(self) -> None: + """ + L{defer.inlineCallbacks} that re-raise tracebacks into their deferred + should not lose their tracebacks. + """ + f = getDivisionFailure() + d: Deferred[None] = Deferred() + try: + f.raiseException() + except BaseException: + d.errback() + + def ic(d: object) -> Generator[Any, Any, None]: + yield d + + defer.inlineCallbacks(ic) + newFailure = self.failureResultOf(d) + tb = traceback.extract_tb(newFailure.getTracebackObject()) + + self.assertEqual(len(tb), 3) + self.assertIn("test_defer", tb[2][0]) + self.assertEqual("getDivisionFailure", tb[2][2]) + self.assertEqual("1 / 0", tb[2][3]) + + self.assertIn("test_defer", tb[0][0]) + self.assertEqual("test_inlineCallbacksTracebacks", tb[0][2]) + self.assertEqual("f.raiseException()", tb[0][3]) + + def test_fromCoroutineRequiresCoroutine(self) -> None: + """ + L{Deferred.fromCoroutine} requires a coroutine object or a generator, + and will reject things that are not that. + """ + thingsThatAreNotCoroutines = [ + # Lambda + lambda x: x, + # Int + 1, + # Boolean + True, + # Function + self.test_fromCoroutineRequiresCoroutine, + # None + None, + # Module + defer, + ] + + for thing in thingsThatAreNotCoroutines: + self.assertRaises(defer.NotACoroutineError, Deferred.fromCoroutine, thing) + + def test_inlineCallbacksCancelCaptured(self) -> None: + """ + Cancelling an L{defer.inlineCallbacks} correctly handles the function + catching the L{defer.CancelledError}. + + The desired behavior is: + 1. If the function is waiting on an inner deferred, that inner + deferred is cancelled, and a L{defer.CancelledError} is raised + within the function. + 2. If the function catches that exception, execution continues, and + the deferred returned by the function is not resolved. + 3. Cancelling the deferred again cancels any deferred the function + is waiting on, and the exception is raised. + """ + canceller1Calls: List[Deferred[object]] = [] + canceller2Calls: List[Deferred[object]] = [] + d1: Deferred[object] = Deferred(canceller1Calls.append) + d2: Deferred[object] = Deferred(canceller2Calls.append) + + @defer.inlineCallbacks + def testFunc() -> Generator[Deferred[object], object, None]: + try: + yield d1 + except Exception: + pass + + yield d2 + + # Call the function, and ensure that none of the deferreds have + # completed or been cancelled yet. + funcD = testFunc() + + self.assertNoResult(d1) + self.assertNoResult(d2) + self.assertNoResult(funcD) + self.assertEqual(canceller1Calls, []) + self.assertEqual(canceller1Calls, []) + + # Cancel the deferred returned by the function, and check that the first + # inner deferred has been cancelled, but the returned deferred has not + # completed (as the function catches the raised exception). + funcD.cancel() + + self.assertEqual(canceller1Calls, [d1]) + self.assertEqual(canceller2Calls, []) + self.assertNoResult(funcD) + + # Cancel the returned deferred again, this time the returned deferred + # should have a failure result, as the function did not catch the cancel + # exception raised by `d2`. + funcD.cancel() + failure = self.failureResultOf(funcD) + self.assertEqual(failure.type, defer.CancelledError) + self.assertEqual(canceller2Calls, [d2]) + + @pyunit.skipIf(_PYPY, "GC works differently on PyPy.") + def test_inlineCallbacksNoCircularReference(self) -> None: + """ + When using L{defer.inlineCallbacks}, after the function exits, it will + not keep references to the function itself or the arguments. + + This ensures that the machinery gets deallocated immediately rather than + waiting for a GC, on CPython. + + The GC on PyPy works differently (del doesn't immediately deallocate the + object), so we skip the test. + """ + + # Create an object and weak reference to track if its gotten freed. + obj: Set[Any] = set() + objWeakRef = weakref.ref(obj) + + @defer.inlineCallbacks + def func(a: Any) -> Any: + yield a + return a + + # Run the function + funcD = func(obj) + self.assertEqual(obj, self.successResultOf(funcD)) + + funcDWeakRef = weakref.ref(funcD) + + # Delete the local references to obj and funcD. + del obj + del funcD + + # The object has been freed if the weak reference returns None. + self.assertIsNone(objWeakRef()) + self.assertIsNone(funcDWeakRef()) + + @pyunit.skipIf(_PYPY, "GC works differently on PyPy.") + def test_coroutineNoCircularReference(self) -> None: + """ + Tests that there is no circular dependency when using + L{Deferred.fromCoroutine}, so that the machinery gets cleaned up + immediately rather than waiting for a GC. + """ + + # Create an object and weak reference to track if its gotten freed. + obj: Set[Any] = set() + objWeakRef = weakref.ref(obj) + + async def func(a: Any) -> Any: + return a + + # Run the function + funcD = Deferred.fromCoroutine(func(obj)) + self.assertEqual(obj, self.successResultOf(funcD)) + + funcDWeakRef = weakref.ref(funcD) + + # Delete the local references to obj and funcD. + del obj + del funcD + + # The object has been freed if the weak reference returns None. + self.assertIsNone(objWeakRef()) + self.assertIsNone(funcDWeakRef()) diff --git a/src/twisted/test/test_twistd.py b/src/twisted/test/test_twistd.py index d90689c2a2..7817452b19 100644 --- a/src/twisted/test/test_twistd.py +++ b/src/twisted/test/test_twistd.py @@ -1013,6 +1013,12 @@ class UnixApplicationRunnerStartApplicationTests(TestCase): If the specified UID is the same as the current UID of the process, then a warning is displayed. """ + + # FIXME:https://github.com/twisted/twisted/issues/10332 + # Assert that there were no existing warnings. + existing_warnings = self.flushWarnings() + self.assertEqual([], existing_warnings) + currentUid = os.getuid() self._setUID("morefoo", currentUid, "morebar", 4343)
`_inlineCallbacks` machinery has a circular reference The `_inlineCallbacks` machinery currently causes a circular reference to be made, which stops Python from freeing the deferreds etc immediately. This is caused by usages of inline functions. The fix is to move those functions out into standalone ones. (PR incoming). Similar to https://github.com/twisted/twisted/issues/10310.
0.0
8cd855a7459d044978ae8bc50b49c30cdca72b1d
[ "src/twisted/test/test_defer.py::InlineCallbackTests::test_coroutineNoCircularReference", "src/twisted/test/test_defer.py::InlineCallbackTests::test_inlineCallbacksNoCircularReference" ]
[ "src/twisted/test/test_defer.py::UtilTests::test_logErrorLogsError", "src/twisted/test/test_defer.py::UtilTests::test_logErrorLogsErrorNoRepr", "src/twisted/test/test_defer.py::UtilTests::test_logErrorReturnsError", "src/twisted/test/test_defer.py::DeferredTests::testCallbackErrors", "src/twisted/test/test_defer.py::DeferredTests::testCallbackWithArgs", "src/twisted/test/test_defer.py::DeferredTests::testCallbackWithKwArgs", "src/twisted/test/test_defer.py::DeferredTests::testCallbackWithoutArgs", "src/twisted/test/test_defer.py::DeferredTests::testDeferredList", "src/twisted/test/test_defer.py::DeferredTests::testDeferredListConsumeErrors", "src/twisted/test/test_defer.py::DeferredTests::testDeferredListDontConsumeErrors", "src/twisted/test/test_defer.py::DeferredTests::testDeferredListFireOnOneError", "src/twisted/test/test_defer.py::DeferredTests::testDeferredListFireOnOneErrorWithAlreadyFiredDeferreds", "src/twisted/test/test_defer.py::DeferredTests::testDeferredListWithAlreadyFiredDeferreds", "src/twisted/test/test_defer.py::DeferredTests::testEmptyDeferredList", "src/twisted/test/test_defer.py::DeferredTests::testImmediateFailure", "src/twisted/test/test_defer.py::DeferredTests::testImmediateSuccess", "src/twisted/test/test_defer.py::DeferredTests::testPausedFailure", "src/twisted/test/test_defer.py::DeferredTests::testTwoCallbacks", "src/twisted/test/test_defer.py::DeferredTests::testUnpauseBeforeCallback", "src/twisted/test/test_defer.py::DeferredTests::test_addCallbacksNoneCallbackArgs", "src/twisted/test/test_defer.py::DeferredTests::test_addCallbacksNoneErrback", "src/twisted/test/test_defer.py::DeferredTests::test_addCallbacksNoneErrbackArgs", "src/twisted/test/test_defer.py::DeferredTests::test_asynchronousImplicitChain", "src/twisted/test/test_defer.py::DeferredTests::test_asynchronousImplicitErrorChain", "src/twisted/test/test_defer.py::DeferredTests::test_boundedStackDepth", "src/twisted/test/test_defer.py::DeferredTests::test_callbackMaybeReturnsFailure", "src/twisted/test/test_defer.py::DeferredTests::test_callbackOrderPreserved", "src/twisted/test/test_defer.py::DeferredTests::test_callbackReturnsDeferred", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredList", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListCallback", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithException", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithFireOnOneCallback", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithFireOnOneCallbackAndDeferredCallback", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithFireOnOneErrback", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback", "src/twisted/test/test_defer.py::DeferredTests::test_cancelDeferredListWithOriginalDeferreds", "src/twisted/test/test_defer.py::DeferredTests::test_cancelFiredOnOneCallbackDeferredList", "src/twisted/test/test_defer.py::DeferredTests::test_cancelFiredOnOneErrbackDeferredList", "src/twisted/test/test_defer.py::DeferredTests::test_cancelGatherResults", "src/twisted/test/test_defer.py::DeferredTests::test_cancelGatherResultsWithAllDeferredsCallback", "src/twisted/test/test_defer.py::DeferredTests::test_canceller_circular_reference_callback", "src/twisted/test/test_defer.py::DeferredTests::test_canceller_circular_reference_errback", "src/twisted/test/test_defer.py::DeferredTests::test_canceller_circular_reference_non_final", "src/twisted/test/test_defer.py::DeferredTests::test_chainDeferredRecordsExplicitChain", "src/twisted/test/test_defer.py::DeferredTests::test_chainDeferredRecordsImplicitChain", "src/twisted/test/test_defer.py::DeferredTests::test_chainedPausedDeferredWithResult", "src/twisted/test/test_defer.py::DeferredTests::test_circularChainException", "src/twisted/test/test_defer.py::DeferredTests::test_circularChainWarning", "src/twisted/test/test_defer.py::DeferredTests::test_continueCallbackNotFirst", "src/twisted/test/test_defer.py::DeferredTests::test_doubleAsynchronousImplicitChaining", "src/twisted/test/test_defer.py::DeferredTests::test_errbackReturnsDeferred", "src/twisted/test/test_defer.py::DeferredTests::test_errbackWithNoArgs", "src/twisted/test/test_defer.py::DeferredTests::test_errbackWithNoArgsNoDebug", "src/twisted/test/test_defer.py::DeferredTests::test_errorInCallbackCapturesVarsWhenDebugging", "src/twisted/test/test_defer.py::DeferredTests::test_errorInCallbackDoesNotCaptureVars", "src/twisted/test/test_defer.py::DeferredTests::test_explicitChainClearedWhenResolved", "src/twisted/test/test_defer.py::DeferredTests::test_gatherResults", "src/twisted/test/test_defer.py::DeferredTests::test_gatherResultsWithConsumeErrors", "src/twisted/test/test_defer.py::DeferredTests::test_innerCallbacksPreserved", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredAsync", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredAsyncError", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredCoroutineFailure", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredCoroutineSuccess", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredSync", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredSyncException", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredSyncFailure", "src/twisted/test/test_defer.py::DeferredTests::test_maybeDeferredSyncWithArgs", "src/twisted/test/test_defer.py::DeferredTests::test_nestedAsynchronousChainedDeferreds", "src/twisted/test/test_defer.py::DeferredTests::test_nestedAsynchronousChainedDeferredsWithExtraCallbacks", "src/twisted/test/test_defer.py::DeferredTests::test_nonReentrantCallbacks", "src/twisted/test/test_defer.py::DeferredTests::test_pausedDeferredChained", "src/twisted/test/test_defer.py::DeferredTests::test_reentrantRunCallbacks", "src/twisted/test/test_defer.py::DeferredTests::test_reentrantRunCallbacksWithFailure", "src/twisted/test/test_defer.py::DeferredTests::test_repr", "src/twisted/test/test_defer.py::DeferredTests::test_reprWithChaining", "src/twisted/test/test_defer.py::DeferredTests::test_reprWithResult", "src/twisted/test/test_defer.py::DeferredTests::test_resultOfDeferredResultOfDeferredOfFiredDeferredCalled", "src/twisted/test/test_defer.py::DeferredTests::test_synchronousImplicitChain", "src/twisted/test/test_defer.py::DeferredTests::test_synchronousImplicitErrorChain", "src/twisted/test/test_defer.py::RaceTests::test_cancel", "src/twisted/test/test_defer.py::RaceTests::test_failure", "src/twisted/test/test_defer.py::RaceTests::test_resultAfterCancel", "src/twisted/test/test_defer.py::RaceTests::test_resultFromCancel", "src/twisted/test/test_defer.py::RaceTests::test_success", "src/twisted/test/test_defer.py::FirstErrorTests::test_comparison", "src/twisted/test/test_defer.py::FirstErrorTests::test_repr", "src/twisted/test/test_defer.py::FirstErrorTests::test_str", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalledDebug_CC", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalledDebug_CE", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalledDebug_EC", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalledDebug_EE", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalled_CC", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalled_CE", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalled_EC", "src/twisted/test/test_defer.py::AlreadyCalledTests::testAlreadyCalled_EE", "src/twisted/test/test_defer.py::AlreadyCalledTests::testNoDebugging", "src/twisted/test/test_defer.py::AlreadyCalledTests::testSwitchDebugging", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancelAfterCallback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancelAfterErrback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancelNestedDeferred", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancellerArg", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancellerMultipleCancel", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancellerThatCallbacks", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_cancellerThatErrbacks", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_noCanceller", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_noCancellerMultipleCancel", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_noCancellerMultipleCancelsAfterCancelAndCallback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_noCancellerMultipleCancelsAfterCancelAndErrback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_raisesAfterCancelAndCallback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_raisesAfterCancelAndErrback", "src/twisted/test/test_defer.py::DeferredCancellerTests::test_simpleCanceller", "src/twisted/test/test_defer.py::LogTests::test_chainedErrorCleanup", "src/twisted/test/test_defer.py::LogTests::test_errorClearedByChaining", "src/twisted/test/test_defer.py::LogTests::test_errorLog", "src/twisted/test/test_defer.py::LogTests::test_errorLogDebugInfo", "src/twisted/test/test_defer.py::LogTests::test_errorLogNoRepr", "src/twisted/test/test_defer.py::LogTests::test_errorLogWithInnerFrameCycle", "src/twisted/test/test_defer.py::LogTests::test_errorLogWithInnerFrameRef", "src/twisted/test/test_defer.py::DeferredListEmptyTests::testDeferredListEmpty", "src/twisted/test/test_defer.py::OtherPrimitivesTests::testLock", "src/twisted/test/test_defer.py::OtherPrimitivesTests::testQueue", "src/twisted/test/test_defer.py::OtherPrimitivesTests::testSemaphore", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelLockAfterAcquired", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelLockBeforeAcquired", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelQueueAfterGet", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelQueueAfterSynchronousGet", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelSemaphoreAfterAcquired", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_cancelSemaphoreBeforeAcquired", "src/twisted/test/test_defer.py::OtherPrimitivesTests::test_semaphoreInvalidTokens", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_cancelDeferUntilLocked", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_cancelDeferUntilLockedWithTimeout", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_concurrentUsage", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_defaultScheduler", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_multipleUsages", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_waitUntilLockedWithNoLock", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_waitUntilLockedWithTimeoutLocked", "src/twisted/test/test_defer.py::DeferredFilesystemLockTests::test_waitUntilLockedWithTimeoutUnlocked", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_callbackAddedToCancelerBeforeTimeout", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_callbackAddedToCancelerBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_cancelBeforeTimeout", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_cancelBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_errbackAddedBeforeTimeout", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_errbackAddedBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_errbackAddedBeforeTimeoutSuppressesCancellation", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_errbackAddedBeforeTimeoutSuppressesCancellationCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_failureBeforeTimeout", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_failureBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_providedCancelCalledBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_successResultBeforeTimeout", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_successResultBeforeTimeoutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_timedOut", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_timedOutCustom", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_timedOutProvidedCancelFailure", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_timedOutProvidedCancelSuccess", "src/twisted/test/test_defer.py::DeferredAddTimeoutTests::test_timeoutChainable", "src/twisted/test/test_defer.py::EnsureDeferredTests::test_ensureDeferredCoroutine", "src/twisted/test/test_defer.py::EnsureDeferredTests::test_ensureDeferredGenerator", "src/twisted/test/test_defer.py::EnsureDeferredTests::test_passesThroughDeferreds", "src/twisted/test/test_defer.py::EnsureDeferredTests::test_willNotAllowNonDeferredOrCoroutine", "src/twisted/test/test_defer.py::TimeoutErrorTests::test_deprecatedTimeout", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_asFuture", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_asFutureCancelFuture", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_asFutureFailure", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_asFutureSuccessCancel", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_fromFuture", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_fromFutureDeferredCancelled", "src/twisted/test/test_defer.py::DeferredFutureAdapterTests::test_fromFutureFutureCancelled", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_asyncWithLock", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_asyncWithLockException", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_asyncWithSemaphore", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_contextvarsWithAsyncAwait", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_resetWithInlineCallbacks", "src/twisted/test/test_defer.py::CoroutineContextVarsTests::test_withInlineCallbacks", "src/twisted/test/test_defer.py::InlineCallbackTests::test_fromCoroutineRequiresCoroutine", "src/twisted/test/test_defer.py::InlineCallbackTests::test_inlineCallbacksCancelCaptured", "src/twisted/test/test_defer.py::InlineCallbackTests::test_inlineCallbacksTracebacks", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_badAttributeWithConfiguredLogObserver", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_defaultUmask", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_invalidUmask", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_listAllProfilers", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_postOptionsNoSubCommandSavesAsUsual", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_postOptionsSubCommandCausesNoSave", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_printSubCommandForUsageError", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_sortedReactorHelp", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_subCommands", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_umask", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_unimportableConfiguredLogObserver", "src/twisted/test/test_twistd.py::ServerOptionsTests::test_version", "src/twisted/test/test_twistd.py::CheckPIDTests::test_anotherRunning", "src/twisted/test/test_twistd.py::CheckPIDTests::test_nonNumeric", "src/twisted/test/test_twistd.py::CheckPIDTests::test_notExists", "src/twisted/test/test_twistd.py::CheckPIDTests::test_stale", "src/twisted/test/test_twistd.py::CheckPIDTests::test_unexpectedOSError", "src/twisted/test/test_twistd.py::TapFileTests::test_createOrGetApplicationWithTapFile", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationRunnerCapturesSignal", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationRunnerChoosesReactorIfNone", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationRunnerGetsCorrectApplication", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationRunnerIgnoresNoSignal", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationStartsWithConfiguredNameIDs", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_applicationStartsWithConfiguredNumericIDs", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_preAndPostApplication", "src/twisted/test/test_twistd.py::ApplicationRunnerTests::test_startReactorRunsTheReactor", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_changeWorkingDirectory", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_chroot", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_daemonPIDFile", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_daemonize", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_daemonizedNoUmask", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_noChroot", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_noDaemonize", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_noDaemonizeNoUmask", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_nonDaemonPIDFile", "src/twisted/test/test_twistd.py::UnixApplicationRunnerSetupEnvironmentTests::test_umask", "src/twisted/test/test_twistd.py::UnixApplicationRunnerStartApplicationTests::test_setUidSameAsCurrentUid", "src/twisted/test/test_twistd.py::UnixApplicationRunnerStartApplicationTests::test_setUidWithoutGid", "src/twisted/test/test_twistd.py::UnixApplicationRunnerStartApplicationTests::test_setupEnvironment", "src/twisted/test/test_twistd.py::UnixApplicationRunnerStartApplicationTests::test_shedPrivileges", "src/twisted/test/test_twistd.py::UnixApplicationRunnerStartApplicationTests::test_shedPrivilegesError", "src/twisted/test/test_twistd.py::UnixApplicationRunnerRemovePIDTests::test_removePID", "src/twisted/test/test_twistd.py::UnixApplicationRunnerRemovePIDTests::test_removePIDErrors", "src/twisted/test/test_twistd.py::AppProfilingTests::test_cProfile", "src/twisted/test/test_twistd.py::AppProfilingTests::test_cProfileSaveStats", "src/twisted/test/test_twistd.py::AppProfilingTests::test_defaultProfiler", "src/twisted/test/test_twistd.py::AppProfilingTests::test_profile", "src/twisted/test/test_twistd.py::AppProfilingTests::test_profilePrintStatsError", "src/twisted/test/test_twistd.py::AppProfilingTests::test_profileSaveStats", "src/twisted/test/test_twistd.py::AppProfilingTests::test_profilerNameCaseInsentive", "src/twisted/test/test_twistd.py::AppProfilingTests::test_unknownProfiler", "src/twisted/test/test_twistd.py::AppProfilingTests::test_withoutCProfile", "src/twisted/test/test_twistd.py::AppProfilingTests::test_withoutProfile", "src/twisted/test/test_twistd.py::AppLoggerTests::test_configuredLogObserverBeatsComponent", "src/twisted/test/test_twistd.py::AppLoggerTests::test_configuredLogObserverBeatsLegacyComponent", "src/twisted/test/test_twistd.py::AppLoggerTests::test_configuredLogObserverBeatsLogfile", "src/twisted/test/test_twistd.py::AppLoggerTests::test_configuredLogObserverBeatsSyslog", "src/twisted/test/test_twistd.py::AppLoggerTests::test_getLogObserverFile", "src/twisted/test/test_twistd.py::AppLoggerTests::test_getLogObserverStdout", "src/twisted/test/test_twistd.py::AppLoggerTests::test_legacyObservers", "src/twisted/test/test_twistd.py::AppLoggerTests::test_loggerComponentBeatsLegacyLoggerComponent", "src/twisted/test/test_twistd.py::AppLoggerTests::test_start", "src/twisted/test/test_twistd.py::AppLoggerTests::test_startUsesApplicationLogObserver", "src/twisted/test/test_twistd.py::AppLoggerTests::test_startUsesConfiguredLogObserver", "src/twisted/test/test_twistd.py::AppLoggerTests::test_stop", "src/twisted/test/test_twistd.py::AppLoggerTests::test_unmarkedObserversDeprecated", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverDefaultFile", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverDontOverrideSignalHandler", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverFile", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverStdout", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverStdoutDaemon", "src/twisted/test/test_twistd.py::UnixAppLoggerTests::test_getLogObserverSyslog", "src/twisted/test/test_twistd.py::DaemonizeTests::test_error", "src/twisted/test/test_twistd.py::DaemonizeTests::test_errorInParent", "src/twisted/test/test_twistd.py::DaemonizeTests::test_errorInParentWithTruncatedUnicode", "src/twisted/test/test_twistd.py::DaemonizeTests::test_errorMessageTruncated", "src/twisted/test/test_twistd.py::DaemonizeTests::test_hooksCalled", "src/twisted/test/test_twistd.py::DaemonizeTests::test_hooksNotCalled", "src/twisted/test/test_twistd.py::DaemonizeTests::test_nonASCIIErrorInParent", "src/twisted/test/test_twistd.py::DaemonizeTests::test_success", "src/twisted/test/test_twistd.py::DaemonizeTests::test_successEINTR", "src/twisted/test/test_twistd.py::DaemonizeTests::test_successInParent", "src/twisted/test/test_twistd.py::DaemonizeTests::test_successInParentEINTR", "src/twisted/test/test_twistd.py::DaemonizeTests::test_unicodeError", "src/twisted/test/test_twistd.py::DaemonizeTests::test_unicodeErrorMessageTruncated", "src/twisted/test/test_twistd.py::ExitWithSignalTests::test_exitWithSignal", "src/twisted/test/test_twistd.py::ExitWithSignalTests::test_normalExit", "src/twisted/test/test_twistd.py::ExitWithSignalTests::test_runnerExitsWithSignal" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-06-25 19:07:04+00:00
mit
6,125
twisted__twisted-11897
diff --git a/src/twisted/newsfragments/11707.bugfix b/src/twisted/newsfragments/11707.bugfix new file mode 100644 index 0000000000..9aef1d7359 --- /dev/null +++ b/src/twisted/newsfragments/11707.bugfix @@ -0,0 +1,7 @@ +When interrupted with control-C, `trial -j` no longer obscures tracebacks for +any errors caused by that interruption with an `UnboundLocalError` due to a bug +in its own implementation. Note that there are still several internal +tracebacks that will be emitted upon exiting, because tearing down the test +runner mid-suite is still not an entirely clean operation, but it should at +least be possible to see errors reported from, for example, a test that is +hanging more clearly. diff --git a/src/twisted/trial/_dist/disttrial.py b/src/twisted/trial/_dist/disttrial.py index a57a4bf37b..1a7cf886c0 100644 --- a/src/twisted/trial/_dist/disttrial.py +++ b/src/twisted/trial/_dist/disttrial.py @@ -13,7 +13,17 @@ import os import sys from functools import partial from os.path import isabs -from typing import Awaitable, Callable, Iterable, List, Sequence, TextIO, Union, cast +from typing import ( + Awaitable, + Callable, + Iterable, + List, + Optional, + Sequence, + TextIO, + Union, + cast, +) from unittest import TestCase, TestSuite from attrs import define, field, frozen @@ -441,15 +451,35 @@ class DistTrialRunner: await startedPool.join() def _run(self, test: Union[TestCase, TestSuite], untilFailure: bool) -> IReporter: - result: Union[Failure, DistReporter] + result: Union[Failure, DistReporter, None] = None + reactorStopping: bool = False + testsInProgress: Deferred[object] - def capture(r): + def capture(r: Union[Failure, DistReporter]) -> None: nonlocal result result = r - d = Deferred.fromCoroutine(self.runAsync(test, untilFailure)) - d.addBoth(capture) - d.addBoth(lambda ignored: self._reactor.stop()) + def maybeStopTests() -> Optional[Deferred[object]]: + nonlocal reactorStopping + reactorStopping = True + if result is None: + testsInProgress.cancel() + return testsInProgress + return None + + def maybeStopReactor(result: object) -> object: + if not reactorStopping: + self._reactor.stop() + return result + + self._reactor.addSystemEventTrigger("before", "shutdown", maybeStopTests) + + testsInProgress = ( + Deferred.fromCoroutine(self.runAsync(test, untilFailure)) + .addBoth(capture) + .addBoth(maybeStopReactor) + ) + self._reactor.run() if isinstance(result, Failure): @@ -458,7 +488,7 @@ class DistTrialRunner: # mypy can't see that raiseException raises an exception so we can # only get here if result is not a Failure, so tell mypy result is # certainly a DistReporter at this point. - assert isinstance(result, DistReporter) + assert isinstance(result, DistReporter), f"{result} is not DistReporter" # Unwrap the DistReporter to give the caller some regular IReporter # object. DistReporter isn't type annotated correctly so fix it here.
twisted/twisted
949f4b64d07acd0737e586c8b6e1a3ee7e88ba2b
diff --git a/src/twisted/trial/_dist/test/test_disttrial.py b/src/twisted/trial/_dist/test/test_disttrial.py index ed378f1a96..eb4519a6ae 100644 --- a/src/twisted/trial/_dist/test/test_disttrial.py +++ b/src/twisted/trial/_dist/test/test_disttrial.py @@ -31,7 +31,7 @@ from hypothesis.strategies import booleans, sampled_from from twisted.internet import interfaces from twisted.internet.base import ReactorBase -from twisted.internet.defer import Deferred, succeed +from twisted.internet.defer import CancelledError, Deferred, succeed from twisted.internet.error import ProcessDone from twisted.internet.protocol import ProcessProtocol, Protocol from twisted.internet.test.modulehelpers import AlternateReactor @@ -125,6 +125,11 @@ class CountingReactor(MemoryReactorClock): See L{IReactorCore.stop}. """ MemoryReactorClock.stop(self) + # TODO: implementing this more comprehensively in MemoryReactor would + # be nice, this is rather hard-coded to disttrial's current + # implementation. + if "before" in self.triggers: + self.triggers["before"]["shutdown"][0][0]() self.stopCount += 1 def run(self): @@ -139,6 +144,9 @@ class CountingReactor(MemoryReactorClock): for f, args, kwargs in self.whenRunningHooks: f(*args, **kwargs) + self.stop() + # do not count internal 'stop' against trial-initiated .stop() count + self.stopCount -= 1 class CountingReactorTests(SynchronousTestCase): @@ -461,6 +469,15 @@ class DistTrialRunnerTests(TestCase): assert_that(errors, has_length(1)) assert_that(errors[0][1].type, equal_to(WorkerPoolBroken)) + def test_runUnexpectedErrorCtrlC(self) -> None: + """ + If the reactor is stopped by C-c (i.e. `run` returns before the test + case's Deferred has been fired) we should cancel the pending test run. + """ + runner = self.getRunner(workerPoolFactory=LocalWorkerPool) + with self.assertRaises(CancelledError): + runner.run(self.suite) + def test_runUnexpectedWorkerError(self) -> None: """ If for some reason the worker process cannot run a test, the error is
`UnboundLocalError` exception when exiting `trial -j` via an interrupt (i.e. ctrl-C) running `trial --reporter=bwverbose -j 10 twisted.internet.test` for unrelated reasons: `trial --reporter=bwverbose -j 10 twisted.internet.test` ``` ^CTraceback (most recent call last): File "/Users/glyph/.virtualenvs/Twisted/bin/trial", line 8, in <module> sys.exit(run()) File "/Users/glyph/Projects/Twisted/src/twisted/scripts/trial.py", line 647, in run testResult = trialRunner.run(suite) File "/Users/glyph/Projects/Twisted/src/twisted/trial/_dist/disttrial.py", line 473, in run return self._run(test, untilFailure=False) File "/Users/glyph/Projects/Twisted/src/twisted/trial/_dist/disttrial.py", line 455, in _run if isinstance(result, Failure): UnboundLocalError: local variable 'result' referenced before assignment ```
0.0
949f4b64d07acd0737e586c8b6e1a3ee7e88ba2b
[ "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runUnexpectedErrorCtrlC" ]
[ "src/twisted/trial/_dist/test/test_disttrial.py::CountingReactorTests::test_providesIReactorProcess", "src/twisted/trial/_dist/test/test_disttrial.py::CountingReactorTests::test_run", "src/twisted/trial/_dist/test/test_disttrial.py::CountingReactorTests::test_spawnProcess", "src/twisted/trial/_dist/test/test_disttrial.py::CountingReactorTests::test_stop", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_createLocalWorkers", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_join", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_launchWorkerProcesses", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_logFile", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_run", "src/twisted/trial/_dist/test/test_disttrial.py::WorkerPoolTests::test_runUsedDirectory", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_exitFirst", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_installedReactor", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_minimalWorker", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_run", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runFailure", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runUncleanWarnings", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runUnexpectedError", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runUnexpectedWorkerError", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runUntilFailure", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runWaitForProcessesDeferreds", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runWithoutTest", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_runWithoutTestButWithAnError", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_writeResults", "src/twisted/trial/_dist/test/test_disttrial.py::DistTrialRunnerTests::test_wrongInstalledReactor", "src/twisted/trial/_dist/test/test_disttrial.py::FunctionalTests::test_countingCalls", "src/twisted/trial/_dist/test/test_disttrial.py::FunctionalTests::test_discardResult", "src/twisted/trial/_dist/test/test_disttrial.py::FunctionalTests::test_fromOptional", "src/twisted/trial/_dist/test/test_disttrial.py::FunctionalTests::test_iterateWhile", "src/twisted/trial/_dist/test/test_disttrial.py::FunctionalTests::test_sequence" ]
{ "failed_lite_validators": [ "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-07-21 20:06:45+00:00
mit
6,126
twisted__twisted-11998
diff --git a/src/twisted/newsfragments/11997.bugfix b/src/twisted/newsfragments/11997.bugfix new file mode 100644 index 0000000000..3c65d78933 --- /dev/null +++ b/src/twisted/newsfragments/11997.bugfix @@ -0,0 +1,1 @@ +twisted.web.http.HTTPChannel now ignores the trailer headers provided in the last chunk of a chunked encoded response, rather than raising an exception. diff --git a/src/twisted/web/http.py b/src/twisted/web/http.py index 53c377d970..1c598380ac 100644 --- a/src/twisted/web/http.py +++ b/src/twisted/web/http.py @@ -1805,7 +1805,6 @@ class _IdentityTransferDecoder: maxChunkSizeLineLength = 1024 - _chunkExtChars = ( b"\t !\"#$%&'()*+,-./0123456789:;<=>?@" b"ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`" @@ -1889,12 +1888,20 @@ class _ChunkedTransferDecoder: state transition this is truncated at the front so that index 0 is where the next state shall begin. - @ivar _start: While in the C{'CHUNK_LENGTH'} state, tracks the index into - the buffer at which search for CRLF should resume. Resuming the search - at this position avoids doing quadratic work if the chunk length line - arrives over many calls to C{dataReceived}. + @ivar _start: While in the C{'CHUNK_LENGTH'} and C{'TRAILER'} states, + tracks the index into the buffer at which search for CRLF should resume. + Resuming the search at this position avoids doing quadratic work if the + chunk length line arrives over many calls to C{dataReceived}. + + @ivar _trailerHeaders: Accumulates raw/unparsed trailer headers. + See https://github.com/twisted/twisted/issues/12014 + + @ivar _maxTrailerHeadersSize: Maximum bytes for trailer header from the + response. + @type _maxTrailerHeadersSize: C{int} - Not used in any other state. + @ivar _receivedTrailerHeadersSize: Bytes received so far for the tailer headers. + @type _receivedTrailerHeadersSize: C{int} """ state = "CHUNK_LENGTH" @@ -1908,6 +1915,9 @@ class _ChunkedTransferDecoder: self.finishCallback = finishCallback self._buffer = bytearray() self._start = 0 + self._trailerHeaders: List[bytearray] = [] + self._maxTrailerHeadersSize = 2**16 + self._receivedTrailerHeadersSize = 0 def _dataReceived_CHUNK_LENGTH(self) -> bool: """ @@ -1984,23 +1994,37 @@ class _ChunkedTransferDecoder: def _dataReceived_TRAILER(self) -> bool: """ - Await the carriage return and line feed characters that follow the - terminal zero-length chunk. Then invoke C{finishCallback} and switch to - state C{'FINISHED'}. + Collect trailer headers if received and finish at the terminal zero-length + chunk. Then invoke C{finishCallback} and switch to state C{'FINISHED'}. @returns: C{False}, as there is either insufficient data to continue, or no data remains. - - @raises _MalformedChunkedDataError: when anything other than CRLF is - received. """ - if len(self._buffer) < 2: + if ( + self._receivedTrailerHeadersSize + len(self._buffer) + > self._maxTrailerHeadersSize + ): + raise _MalformedChunkedDataError("Trailer headers data is too long.") + + eolIndex = self._buffer.find(b"\r\n", self._start) + + if eolIndex == -1: + # Still no end of network line marker found. + # Continue processing more data. return False - if not self._buffer.startswith(b"\r\n"): - raise _MalformedChunkedDataError("Chunk did not end with CRLF") + if eolIndex > 0: + # A trailer header was detected. + self._trailerHeaders.append(self._buffer[0:eolIndex]) + del self._buffer[0 : eolIndex + 2] + self._start = 0 + self._receivedTrailerHeadersSize += eolIndex + 2 + return True + + # eolIndex in this part of code is equal to 0 data = memoryview(self._buffer)[2:].tobytes() + del self._buffer[:] self.state = "FINISHED" self.finishCallback(data)
twisted/twisted
f35f891ca30032ab8cda07c712b222a2ee9d982b
diff --git a/src/twisted/web/test/test_http.py b/src/twisted/web/test/test_http.py index d6a6a17054..33d0a49fca 100644 --- a/src/twisted/web/test/test_http.py +++ b/src/twisted/web/test/test_http.py @@ -1224,6 +1224,7 @@ class ChunkedTransferEncodingTests(unittest.TestCase): p.dataReceived(s) self.assertEqual(L, [b"a", b"b", b"c", b"1", b"2", b"3", b"4", b"5"]) self.assertEqual(finished, [b""]) + self.assertEqual(p._trailerHeaders, []) def test_long(self): """ @@ -1381,20 +1382,6 @@ class ChunkedTransferEncodingTests(unittest.TestCase): http._MalformedChunkedDataError, p.dataReceived, b"3\r\nabc!!!!" ) - def test_malformedChunkEndFinal(self): - r""" - L{_ChunkedTransferDecoder.dataReceived} raises - L{_MalformedChunkedDataError} when the terminal zero-length chunk is - followed by characters other than C{\r\n}. - """ - p = http._ChunkedTransferDecoder( - lambda b: None, - lambda b: None, # pragma: nocov - ) - self.assertRaises( - http._MalformedChunkedDataError, p.dataReceived, b"3\r\nabc\r\n0\r\n!!" - ) - def test_finish(self): """ L{_ChunkedTransferDecoder.dataReceived} interprets a zero-length @@ -1469,6 +1456,79 @@ class ChunkedTransferEncodingTests(unittest.TestCase): self.assertEqual(errors, []) self.assertEqual(successes, [True]) + def test_trailerHeaders(self): + """ + L{_ChunkedTransferDecoder.dataReceived} decodes chunked-encoded data + and ignores trailer headers which come after the terminating zero-length + chunk. + """ + L = [] + finished = [] + p = http._ChunkedTransferDecoder(L.append, finished.append) + p.dataReceived(b"3\r\nabc\r\n5\r\n12345\r\n") + p.dataReceived( + b"a\r\n0123456789\r\n0\r\nServer-Timing: total;dur=123.4\r\nExpires: Wed, 21 Oct 2015 07:28:00 GMT\r\n\r\n" + ) + self.assertEqual(L, [b"abc", b"12345", b"0123456789"]) + self.assertEqual(finished, [b""]) + self.assertEqual( + p._trailerHeaders, + [ + b"Server-Timing: total;dur=123.4", + b"Expires: Wed, 21 Oct 2015 07:28:00 GMT", + ], + ) + + def test_shortTrailerHeader(self): + """ + L{_ChunkedTransferDecoder.dataReceived} decodes chunks of input with + tailer header broken up and delivered in multiple calls. + """ + L = [] + finished = [] + p = http._ChunkedTransferDecoder(L.append, finished.append) + for s in iterbytes( + b"3\r\nabc\r\n5\r\n12345\r\n0\r\nServer-Timing: total;dur=123.4\r\n\r\n" + ): + p.dataReceived(s) + self.assertEqual(L, [b"a", b"b", b"c", b"1", b"2", b"3", b"4", b"5"]) + self.assertEqual(finished, [b""]) + self.assertEqual(p._trailerHeaders, [b"Server-Timing: total;dur=123.4"]) + + def test_tooLongTrailerHeader(self): + r""" + L{_ChunkedTransferDecoder.dataReceived} raises + L{_MalformedChunkedDataError} when the trailing headers data is too long. + """ + p = http._ChunkedTransferDecoder( + lambda b: None, + lambda b: None, # pragma: nocov + ) + p._maxTrailerHeadersSize = 10 + self.assertRaises( + http._MalformedChunkedDataError, + p.dataReceived, + b"3\r\nabc\r\n0\r\nTotal-Trailer: header;greater-then=10\r\n\r\n", + ) + + def test_unfinishedTrailerHeader(self): + r""" + L{_ChunkedTransferDecoder.dataReceived} raises + L{_MalformedChunkedDataError} when the trailing headers data is too long + and doesn't have final CRLF characters. + """ + p = http._ChunkedTransferDecoder( + lambda b: None, + lambda b: None, # pragma: nocov + ) + p._maxTrailerHeadersSize = 10 + p.dataReceived(b"3\r\nabc\r\n0\r\n0123456789") + self.assertRaises( + http._MalformedChunkedDataError, + p.dataReceived, + b"A", + ) + class ChunkingTests(unittest.TestCase, ResponseTestMixin): strings = [b"abcv", b"", b"fdfsd423", b"Ffasfas\r\n", b"523523\n\rfsdf", b"4234"]
Twisted web client doesn't support trailer Server-Timing **Describe the incorrect behavior you saw** Twisted web client doesn't support trailer Server-Timing. Example: https://w3c.github.io/server-timing/#the-server-timing-header-field **Describe how to cause this behavior** Use console program (simple http client) from this gist: https://gist.github.com/taroved/06922ceeb872094304cc889dacae099f Always you run the code: ```shell python httpclient.py https://www.esquire.com/ ``` You see such exception: ``` Traceback (most recent call last): Failure: twisted.web._newclient.ResponseFailed: [<twisted.python.failure.Failure twisted.web.http._MalformedChunkedDataError: Chunk did not end with CRLF>, <twisted.python.failure.Failure twisted.web.http._DataLoss: Chunked decoder in 'TRAILER' state, still expecting more data to get to 'FINISHED' state.>] ``` **Describe the correct behavior you'd like to see** Such pages as https://www.esquire.com/ should be downloaded without exceptions. **Testing environment** - Linux 939ff8bae3fe 5.15.49-linuxkit-pr - Twisted version: 23.8.0
0.0
f35f891ca30032ab8cda07c712b222a2ee9d982b
[ "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_short", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_shortTrailerHeader", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_trailerHeaders", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_unfinishedTrailerHeader" ]
[ "src/twisted/web/test/test_http.py::DateTimeTests::testRoundtrip", "src/twisted/web/test/test_http.py::DateTimeTests::testStringToDatetime", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_buffer", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_connectionLostAfterForceClose", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_noPipelining", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_noPipeliningApi", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_requestBodyDefaultTimeout", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_requestBodyTimeout", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_transportForciblyClosed", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_transportNotAbortedAfterConnectionLost", "src/twisted/web/test/test_http.py::HTTP1_0Tests::test_transportNotAbortedWithZeroAbortTimeout", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_buffer", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_connectionLostAfterForceClose", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_noPipelining", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_noPipeliningApi", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_requestBodyDefaultTimeout", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_requestBodyTimeout", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_transportForciblyClosed", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_transportNotAbortedAfterConnectionLost", "src/twisted/web/test/test_http.py::HTTP1_1Tests::test_transportNotAbortedWithZeroAbortTimeout", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_buffer", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_connectionLostAfterForceClose", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_noPipelining", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_noPipeliningApi", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_requestBodyDefaultTimeout", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_requestBodyTimeout", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_transportForciblyClosed", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_transportNotAbortedAfterConnectionLost", "src/twisted/web/test/test_http.py::HTTP1_1_close_Tests::test_transportNotAbortedWithZeroAbortTimeout", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_buffer", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_connectionLostAfterForceClose", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_noPipeliningApi", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_requestBodyDefaultTimeout", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_requestBodyTimeout", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_transportForciblyClosed", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_transportNotAbortedAfterConnectionLost", "src/twisted/web/test/test_http.py::HTTP0_9Tests::test_transportNotAbortedWithZeroAbortTimeout", "src/twisted/web/test/test_http.py::PipeliningBodyTests::test_noPipelining", "src/twisted/web/test/test_http.py::PipeliningBodyTests::test_pipeliningReadLimit", "src/twisted/web/test/test_http.py::ShutdownTests::test_losingConnection", "src/twisted/web/test/test_http.py::SecurityTests::test_isSecure", "src/twisted/web/test/test_http.py::SecurityTests::test_notSecure", "src/twisted/web/test/test_http.py::SecurityTests::test_notSecureAfterFinish", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_GenericHTTPChannelPropagatesCallLater", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_factory", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_http11", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_http2_absent", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_protocolNone", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_protocolUnspecified", "src/twisted/web/test/test_http.py::GenericHTTPChannelTests::test_unknownProtocol", "src/twisted/web/test/test_http.py::HTTPLoopbackTests::testLoopback", "src/twisted/web/test/test_http.py::PersistenceTests::test_http09", "src/twisted/web/test/test_http.py::PersistenceTests::test_http10", "src/twisted/web/test/test_http.py::PersistenceTests::test_http11", "src/twisted/web/test/test_http.py::PersistenceTests::test_http11Close", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_earlyConnectionLose", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_exactAmountReceived", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_finishedConnectionLose", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_longString", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_rejectDataAfterFinished", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_shortStrings", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_unknownContentLength", "src/twisted/web/test/test_http.py::IdentityTransferEncodingTests::test_unknownContentLengthConnectionLose", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_afterFinished", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_decoding", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_earlyConnectionLose", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_empty", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_extensions", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_extensionsMalformed", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_extra", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_finish", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_finishedConnectionLose", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_long", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_malformedChunkEnd", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_malformedChunkSize", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_malformedChunkSizeHex", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_malformedChunkSizeNegative", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_newlines", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_oversizedChunkSizeLine", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_oversizedChunkSizeLinePartial", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_reentrantFinishedNoMoreData", "src/twisted/web/test/test_http.py::ChunkedTransferEncodingTests::test_tooLongTrailerHeader", "src/twisted/web/test/test_http.py::ChunkingTests::testChunks", "src/twisted/web/test/test_http.py::ChunkingTests::testConcatenatedChunks", "src/twisted/web/test/test_http.py::ChunkingTests::test_chunkedResponses", "src/twisted/web/test/test_http.py::ChunkingTests::test_multipartFormData", "src/twisted/web/test/test_http.py::ParsingTests::testCookies", "src/twisted/web/test/test_http.py::ParsingTests::testGET", "src/twisted/web/test/test_http.py::ParsingTests::test_basicAuth", "src/twisted/web/test/test_http.py::ParsingTests::test_basicAuthException", "src/twisted/web/test/test_http.py::ParsingTests::test_chunkedEncoding", "src/twisted/web/test/test_http.py::ParsingTests::test_contentLengthAndTransferEncoding", "src/twisted/web/test/test_http.py::ParsingTests::test_contentLengthAndTransferEncodingWithPipelinedRequests", "src/twisted/web/test/test_http.py::ParsingTests::test_contentLengthMalformed", "src/twisted/web/test/test_http.py::ParsingTests::test_contentLengthNegative", "src/twisted/web/test/test_http.py::ParsingTests::test_contentLengthTooPositive", "src/twisted/web/test/test_http.py::ParsingTests::test_duplicateContentLengths", "src/twisted/web/test/test_http.py::ParsingTests::test_duplicateContentLengthsWithPipelinedRequests", "src/twisted/web/test/test_http.py::ParsingTests::test_extraQuestionMark", "src/twisted/web/test/test_http.py::ParsingTests::test_formPOSTRequest", "src/twisted/web/test/test_http.py::ParsingTests::test_headerLimitPerRequest", "src/twisted/web/test/test_http.py::ParsingTests::test_headerStripWhitespace", "src/twisted/web/test/test_http.py::ParsingTests::test_headers", "src/twisted/web/test/test_http.py::ParsingTests::test_headersMultiline", "src/twisted/web/test/test_http.py::ParsingTests::test_headersTooBigInitialCommand", "src/twisted/web/test/test_http.py::ParsingTests::test_headersTooBigOtherHeaders", "src/twisted/web/test/test_http.py::ParsingTests::test_headersTooBigPerRequest", "src/twisted/web/test/test_http.py::ParsingTests::test_invalidContentLengthHeader", "src/twisted/web/test/test_http.py::ParsingTests::test_invalidHeaderNoColon", "src/twisted/web/test/test_http.py::ParsingTests::test_invalidHeaderOnlyColon", "src/twisted/web/test/test_http.py::ParsingTests::test_invalidHeaderWhitespaceBeforeColon", "src/twisted/web/test/test_http.py::ParsingTests::test_invalidNonAsciiMethod", "src/twisted/web/test/test_http.py::ParsingTests::test_malformedChunkedEncoding", "src/twisted/web/test/test_http.py::ParsingTests::test_multipartEmptyHeaderProcessingFailure", "src/twisted/web/test/test_http.py::ParsingTests::test_multipartFileData", "src/twisted/web/test/test_http.py::ParsingTests::test_multipartFormData", "src/twisted/web/test/test_http.py::ParsingTests::test_multipartProcessingFailure", "src/twisted/web/test/test_http.py::ParsingTests::test_tooManyHeaders", "src/twisted/web/test/test_http.py::ParsingTests::test_transferEncodingIdentity", "src/twisted/web/test/test_http.py::ParsingTests::test_unknownTransferEncoding", "src/twisted/web/test/test_http.py::QueryArgumentsTests::test_urlparse", "src/twisted/web/test/test_http.py::QueryArgumentsTests::test_urlparseRejectsUnicode", "src/twisted/web/test/test_http.py::ClientStatusParsingTests::testBaseline", "src/twisted/web/test/test_http.py::ClientStatusParsingTests::testNoMessage", "src/twisted/web/test/test_http.py::ClientStatusParsingTests::testNoMessage_trailingSpace", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieSameSite", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieSanitization", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieWithAllArgumentsBytes", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieWithAllArgumentsUnicode", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieWithMinimumArgumentsBytes", "src/twisted/web/test/test_http.py::RequestTests::test_addCookieWithMinimumArgumentsUnicode", "src/twisted/web/test/test_http.py::RequestTests::test_connectionLost", "src/twisted/web/test/test_http.py::RequestTests::test_connectionLostNotification", "src/twisted/web/test/test_http.py::RequestTests::test_eq", "src/twisted/web/test/test_http.py::RequestTests::test_eqWithNonRequest", "src/twisted/web/test/test_http.py::RequestTests::test_finishAfterConnectionLost", "src/twisted/web/test/test_http.py::RequestTests::test_finishCleansConnection", "src/twisted/web/test/test_http.py::RequestTests::test_finishNotification", "src/twisted/web/test/test_http.py::RequestTests::test_finishProducerStillRegistered", "src/twisted/web/test/test_http.py::RequestTests::test_finishProducesLog", "src/twisted/web/test/test_http.py::RequestTests::test_firstWrite", "src/twisted/web/test/test_http.py::RequestTests::test_firstWriteHTTP11Chunked", "src/twisted/web/test/test_http.py::RequestTests::test_firstWriteLastModified", "src/twisted/web/test/test_http.py::RequestTests::test_getAllHeaders", "src/twisted/web/test/test_http.py::RequestTests::test_getAllHeadersMultipleHeaders", "src/twisted/web/test/test_http.py::RequestTests::test_getAllHeadersNoHeaders", "src/twisted/web/test/test_http.py::RequestTests::test_getClientAddress", "src/twisted/web/test/test_http.py::RequestTests::test_getClientIPWithIPv4", "src/twisted/web/test/test_http.py::RequestTests::test_getClientIPWithIPv6", "src/twisted/web/test/test_http.py::RequestTests::test_getClientIPWithNonTCPPeer", "src/twisted/web/test/test_http.py::RequestTests::test_getHeader", "src/twisted/web/test/test_http.py::RequestTests::test_getHeaderNotFound", "src/twisted/web/test/test_http.py::RequestTests::test_getHeaderReceivedMultiples", "src/twisted/web/test/test_http.py::RequestTests::test_getRequestHostname", "src/twisted/web/test/test_http.py::RequestTests::test_hashable", "src/twisted/web/test/test_http.py::RequestTests::test_lastModifiedAlreadyWritten", "src/twisted/web/test/test_http.py::RequestTests::test_ne", "src/twisted/web/test/test_http.py::RequestTests::test_neWithNonRequest", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookies", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesContinueAfterMalformedCookie", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesEmptyCookie", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesEmptyValue", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesIgnoreValueless", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesMultipleHeaders", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesNoCookie", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesRetainRightSpace", "src/twisted/web/test/test_http.py::RequestTests::test_parseCookiesStripLeftSpace", "src/twisted/web/test/test_http.py::RequestTests::test_provides_IDeprecatedHTTPChannelToRequestInterface", "src/twisted/web/test/test_http.py::RequestTests::test_receivedCookiesDefault", "src/twisted/web/test/test_http.py::RequestTests::test_registerProducerTwiceFails", "src/twisted/web/test/test_http.py::RequestTests::test_registerProducerWhenNotQueuedRegistersPullProducer", "src/twisted/web/test/test_http.py::RequestTests::test_registerProducerWhenNotQueuedRegistersPushProducer", "src/twisted/web/test/test_http.py::RequestTests::test_reprInitialized", "src/twisted/web/test/test_http.py::RequestTests::test_reprSubclass", "src/twisted/web/test/test_http.py::RequestTests::test_reprUninitialized", "src/twisted/web/test/test_http.py::RequestTests::test_requestBodyTimeoutFromFactory", "src/twisted/web/test/test_http.py::RequestTests::test_setHeader", "src/twisted/web/test/test_http.py::RequestTests::test_setHost", "src/twisted/web/test/test_http.py::RequestTests::test_setHostNonDefaultPort", "src/twisted/web/test/test_http.py::RequestTests::test_setHostSSL", "src/twisted/web/test/test_http.py::RequestTests::test_setHostSSLNonDefaultPort", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedCached", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedIgnore", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedNeverSet", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedNotCached", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedTwiceCached", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedTwiceNotCached", "src/twisted/web/test/test_http.py::RequestTests::test_setLastModifiedUpdate", "src/twisted/web/test/test_http.py::RequestTests::test_setResponseCode", "src/twisted/web/test/test_http.py::RequestTests::test_setResponseCodeAcceptsIntegers", "src/twisted/web/test/test_http.py::RequestTests::test_setResponseCodeAcceptsLongIntegers", "src/twisted/web/test/test_http.py::RequestTests::test_setResponseCodeAndMessage", "src/twisted/web/test/test_http.py::RequestTests::test_setResponseCodeAndMessageNotBytes", "src/twisted/web/test/test_http.py::RequestTests::test_unregisterNonQueuedNonStreamingProducer", "src/twisted/web/test/test_http.py::RequestTests::test_unregisterNonQueuedStreamingProducer", "src/twisted/web/test/test_http.py::RequestTests::test_writeAfterConnectionLost", "src/twisted/web/test/test_http.py::RequestTests::test_writeAfterFinish", "src/twisted/web/test/test_http.py::MultilineHeadersTests::test_extractHeader", "src/twisted/web/test/test_http.py::MultilineHeadersTests::test_multilineHeaders", "src/twisted/web/test/test_http.py::MultilineHeadersTests::test_noHeaders", "src/twisted/web/test/test_http.py::Expect100ContinueServerTests::test_HTTP10", "src/twisted/web/test/test_http.py::Expect100ContinueServerTests::test_expect100ContinueHeader", "src/twisted/web/test/test_http.py::DeprecatedRequestAttributesTests::test_getClientIP", "src/twisted/web/test/test_http.py::DeprecatedRequestAttributesTests::test_noLongerQueued", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelCanUnregisterWithNoProducer", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelIsAProducer", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelPropagatesPausedProductionToRequest", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelPropagatesProducingFromTransportToTransport", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelRejectsMultipleProducers", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelStaysPausedWhenRequestCompletes", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelStopRequestProducer", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelStopWithNoRequestOutstanding", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelToleratesDataWhenTransportPaused", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelToleratesPullProducers", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelUnregistersSelfWhenCallingLoseConnection", "src/twisted/web/test/test_http.py::ChannelProductionTests::test_HTTPChannelUnregistersSelfWhenTimingOut", "src/twisted/web/test/test_http.py::HTTPChannelSanitizationTests::test_writeHeadersSanitizesLinearWhitespace", "src/twisted/web/test/test_http.py::HTTPClientSanitizationTests::test_sendHeaderSanitizesLinearWhitespace", "src/twisted/web/test/test_http.py::HexHelperTests::test_decodeNotHex", "src/twisted/web/test/test_http.py::HexHelperTests::test_decodes", "src/twisted/web/test/test_http.py::HexHelperTests::test_isHex", "src/twisted/web/test/test_http.py::HexHelperTests::test_isNotHex" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-09-20 16:19:56+00:00
mit
6,127
twisted__twisted-12040
diff --git a/src/twisted/logger/_format.py b/src/twisted/logger/_format.py index 4bc06ec40c..959f4867ad 100644 --- a/src/twisted/logger/_format.py +++ b/src/twisted/logger/_format.py @@ -6,6 +6,8 @@ Tools for formatting logging events. """ +from __future__ import annotations + from datetime import datetime as DateTime from typing import Any, Callable, Iterator, Mapping, Optional, Union, cast @@ -164,6 +166,51 @@ def formatEventAsClassicLogText( return eventText + "\n" +def keycall(key: str, getter: Callable[[str], Any]) -> PotentialCallWrapper: + """ + Check to see if C{key} ends with parentheses ("C{()}"); if not, wrap up the + result of C{get} in a L{PotentialCallWrapper}. Otherwise, call the result + of C{get} first, before wrapping it up. + + @param key: The last dotted segment of a formatting key, as parsed by + L{Formatter.vformat}, which may end in C{()}. + + @param getter: A function which takes a string and returns some other + object, to be formatted and stringified for a log. + + @return: A L{PotentialCallWrapper} that will wrap up the result to allow + for subsequent usages of parens to defer execution to log-format time. + """ + callit = key.endswith("()") + realKey = key[:-2] if callit else key + value = getter(realKey) + if callit: + value = value() + return PotentialCallWrapper(value) + + +class PotentialCallWrapper(object): + """ + Object wrapper that wraps C{getattr()} so as to process call-parentheses + C{"()"} after a dotted attribute access. + """ + + def __init__(self, wrapped: object) -> None: + self._wrapped = wrapped + + def __getattr__(self, name: str) -> object: + return keycall(name, self._wrapped.__getattribute__) + + def __format__(self, format_spec: str) -> str: + return self._wrapped.__format__(format_spec) + + def __repr__(self) -> str: + return self._wrapped.__repr__() + + def __str__(self) -> str: + return self._wrapped.__str__() + + class CallMapping(Mapping[str, Any]): """ Read-only mapping that turns a C{()}-suffix in key names into an invocation @@ -190,12 +237,7 @@ class CallMapping(Mapping[str, Any]): Look up an item in the submapping for this L{CallMapping}, calling it if C{key} ends with C{"()"}. """ - callit = key.endswith("()") - realKey = key[:-2] if callit else key - value = self._submapping[realKey] - if callit: - value = value() - return value + return keycall(key, self._submapping.__getitem__) def formatWithCall(formatString: str, mapping: Mapping[str, Any]) -> str: diff --git a/src/twisted/newsfragments/9347.bugfix b/src/twisted/newsfragments/9347.bugfix new file mode 100644 index 0000000000..2dbfc1676b --- /dev/null +++ b/src/twisted/newsfragments/9347.bugfix @@ -0,0 +1,4 @@ +twisted.logger.formatEvent now honors dotted method names, not just flat +function names, in format strings, as it has long been explicitly documented to +do. So, you will now get the expected result from `formatEvent("here's the +result of calling a method at log-format time: {obj.method()}", obj=...)`
twisted/twisted
311d8dbaf40ddeb887cd3edab1333a3180e9d4d9
diff --git a/src/twisted/logger/test/test_format.py b/src/twisted/logger/test/test_format.py index 67dbf0ce78..6c830ca9f2 100644 --- a/src/twisted/logger/test/test_format.py +++ b/src/twisted/logger/test/test_format.py @@ -36,6 +36,17 @@ class FormattingTests(unittest.TestCase): Tests for basic event formatting functions. """ + def format(self, logFormat: AnyStr, **event: object) -> str: + """ + Create a Twisted log event dictionary from C{event} with the given + C{logFormat} format string, format it with L{formatEvent}, ensure that + its type is L{str}, and return its result. + """ + event["log_format"] = logFormat + result = formatEvent(event) + self.assertIs(type(result), str) + return result + def test_formatEvent(self) -> None: """ L{formatEvent} will format an event according to several rules: @@ -53,27 +64,36 @@ class FormattingTests(unittest.TestCase): L{formatEvent} will always return L{str}, and if given bytes, will always treat its format string as UTF-8 encoded. """ - - def format(logFormat: AnyStr, **event: object) -> str: - event["log_format"] = logFormat - result = formatEvent(event) - self.assertIs(type(result), str) - return result - - self.assertEqual("", format(b"")) - self.assertEqual("", format("")) - self.assertEqual("abc", format("{x}", x="abc")) + self.assertEqual("", self.format(b"")) + self.assertEqual("", self.format("")) + self.assertEqual("abc", self.format("{x}", x="abc")) self.assertEqual( "no, yes.", - format("{not_called}, {called()}.", not_called="no", called=lambda: "yes"), + self.format( + "{not_called}, {called()}.", not_called="no", called=lambda: "yes" + ), ) - self.assertEqual("S\xe1nchez", format(b"S\xc3\xa1nchez")) - self.assertIn("Unable to format event", format(b"S\xe1nchez")) - maybeResult = format(b"S{a!s}nchez", a=b"\xe1") + self.assertEqual("S\xe1nchez", self.format(b"S\xc3\xa1nchez")) + self.assertIn("Unable to format event", self.format(b"S\xe1nchez")) + maybeResult = self.format(b"S{a!s}nchez", a=b"\xe1") self.assertIn("Sb'\\xe1'nchez", maybeResult) xe1 = str(repr(b"\xe1")) - self.assertIn("S" + xe1 + "nchez", format(b"S{a!r}nchez", a=b"\xe1")) + self.assertIn("S" + xe1 + "nchez", self.format(b"S{a!r}nchez", a=b"\xe1")) + + def test_formatMethod(self) -> None: + """ + L{formatEvent} will format PEP 3101 keys containing C{.}s ending with + C{()} as methods. + """ + + class World: + def where(self) -> str: + return "world" + + self.assertEqual( + "hello world", self.format("hello {what.where()}", what=World()) + ) def test_formatEventNoFormat(self) -> None: """
twisted.logger doesn't execute methods despite documentation |<img alt="ElementalAlchemist's avatar" src="https://avatars.githubusercontent.com/u/0?s=50" width="50" height="50">| ElementalAlchemist reported| |-|-| |Trac ID|trac#9347| |Type|defect| |Created|2017-12-06 02:56:36Z| It may come up that people want to log things based on data gotten from object methods, e.g. ``` self.ircd.log.debug("Disconnecting user {user.uuid} ({user.hostmask()}): {reason}", user=self, reason=reason) ``` where `user.hostmask()` is some sort of useful data. According to the documentation (https://twistedmatrix.com/documents/16.1.1/core/howto/logger.html#format-strings), not only is this allowed, but there is an example showing that this is explicitly allowed. However, attempting to log the above message results in Twisted logging something like this: ``` 2017-12-05 20:52:26-0600 [-] Unable to format event {'log_namespace': 'txircd', 'log_level': <LogLevel=debug>, 'format': '%(log_legacy)s', 'log_logger': <Logger 'txircd'>, 'log_source': None, 'system': '-', 'reason': 'Registration timeout', 'user': <txircd.user.IRCUser instance at 0x7f0c092e8050>, 'time': 1512528746.643236, 'log_format': 'Disconnecting user {user.uuid} ({user.hostmask()}): {reason}', 'message': (), 'log_time': 1512528746.643236}: IRCUser instance has no attribute 'hostmask()' ``` Instead, in order to get the desired logging, you need to modify it so that the functions aren't run on objects in the string: ``` self.ircd.log.debug("Disconnecting user {user.uuid} ({hostmask()}): {reason}", user=self, hostmask=self.hostmask, reason=reason) ``` This logs as expected, but the need to change to this doesn't match up with what the documentation says. Either object methods need to be allowed, or the documentation needs to be changed to disallow it (including modifying the example where an object method is explicitly used in this way). <details><summary>Searchable metadata</summary> ``` trac-id__9347 9347 type__defect defect reporter__ElementalAlchemist ElementalAlchemist priority__normal normal milestone__None None branch__ branch_author__ status__new new resolution__None None component__logger logger keywords__None None time__1512528996358368 1512528996358368 changetime__1513653408400714 1513653408400714 version__None None owner__None None ``` </details>
0.0
311d8dbaf40ddeb887cd3edab1333a3180e9d4d9
[ "src/twisted/logger/test/test_format.py::FormattingTests::test_formatMethod" ]
[ "src/twisted/logger/test/test_format.py::FormattingTests::test_formatEvent", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatEventNoFormat", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatEventWeirdFormat", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatUnformattableEvent", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatUnformattableEventWithUnformattableErrorOMGWillItStop", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatUnformattableEventWithUnformattableKey", "src/twisted/logger/test/test_format.py::FormattingTests::test_formatUnformattableEventWithUnformattableValue", "src/twisted/logger/test/test_format.py::TimeFormattingTests::test_formatTimePercentF", "src/twisted/logger/test/test_format.py::TimeFormattingTests::test_formatTimeWithAlternateTimeFormat", "src/twisted/logger/test/test_format.py::TimeFormattingTests::test_formatTimeWithDefaultFormat", "src/twisted/logger/test/test_format.py::TimeFormattingTests::test_formatTimeWithNoFormat", "src/twisted/logger/test/test_format.py::TimeFormattingTests::test_formatTimeWithNoTime", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatEmptyFormat", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatFormat", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatFormatMultiLine", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatLevel", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatNamespace", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatNoFormat", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatSystem", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatSystemRulz", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatSystemUnformattable", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatTimeCustom", "src/twisted/logger/test/test_format.py::ClassicLogFormattingTests::test_formatTimeDefault", "src/twisted/logger/test/test_format.py::FormatFieldTests::test_formatWithCall", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventAsTextSystemMissing", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventAsTextSystemMissingLevelOnly", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventAsTextSystemMissingNamespaceAndLevel", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventAsTextSystemOnly", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventAsTextTimestampOnly", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_eventWithTraceback", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatEmptyEventWithTraceback", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatEventNonCritical", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatEventUnformattableTraceback", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatTracebackHandlesUTF8DecodeFailure", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatTracebackMultibyte", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatUnformattableErrorWithTraceback", "src/twisted/logger/test/test_format.py::EventAsTextTests::test_formatUnformattableWithTraceback" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-11-27 21:03:54+00:00
mit
6,128
twisted__twisted-12045
diff --git a/docs/core/howto/tutorial/intro.rst b/docs/core/howto/tutorial/intro.rst index 2929f74cc0..07e2996f31 100644 --- a/docs/core/howto/tutorial/intro.rst +++ b/docs/core/howto/tutorial/intro.rst @@ -395,29 +395,18 @@ server does. Read Status from the Web ------------------------ - - -The web. That invention which has infiltrated homes around the -world finally gets through to our invention. In this case we use the -built-in Twisted web client -via ``twisted.web.client.getPage`` , a non-blocking version of -Python's :func:`urllib2.urlopen(URL).read <urllib2.urlopen>` . -Like ``getProcessOutput`` it returns a Deferred which will be -called back with a string, and can thus be used as a drop-in -replacement. - - - +The web. That invention which has infiltrated homes around the world finally +gets through to our invention. In this case we use the built-in Twisted web +client via ``twisted.web.client.getPage`` , a non-blocking version of Python's +:func:`urllib.urlopen(URL).read <urllib.request.urlopen>` . Like +``getProcessOutput`` it returns a Deferred which will be called back with a +string, and can thus be used as a drop-in replacement. Thus, we have examples of three different database back-ends, none of which change the protocol class. In fact, we will not have to change the protocol again until the end of this tutorial: we have achieved, here, one truly usable class. - - - - :download:`finger10.py <listings/finger/finger10.py>` .. literalinclude:: listings/finger/finger10.py diff --git a/docs/web/howto/client.rst b/docs/web/howto/client.rst index e3c149dd26..5412c155d9 100644 --- a/docs/web/howto/client.rst +++ b/docs/web/howto/client.rst @@ -712,22 +712,12 @@ what other kinds of endpoints exist. Handling HTTP cookies ~~~~~~~~~~~~~~~~~~~~~ - - - An existing agent instance can be wrapped with -:py:class:`twisted.web.client.CookieAgent` to automatically -store, send and track HTTP cookies. A ``CookieJar`` -instance, from the Python standard library module -`cookielib <http://docs.python.org/library/cookielib.html>`_ , is -used to store the cookie information. An example of using -``CookieAgent`` to perform a request and display the collected -cookies might look like this: - - - - - +:py:class:`twisted.web.client.CookieAgent` to automatically store, send and +track HTTP cookies. A ``CookieJar`` instance, from the Python standard library +module `http.cookiejar <http://docs.python.org/library/http.cookiejar.html>`_ , +is used to store the cookie information. An example of using ``CookieAgent`` to +perform a request and display the collected cookies might look like this: :download:`cookies.py <listings/client/cookies.py>` diff --git a/docs/web/howto/listings/client/cookies.py b/docs/web/howto/listings/client/cookies.py index f82a4c1d3e..bdaf966d0b 100644 --- a/docs/web/howto/listings/client/cookies.py +++ b/docs/web/howto/listings/client/cookies.py @@ -1,5 +1,7 @@ +from http.cookiejar import CookieJar + from twisted.internet import reactor -from twisted.python import compat, log +from twisted.python import log from twisted.web.client import Agent, CookieAgent @@ -12,7 +14,7 @@ def displayCookies(response, cookieJar): def main(): - cookieJar = compat.cookielib.CookieJar() + cookieJar = CookieJar() agent = CookieAgent(Agent(reactor), cookieJar) d = agent.request(b"GET", b"http://httpbin.org/cookies/set?some=data") diff --git a/src/twisted/web/client.py b/src/twisted/web/client.py index 9a0d5e9e10..e66b0cf317 100644 --- a/src/twisted/web/client.py +++ b/src/twisted/web/client.py @@ -6,13 +6,16 @@ HTTP client. """ +from __future__ import annotations import collections import os import warnings import zlib +from dataclasses import dataclass from functools import wraps -from typing import Iterable +from http.cookiejar import CookieJar +from typing import TYPE_CHECKING, Iterable, Optional from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse from zope.interface import implementer @@ -21,6 +24,7 @@ from incremental import Version from twisted.internet import defer, protocol, task from twisted.internet.abstract import isIPv6Address +from twisted.internet.defer import Deferred from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS from twisted.internet.interfaces import IOpenSSLContextFactory, IProtocol from twisted.logger import Logger @@ -43,6 +47,20 @@ from twisted.web.iweb import ( IResponse, ) +# For the purpose of type-checking we want our faked-out types to be identical to the types they are replacing. +# For the purpose of the impementation, we want to start +# with a blank slate so that we don't accidentally use +# any of the real implementation. + +if TYPE_CHECKING: + from email.message import EmailMessage as _InfoType + from http.client import HTTPResponse as _ResponseBase + from urllib.request import Request as _RequestBase +else: + _RequestBase = object + _ResponseBase = object + _InfoType = object + def urlunparse(parts): result = _urlunparse(tuple(p.decode("charmap") for p in parts)) @@ -1200,36 +1218,38 @@ class ProxyAgent(_AgentBase): ) -class _FakeUrllib2Request: +class _FakeStdlibRequest(_RequestBase): """ - A fake C{urllib2.Request} object for C{cookielib} to work with. + A fake L{urllib.request.Request} object for L{cookiejar} to work with. - @see: U{http://docs.python.org/library/urllib2.html#request-objects} + @see: U{urllib.request.Request + <https://docs.python.org/3/library/urllib.request.html#urllib.request.Request>} - @type uri: native L{str} @ivar uri: Request URI. - @type headers: L{twisted.web.http_headers.Headers} @ivar headers: Request headers. - @type type: native L{str} @ivar type: The scheme of the URI. - @type host: native L{str} @ivar host: The host[:port] of the URI. @since: 11.1 """ - def __init__(self, uri): + uri: str + type: str + host: str + # The received headers managed using Twisted API. + _twistedHeaders: Headers + + def __init__(self, uri: bytes) -> None: """ - Create a fake Urllib2 request. + Create a fake request. @param uri: Request URI. - @type uri: L{bytes} """ self.uri = nativeString(uri) - self.headers = Headers() + self._twistedHeaders = Headers() _uri = URI.fromBytes(uri) self.type = nativeString(_uri.scheme) @@ -1240,19 +1260,19 @@ class _FakeUrllib2Request: self.host += ":" + str(_uri.port) self.origin_req_host = nativeString(_uri.host) - self.unverifiable = lambda _: False + self.unverifiable = False def has_header(self, header): - return self.headers.hasHeader(networkString(header)) + return self._twistedHeaders.hasHeader(networkString(header)) def add_unredirected_header(self, name, value): - self.headers.addRawHeader(networkString(name), networkString(value)) + self._twistedHeaders.addRawHeader(networkString(name), networkString(value)) def get_full_url(self): return self.uri def get_header(self, name, default=None): - headers = self.headers.getRawHeaders(networkString(name), default) + headers = self._twistedHeaders.getRawHeaders(networkString(name), default) if headers is not None: headers = [nativeString(x) for x in headers] return headers[0] @@ -1269,62 +1289,68 @@ class _FakeUrllib2Request: return False -class _FakeUrllib2Response: +@dataclass +class _FakeUrllibResponseInfo(_InfoType): + response: IResponse + + def get_all(self, name: str, default: bytes) -> list[str]: # type:ignore[override] + headers = self.response.headers.getRawHeaders(networkString(name), default) + h = [nativeString(x) for x in headers] + return h + + +class _FakeStdlibResponse(_ResponseBase): """ - A fake C{urllib2.Response} object for C{cookielib} to work with. + A fake L{urllib.response.Response} object for L{http.cookiejar} to work + with. - @type response: C{twisted.web.iweb.IResponse} @ivar response: Underlying Twisted Web response. @since: 11.1 """ - def __init__(self, response): - self.response = response + response: IResponse - def info(self): - class _Meta: - def getheaders(zelf, name): - # PY2 - headers = self.response.headers.getRawHeaders(name, []) - return headers - - def get_all(zelf, name, default): - # PY3 - headers = self.response.headers.getRawHeaders( - networkString(name), default - ) - h = [nativeString(x) for x in headers] - return h + def __init__(self, response: IResponse) -> None: + self.response = response - return _Meta() + def info(self) -> _InfoType: + result = _FakeUrllibResponseInfo(self.response) + return result @implementer(IAgent) class CookieAgent: """ - L{CookieAgent} extends the basic L{Agent} to add RFC-compliant - handling of HTTP cookies. Cookies are written to and extracted - from a C{cookielib.CookieJar} instance. + L{CookieAgent} extends the basic L{Agent} to add RFC-compliant handling of + HTTP cookies. Cookies are written to and extracted from a L{CookieJar} + instance. The same cookie jar instance will be used for any requests through this agent, mutating it whenever a I{Set-Cookie} header appears in a response. - @type _agent: L{twisted.web.client.Agent} @ivar _agent: Underlying Twisted Web agent to issue requests through. - @type cookieJar: C{cookielib.CookieJar} @ivar cookieJar: Initialized cookie jar to read cookies from and store cookies to. @since: 11.1 """ - def __init__(self, agent, cookieJar): + _agent: IAgent + cookieJar: CookieJar + + def __init__(self, agent: IAgent, cookieJar: CookieJar) -> None: self._agent = agent self.cookieJar = cookieJar - def request(self, method, uri, headers=None, bodyProducer=None): + def request( + self, + method: bytes, + uri: bytes, + headers: Optional[Headers] = None, + bodyProducer: Optional[IBodyProducer] = None, + ) -> Deferred[IResponse]: """ Issue a new request to the wrapped L{Agent}. @@ -1337,33 +1363,33 @@ class CookieAgent: @see: L{Agent.request} """ - if headers is None: - headers = Headers() - lastRequest = _FakeUrllib2Request(uri) + actualHeaders = headers if headers is not None else Headers() + lastRequest = _FakeStdlibRequest(uri) # Setting a cookie header explicitly will disable automatic request # cookies. - if not headers.hasHeader(b"cookie"): + if not actualHeaders.hasHeader(b"cookie"): self.cookieJar.add_cookie_header(lastRequest) cookieHeader = lastRequest.get_header("Cookie", None) if cookieHeader is not None: - headers = headers.copy() - headers.addRawHeader(b"cookie", networkString(cookieHeader)) + actualHeaders = actualHeaders.copy() + actualHeaders.addRawHeader(b"cookie", networkString(cookieHeader)) - d = self._agent.request(method, uri, headers, bodyProducer) - d.addCallback(self._extractCookies, lastRequest) - return d + return self._agent.request( + method, uri, actualHeaders, bodyProducer + ).addCallback(self._extractCookies, lastRequest) - def _extractCookies(self, response, request): + def _extractCookies( + self, response: IResponse, request: _FakeStdlibRequest + ) -> IResponse: """ Extract response cookies and store them in the cookie jar. - @type response: L{twisted.web.iweb.IResponse} - @param response: Twisted Web response. + @param response: the Twisted Web response that we are processing. - @param request: A urllib2 compatible request object. + @param request: A L{_FakeStdlibRequest} wrapping our Twisted request, + for L{CookieJar} to extract cookies from. """ - resp = _FakeUrllib2Response(response) - self.cookieJar.extract_cookies(resp, request) + self.cookieJar.extract_cookies(_FakeStdlibResponse(response), request) return response diff --git a/src/twisted/web/newsfragments/12044.bugfix b/src/twisted/web/newsfragments/12044.bugfix new file mode 100644 index 0000000000..6aef72af5e --- /dev/null +++ b/src/twisted/web/newsfragments/12044.bugfix @@ -0,0 +1,2 @@ +The documentation for twisted.web.client.CookieAgent no longer references +long-deprecated ``cookielib`` and ``urllib2`` standard library modules.
twisted/twisted
bafd067766898b8a0769a63eab0a2e72d6dc94fa
diff --git a/src/twisted/web/test/test_agent.py b/src/twisted/web/test/test_agent.py index 9cee5b75a0..d042f9caf7 100644 --- a/src/twisted/web/test/test_agent.py +++ b/src/twisted/web/test/test_agent.py @@ -4,6 +4,9 @@ """ Tests for L{twisted.web.client.Agent} and related new client APIs. """ + +from __future__ import annotations + import zlib from http.cookiejar import CookieJar from io import BytesIO @@ -1281,7 +1284,7 @@ class AgentTests( self.assertIsInstance(req, Request) resp = client.Response._construct( - (b"HTTP", 1, 1), 200, b"OK", client.Headers({}), None, req + (b"HTTP", 1, 1), 200, b"OK", Headers({}), None, req ) res.callback(resp) @@ -1313,7 +1316,7 @@ class AgentTests( """ L{Request.absoluteURI} is L{None} if L{Request._parsedURI} is L{None}. """ - request = client.Request(b"FOO", b"/", client.Headers(), None) + request = client.Request(b"FOO", b"/", Headers(), None) self.assertIdentical(request.absoluteURI, None) def test_endpointFactory(self): @@ -1368,7 +1371,7 @@ class AgentMethodInjectionTests( """ agent = client.Agent(self.createReactor()) uri = b"http://twisted.invalid" - agent.request(method, uri, client.Headers(), None) + agent.request(method, uri, Headers(), None) class AgentURIInjectionTests( @@ -1388,7 +1391,7 @@ class AgentURIInjectionTests( """ agent = client.Agent(self.createReactor()) method = b"GET" - agent.request(method, uri, client.Headers(), None) + agent.request(method, uri, Headers(), None) @skipIf(not sslPresent, "SSL not present, cannot run SSL tests.") @@ -1795,9 +1798,7 @@ class HTTPConnectionPoolRetryTests(TestCase, FakeReactorAndConnectMixin): return defer.succeed(protocol) bodyProducer = object() - request = client.Request( - b"FOO", b"/", client.Headers(), bodyProducer, persistent=True - ) + request = client.Request(b"FOO", b"/", Headers(), bodyProducer, persistent=True) newProtocol() protocol = protocols[0] retrier = client._RetryingHTTP11ClientProtocol(protocol, newProtocol) @@ -1936,32 +1937,36 @@ class CookieTestsMixin: Mixin for unit tests dealing with cookies. """ - def addCookies(self, cookieJar, uri, cookies): + def addCookies( + self, cookieJar: CookieJar, uri: bytes, cookies: list[bytes] + ) -> tuple[client._FakeStdlibRequest, client._FakeStdlibResponse]: """ Add a cookie to a cookie jar. """ - response = client._FakeUrllib2Response( + response = client._FakeStdlibResponse( client.Response( (b"HTTP", 1, 1), 200, b"OK", - client.Headers({b"Set-Cookie": cookies}), + Headers({b"Set-Cookie": cookies}), None, ) ) - request = client._FakeUrllib2Request(uri) + request = client._FakeStdlibRequest(uri) cookieJar.extract_cookies(response, request) return request, response class CookieJarTests(TestCase, CookieTestsMixin): """ - Tests for L{twisted.web.client._FakeUrllib2Response} and - L{twisted.web.client._FakeUrllib2Request}'s interactions with - L{CookieJar} instances. + Tests for L{twisted.web.client._FakeStdlibResponse} and + L{twisted.web.client._FakeStdlibRequest}'s interactions with L{CookieJar} + instances. """ - def makeCookieJar(self): + def makeCookieJar( + self, + ) -> tuple[CookieJar, tuple[client._FakeStdlibRequest, client._FakeStdlibResponse]]: """ @return: a L{CookieJar} with some sample cookies """ @@ -1973,10 +1978,11 @@ class CookieJarTests(TestCase, CookieTestsMixin): ) return cookieJar, reqres - def test_extractCookies(self): + def test_extractCookies(self) -> None: """ - L{CookieJar.extract_cookies} extracts cookie information from - fake urllib2 response instances. + L{CookieJar.extract_cookies} extracts cookie information from our + stdlib-compatibility wrappers, L{client._FakeStdlibRequest} and + L{client._FakeStdlibResponse}. """ jar = self.makeCookieJar()[0] cookies = {c.name: c for c in jar} @@ -1997,17 +2003,20 @@ class CookieJarTests(TestCase, CookieTestsMixin): self.assertEqual(cookie.comment, "goodbye") self.assertIdentical(cookie.get_nonstandard_attr("cow"), None) - def test_sendCookie(self): + def test_sendCookie(self) -> None: """ - L{CookieJar.add_cookie_header} adds a cookie header to a fake - urllib2 request instance. + L{CookieJar.add_cookie_header} adds a cookie header to a Twisted + request via our L{client._FakeStdlibRequest} wrapper. """ jar, (request, response) = self.makeCookieJar() self.assertIdentical(request.get_header("Cookie", None), None) jar.add_cookie_header(request) - self.assertEqual(request.get_header("Cookie", None), "foo=1; bar=2") + self.assertEqual( + list(request._twistedHeaders.getAllRawHeaders()), + [(b"Cookie", [b"foo=1; bar=2"])], + ) class CookieAgentTests( @@ -2057,7 +2066,7 @@ class CookieAgentTests( (b"HTTP", 1, 1), 200, b"OK", - client.Headers( + Headers( { b"Set-Cookie": [ b"foo=1", @@ -2070,6 +2079,26 @@ class CookieAgentTests( return d + def test_leaveExistingCookieHeader(self) -> None: + """ + L{CookieAgent.request} will not insert a C{'Cookie'} header into the + L{Request} object when there is already a C{'Cookie'} header in the + request headers parameter. + """ + uri = b"http://example.com:1234/foo?bar" + cookie = b"foo=1" + + cookieJar = CookieJar() + self.addCookies(cookieJar, uri, [cookie]) + self.assertEqual(len(list(cookieJar)), 1) + + agent = self.buildAgentForWrapperTest(self.reactor) + cookieAgent = client.CookieAgent(agent, cookieJar) + cookieAgent.request(b"GET", uri, Headers({"cookie": ["already-set"]})) + + req, res = self.protocol.requests.pop() + self.assertEqual(req.headers.getRawHeaders(b"cookie"), [b"already-set"]) + def test_requestWithCookie(self): """ L{CookieAgent.request} inserts a C{'Cookie'} header into the L{Request}
remove all references to `urllib2` and `cookielib` It's been a decade or so since these modules were deprecated, and it would be good to clean up both our docs and our implementation to stop referring to them.
0.0
bafd067766898b8a0769a63eab0a2e72d6dc94fa
[ "src/twisted/web/test/test_agent.py::CookieJarTests::test_extractCookies", "src/twisted/web/test/test_agent.py::CookieJarTests::test_sendCookie", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_leaveExistingCookieHeader", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_portCookie", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_portCookieOnWrongPort", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_requestWithCookie", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_secureCookieOnInsecureConnection" ]
[ "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_cancelWhileProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_defaultCooperator", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_failedReadWhileProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_inputClosedAtEOF", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_interface", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_knownLength", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_multipleStop", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_pauseProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_resumeProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_startProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_stopProducing", "src/twisted/web/test/test_agent.py::FileBodyProducerTests::test_unknownLength", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_cancelGetConnectionCancelsEndpointConnect", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_closeCachedConnections", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_getCachedConnection", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_getReturnsNewIfCacheEmpty", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_getSkipsDisconnected", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_getUsesQuiescentCallback", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_maxPersistentPerHost", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_newConnection", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_putExceedsMaxPersistent", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_putNotQuiescent", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolTests::test_putStartsTimeout", "src/twisted/web/test/test_agent.py::AgentTests::test_bindAddress", "src/twisted/web/test/test_agent.py::AgentTests::test_connectHTTP", "src/twisted/web/test/test_agent.py::AgentTests::test_connectTimeout", "src/twisted/web/test/test_agent.py::AgentTests::test_connectUsesConnectionPool", "src/twisted/web/test/test_agent.py::AgentTests::test_connectionFailed", "src/twisted/web/test/test_agent.py::AgentTests::test_defaultPool", "src/twisted/web/test/test_agent.py::AgentTests::test_endpointFactory", "src/twisted/web/test/test_agent.py::AgentTests::test_endpointFactoryDefaultPool", "src/twisted/web/test/test_agent.py::AgentTests::test_endpointFactoryPool", "src/twisted/web/test/test_agent.py::AgentTests::test_headersUnmodified", "src/twisted/web/test/test_agent.py::AgentTests::test_hostIPv6Bracketed", "src/twisted/web/test/test_agent.py::AgentTests::test_hostOverride", "src/twisted/web/test/test_agent.py::AgentTests::test_hostProvided", "src/twisted/web/test/test_agent.py::AgentTests::test_hostValueNonStandardHTTP", "src/twisted/web/test/test_agent.py::AgentTests::test_hostValueNonStandardHTTPS", "src/twisted/web/test/test_agent.py::AgentTests::test_hostValueStandardHTTP", "src/twisted/web/test/test_agent.py::AgentTests::test_hostValueStandardHTTPS", "src/twisted/web/test/test_agent.py::AgentTests::test_integrationTestIPv4", "src/twisted/web/test/test_agent.py::AgentTests::test_integrationTestIPv4Address", "src/twisted/web/test/test_agent.py::AgentTests::test_integrationTestIPv6", "src/twisted/web/test/test_agent.py::AgentTests::test_integrationTestIPv6Address", "src/twisted/web/test/test_agent.py::AgentTests::test_interface", "src/twisted/web/test/test_agent.py::AgentTests::test_nonBytesMethod", "src/twisted/web/test/test_agent.py::AgentTests::test_nonDecodableURI", "src/twisted/web/test/test_agent.py::AgentTests::test_nonPersistent", "src/twisted/web/test/test_agent.py::AgentTests::test_persistent", "src/twisted/web/test/test_agent.py::AgentTests::test_request", "src/twisted/web/test/test_agent.py::AgentTests::test_requestAbsoluteURI", "src/twisted/web/test/test_agent.py::AgentTests::test_requestMissingAbsoluteURI", "src/twisted/web/test/test_agent.py::AgentTests::test_responseIncludesRequest", "src/twisted/web/test/test_agent.py::AgentTests::test_unsupportedScheme", "src/twisted/web/test/test_agent.py::AgentMethodInjectionTests::test_methodWithCLRFRejected", "src/twisted/web/test/test_agent.py::AgentMethodInjectionTests::test_methodWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::AgentMethodInjectionTests::test_methodWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_hostWithCRLFRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_hostWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_hostWithWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_pathWithCRLFRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_pathWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::AgentURIInjectionTests::test_pathWithWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::WebClientContextFactoryTests::test_deprecated", "src/twisted/web/test/test_agent.py::WebClientContextFactoryTests::test_missingSSL", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_dontRetryIfFailedDueToCancel", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_dontRetryIfRetryAutomaticallyFalse", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_dontRetryIfShouldRetryReturnsFalse", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_notWrappedOnNewReturned", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_onlyRetryIdempotentMethods", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_onlyRetryIfNoResponseReceived", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_onlyRetryOnce", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_onlyRetryWithoutBody", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_retryIfFailedDueToNonCancelException", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_retryIfShouldRetryReturnsTrue", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_retryWithNewConnection", "src/twisted/web/test/test_agent.py::HTTPConnectionPoolRetryTests::test_wrappedOnPersistentReturned", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_emptyCookieJarRequest", "src/twisted/web/test/test_agent.py::CookieAgentTests::test_interface", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_acceptHeaders", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_existingHeaders", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_interface", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_plainEncodingResponse", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_unknownEncoding", "src/twisted/web/test/test_agent.py::ContentDecoderAgentTests::test_unsupportedEncoding", "src/twisted/web/test/test_agent.py::ContentDecoderAgentWithGzipTests::test_brokenContent", "src/twisted/web/test/test_agent.py::ContentDecoderAgentWithGzipTests::test_flushData", "src/twisted/web/test/test_agent.py::ContentDecoderAgentWithGzipTests::test_flushError", "src/twisted/web/test/test_agent.py::ContentDecoderAgentWithGzipTests::test_gzipEncodingResponse", "src/twisted/web/test/test_agent.py::ProxyAgentTests::test_connectUsesConnectionPool", "src/twisted/web/test/test_agent.py::ProxyAgentTests::test_interface", "src/twisted/web/test/test_agent.py::ProxyAgentTests::test_nonBytesMethod", "src/twisted/web/test/test_agent.py::ProxyAgentTests::test_nonPersistent", "src/twisted/web/test/test_agent.py::ProxyAgentTests::test_proxyRequest", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_301OnPost", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_302OnPost", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_307OnPost", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_crossDomainHeaders", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_crossPortHeaders", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_interface", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_noLocationField", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_noRedirect", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirect301", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirect302", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirect303", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirect307", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirect308", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_redirectLimit", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_relativeURI", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_relativeURIPreserveFragments", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_relativeURISchemeRelative", "src/twisted/web/test/test_agent.py::RedirectAgentTests::test_responseHistory", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_307OnPost", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_crossDomainHeaders", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_crossPortHeaders", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_interface", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_noLocationField", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_noRedirect", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirect301", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirect302", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirect303", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirect307", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirect308", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirectLimit", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirectToGet301", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_redirectToGet302", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_relativeURI", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_relativeURIPreserveFragments", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_relativeURISchemeRelative", "src/twisted/web/test/test_agent.py::BrowserLikeRedirectAgentTests::test_responseHistory", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_cancel", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_deprecatedTransport", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_deprecatedTransportNoWarning", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_otherErrors", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_success", "src/twisted/web/test/test_agent.py::ReadBodyTests::test_withPotentialDataLoss", "src/twisted/web/test/test_agent.py::RequestMethodInjectionTests::test_methodWithCLRFRejected", "src/twisted/web/test/test_agent.py::RequestMethodInjectionTests::test_methodWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestMethodInjectionTests::test_methodWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToMethodInjectionTests::test_methodWithCLRFRejected", "src/twisted/web/test/test_agent.py::RequestWriteToMethodInjectionTests::test_methodWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToMethodInjectionTests::test_methodWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_hostWithCRLFRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_hostWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_hostWithWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_pathWithCRLFRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_pathWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestURIInjectionTests::test_pathWithWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_hostWithCRLFRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_hostWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_hostWithWithUnprintableASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_pathWithCRLFRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_pathWithNonASCIIRejected", "src/twisted/web/test/test_agent.py::RequestWriteToURIInjectionTests::test_pathWithWithUnprintableASCIIRejected" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-30 01:49:24+00:00
mit
6,129
twisted__twisted-12047
diff --git a/src/twisted/conch/insults/insults.py b/src/twisted/conch/insults/insults.py index 4640aab368..ff5edf45b0 100644 --- a/src/twisted/conch/insults/insults.py +++ b/src/twisted/conch/insults/insults.py @@ -431,23 +431,7 @@ _KEY_NAMES = ( "CONTROL", ) - -class _const: - """ - @ivar name: A string naming this constant - """ - - def __init__(self, name: str) -> None: - self.name = name - - def __repr__(self) -> str: - return "[" + self.name + "]" - - def __bytes__(self) -> bytes: - return ("[" + self.name + "]").encode("ascii") - - -FUNCTION_KEYS = [_const(_name).__bytes__() for _name in _KEY_NAMES] +FUNCTION_KEYS = [f"[{_name}]".encode("ascii") for _name in _KEY_NAMES] @implementer(ITerminalTransport) diff --git a/src/twisted/conch/insults/window.py b/src/twisted/conch/insults/window.py index c93fae7b21..da0fc1e08e 100644 --- a/src/twisted/conch/insults/window.py +++ b/src/twisted/conch/insults/window.py @@ -6,6 +6,8 @@ Simple insults-based widget library @author: Jp Calderone """ +from __future__ import annotations + import array from twisted.conch.insults import helper, insults @@ -47,7 +49,8 @@ class Widget: focused = False parent = None dirty = False - width = height = None + width: int | None = None + height: int | None = None def repaint(self): if not self.dirty: @@ -109,7 +112,12 @@ class Widget: name = keyID if not isinstance(keyID, str): name = name.decode("utf-8") - func = getattr(self, "func_" + name, None) + + # Peel off the square brackets added by the computed definition of + # twisted.conch.insults.insults.FUNCTION_KEYS. + methodName = "func_" + name[1:-1] + + func = getattr(self, methodName, None) if func is not None: func(modifier) diff --git a/src/twisted/conch/newsfragments/12046.bugfix b/src/twisted/conch/newsfragments/12046.bugfix new file mode 100644 index 0000000000..2f9b269f0d --- /dev/null +++ b/src/twisted/conch/newsfragments/12046.bugfix @@ -0,0 +1,1 @@ +twisted.conch.insults.window.Widget.functionKeyReceived now dispatches functional key events to corresponding `func_KEYNAME` methods, where `KEYNAME` can be `F1`, `F2`, `HOME`, `UP_ARROW` etc. This is a regression introduced with #8214 in Twisted 16.5.0, where events changed from `const` objects to bytestrings in square brackets like `[F1]`. \ No newline at end of file
twisted/twisted
63df84e454978bd7a2d57ed292913384ca352e1a
diff --git a/src/twisted/conch/test/test_window.py b/src/twisted/conch/test/test_window.py index bcb0755a0a..9bfb53ee47 100644 --- a/src/twisted/conch/test/test_window.py +++ b/src/twisted/conch/test/test_window.py @@ -5,7 +5,14 @@ from __future__ import annotations from typing import Callable -from twisted.conch.insults.window import ScrolledArea, TextOutput, TopWindow +from twisted.conch.insults.insults import ServerProtocol +from twisted.conch.insults.window import ( + ScrolledArea, + Selection, + TextOutput, + TopWindow, + Widget, +) from twisted.trial.unittest import TestCase @@ -66,3 +73,100 @@ class ScrolledAreaTests(TestCase): scrolled = ScrolledArea(widget) self.assertIs(widget.parent, scrolled._viewport) self.assertIs(scrolled._viewport.parent, scrolled) + + +class SelectionTests(TestCase): + """ + Change focused entry in L{Selection} using function keys. + """ + + def setUp(self) -> None: + """ + Create L{ScrolledArea} widget with 10 elements and position selection to 5th element. + """ + seq: list[bytes] = [f"{_num}".encode("ascii") for _num in range(10)] + self.widget = Selection(seq, None) + self.widget.height = 10 + self.widget.focusedIndex = 5 + + def test_selectionDownArrow(self) -> None: + """ + Send DOWN_ARROW to select element just below the current one. + """ + self.widget.keystrokeReceived(ServerProtocol.DOWN_ARROW, None) # type: ignore[attr-defined] + self.assertIs(self.widget.focusedIndex, 6) + + def test_selectionUpArrow(self) -> None: + """ + Send UP_ARROW to select element just above the current one. + """ + self.widget.keystrokeReceived(ServerProtocol.UP_ARROW, None) # type: ignore[attr-defined] + self.assertIs(self.widget.focusedIndex, 4) + + def test_selectionPGDN(self) -> None: + """ + Send PGDN to select element one page down (here: last element). + """ + self.widget.keystrokeReceived(ServerProtocol.PGDN, None) # type: ignore[attr-defined] + self.assertIs(self.widget.focusedIndex, 9) + + def test_selectionPGUP(self) -> None: + """ + Send PGUP to select element one page up (here: first element). + """ + self.widget.keystrokeReceived(ServerProtocol.PGUP, None) # type: ignore[attr-defined] + self.assertIs(self.widget.focusedIndex, 0) + + +class RecordingWidget(Widget): + """ + A dummy Widget implementation to test handling of function keys by + recording keyReceived events. + """ + + def __init__(self) -> None: + Widget.__init__(self) + self.triggered: list[str] = [] + + def func_F1(self, modifier: str) -> None: + self.triggered.append("F1") + + def func_HOME(self, modifier: str) -> None: + self.triggered.append("HOME") + + def func_DOWN_ARROW(self, modifier: str) -> None: + self.triggered.append("DOWN_ARROW") + + def func_UP_ARROW(self, modifier: str) -> None: + self.triggered.append("UP_ARROW") + + def func_PGDN(self, modifier: str) -> None: + self.triggered.append("PGDN") + + def func_PGUP(self, modifier: str) -> None: + self.triggered.append("PGUP") + + +class WidgetFunctionKeyTests(TestCase): + """ + Call functionKeyReceived with key values from insults.ServerProtocol + """ + + def test_functionKeyReceivedDispatch(self) -> None: + """ + L{Widget.functionKeyReceived} dispatches its input, a constant on + ServerProtocol, to a matched C{func_KEY} method. + """ + widget = RecordingWidget() + + def checkOneKey(key: str) -> None: + widget.functionKeyReceived(getattr(ServerProtocol, key), None) + self.assertEqual([key], widget.triggered) + widget.triggered.clear() + + checkOneKey("F1") + checkOneKey("HOME") + checkOneKey("DOWN_ARROW") + checkOneKey("UP_ARROW") + checkOneKey("PGDN") + checkOneKey("PGUP")
Conch widgets are ignoring function keys **Describe the incorrect behavior you saw** `conch.insults.window.Widget` objects are ignoring function keys **Describe how to cause this behavior** Happens with any `Widget`, most probably caused in 2016 with these two commits: 6659c6b4f0290b83d5978e93ed8aff3d4878f649 changed how `FUNCTION_KEYS` are defined (from `const` instances to `bytes`) in `twisted.conch.insults.insults` 5d2ff6938cd1fcfce9e0861ae2c3a562c21b8156 changed how `Widget.functionKeyReceived` handles them in `twisted.conch.insults.window` This is not covered by tests, so it slipped under radar. Looks like I'm first user in years. Even demos included in docs are bit rusty, so here is somewhat stripped gist -> [`window.tac`](https://gist.github.com/Menyadar/09e989c56b23f14386f3c8224b551c3d). Focus "Selection" widgets (there are two of them - columns with numbers, jump to them with `tab` key) and try to change the selection using arrow keys or page up/down. **Describe the correct behavior you'd like to see** Movement should just work **Testing environment** - Operating System and Version; paste the output of these commands: ``` DISTRIB_ID=Ubuntu DISTRIB_RELEASE=22.04 DISTRIB_CODENAME=jammy DISTRIB_DESCRIPTION="Ubuntu 22.04.3 LTS" ``` - Twisted version [e.g. 22.2.0] ``` $ twist --version 23.10.0.post0 ``` **Additional context** Fix is trivial, PR on the way
0.0
63df84e454978bd7a2d57ed292913384ca352e1a
[ "src/twisted/conch/test/test_window.py::SelectionTests::test_selectionDownArrow", "src/twisted/conch/test/test_window.py::SelectionTests::test_selectionPGDN", "src/twisted/conch/test/test_window.py::SelectionTests::test_selectionPGUP", "src/twisted/conch/test/test_window.py::SelectionTests::test_selectionUpArrow", "src/twisted/conch/test/test_window.py::WidgetFunctionKeyTests::test_functionKeyReceivedDispatch" ]
[ "src/twisted/conch/test/test_window.py::TopWindowTests::test_paintScheduling", "src/twisted/conch/test/test_window.py::ScrolledAreaTests::test_parent" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-01 03:46:31+00:00
mit
6,130
twisted__twisted-12069
diff --git a/src/twisted/internet/process.py b/src/twisted/internet/process.py index ef3b88d9f1..ff7684e358 100644 --- a/src/twisted/internet/process.py +++ b/src/twisted/internet/process.py @@ -879,7 +879,7 @@ class Process(_BaseProcess): else: fdState.append((eachFD, isCloseOnExec)) if environment is None: - environment = {} + environment = os.environ setSigDef = [ everySignal diff --git a/src/twisted/newsfragments/12068.bugfix b/src/twisted/newsfragments/12068.bugfix new file mode 100644 index 0000000000..584d3ed944 --- /dev/null +++ b/src/twisted/newsfragments/12068.bugfix @@ -0,0 +1,1 @@ +twisted.internet.process.Process, used by ``reactor.spawnProcess``, now copies the parent environment when the `env=None` argument is passed on Posix systems and ``os.posix_spawnp`` is used internally.
twisted/twisted
a4ab53c33b7069d061f754d6f792b89104b4de94
diff --git a/src/twisted/internet/test/test_process.py b/src/twisted/internet/test/test_process.py index 0b8cdee750..d1d930cca3 100644 --- a/src/twisted/internet/test/test_process.py +++ b/src/twisted/internet/test/test_process.py @@ -29,6 +29,7 @@ from twisted.python.compat import networkString from twisted.python.filepath import FilePath, _asFilesystemBytes from twisted.python.log import err, msg from twisted.python.runtime import platform +from twisted.test.test_process import Accumulator from twisted.trial.unittest import SynchronousTestCase, TestCase # Get the current Python executable as a bytestring. @@ -1001,6 +1002,132 @@ class ProcessTestsBuilder(ProcessTestsBuilderBase): hamcrest.equal_to(["process already removed as desired"]), ) + def checkSpawnProcessEnvironment(self, spawnKwargs, expectedEnv, usePosixSpawnp): + """ + Shared code for testing the environment variables + present in the spawned process. + + The spawned process serializes its environ to stderr or stdout (depending on usePTY) + which is checked against os.environ of the calling process. + """ + p = Accumulator() + d = p.endedDeferred = Deferred() + + reactor = self.buildReactor() + reactor._neverUseSpawn = not usePosixSpawnp + + reactor.callWhenRunning( + reactor.spawnProcess, + p, + pyExe, + [ + pyExe, + b"-c", + networkString( + "import os, sys; " + "env = dict(os.environ); " + # LC_CTYPE is set by python, see https://peps.python.org/pep-0538/ + 'env.pop("LC_CTYPE", None); ' + 'env.pop("__CF_USER_TEXT_ENCODING", None); ' + "sys.stderr.write(str(sorted(env.items())))" + ), + ], + usePTY=self.usePTY, + **spawnKwargs, + ) + + def shutdown(ign): + reactor.stop() + + d.addBoth(shutdown) + + self.runReactor(reactor) + + expectedEnv.pop("LC_CTYPE", None) + expectedEnv.pop("__CF_USER_TEXT_ENCODING", None) + self.assertEqual( + bytes(str(sorted(expectedEnv.items())), "utf-8"), + p.outF.getvalue() if self.usePTY else p.errF.getvalue(), + ) + + def checkSpawnProcessEnvironmentWithPosixSpawnp(self, spawnKwargs, expectedEnv): + return self.checkSpawnProcessEnvironment( + spawnKwargs, expectedEnv, usePosixSpawnp=True + ) + + def checkSpawnProcessEnvironmentWithFork(self, spawnKwargs, expectedEnv): + return self.checkSpawnProcessEnvironment( + spawnKwargs, expectedEnv, usePosixSpawnp=False + ) + + @onlyOnPOSIX + def test_environmentPosixSpawnpEnvNotSet(self): + """ + An empty environment is passed to the spawned process, when the default value of the C{env} + is used. That is, when the C{env} argument is not explicitly set. + + In this case posix_spawnp is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithPosixSpawnp({}, {}) + + @onlyOnPOSIX + def test_environmentForkEnvNotSet(self): + """ + An empty environment is passed to the spawned process, when the default value of the C{env} + is used. That is, when the C{env} argument is not explicitly set. + + In this case fork+execvpe is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithFork({}, {}) + + @onlyOnPOSIX + def test_environmentPosixSpawnpEnvNone(self): + """ + The parent process environment is passed to the spawned process, when C{env} is set to + C{None}. + + In this case posix_spawnp is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithPosixSpawnp( + {"env": None}, os.environ + ) + + @onlyOnPOSIX + def test_environmentForkEnvNone(self): + """ + The parent process environment is passed to the spawned process, when C{env} is set to + C{None}. + + In this case fork+execvpe is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithFork({"env": None}, os.environ) + + @onlyOnPOSIX + def test_environmentPosixSpawnpEnvCustom(self): + """ + The user-specified environment without extra variables from parent process is passed to the + spawned process, when C{env} is set to a dictionary. + + In this case posix_spawnp is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithPosixSpawnp( + {"env": {"MYENV1": "myvalue1"}}, + {"MYENV1": "myvalue1"}, + ) + + @onlyOnPOSIX + def test_environmentForkEnvCustom(self): + """ + The user-specified environment without extra variables from parent process is passed to the + spawned process, when C{env} is set to a dictionary. + + In this case fork+execvpe is used as the backend for spawning processes. + """ + return self.checkSpawnProcessEnvironmentWithFork( + {"env": {"MYENV1": "myvalue1"}}, + {"MYENV1": "myvalue1"}, + ) + globals().update(ProcessTestsBuilder.makeTestCaseClasses())
spawnProcess() passes incorrect environment to subprocess when env=None and posix_spawnp() is used [Documentation on reactor.spawnProcess](https://docs.twisted.org/en/stable/api/twisted.internet.interfaces.IReactorProcess.html) says the following about env parameter: ```env is None: On POSIX: pass os.environ``` However, twisted has [this code](https://github.com/twisted/twisted/blob/68f112f1eecb4613a3b678314a5479464c184ab4/src/twisted/internet/process.py#L881) in the code path leading to a call to posix_spawnp(). ``` if environment is None: environment = {} ``` This leads to a subprocess being initialized with empty environment even though `os.environ` was expected. **Describe how to cause this behavior** There's a PR with automated tests added to Twisted. **Describe the correct behavior you'd like to see** Subprocess having parent process environment when invoked via `reactor.spawnProcess(..., env=None)`. **Testing environment** - Operating System and Version; - Debian 12 - Twisted version: 23.10.0 - Reactor: default on Linux **Additional context** Probably a regression since 23.8.0 when posix_spawnp was enabled.
0.0
a4ab53c33b7069d061f754d6f792b89104b4de94
[ "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentPosixSpawnpEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentPosixSpawnpEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentPosixSpawnpEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentPosixSpawnpEnvNone" ]
[ "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentForkEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentForkEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentForkEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentPosixSpawnpEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_environmentPosixSpawnpEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_SelectReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentForkEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentForkEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentForkEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentPosixSpawnpEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_environmentPosixSpawnpEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentForkEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentForkEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentForkEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentPosixSpawnpEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_environmentPosixSpawnpEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_PollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_childConnectionLost", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentForkEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentForkEnvNone", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentForkEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentPosixSpawnpEnvCustom", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_environmentPosixSpawnpEnvNotSet", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_pauseAndResumeProducing", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processCommandLineArguments", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processEnded", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_process_unregistered_before_protocol_ended_callback", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_shebang", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_write", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::ProcessTestsBuilder_EPollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_SelectReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_AsyncioSelectorReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_PollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_changeGID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_changeUID", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_errorDuringExec", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_openFileDescriptors", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processExitedRaises", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processExitedWithSignal", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_processTransportInterface", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_spawnProcessEarlyIsReaped", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_systemCallUninterruptedByChildExit", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_timelyProcessExited", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_write", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeSequence", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeToChild", "src/twisted/internet/test/test_process.py::PTYProcessTestsBuilder_EPollReactorTests::test_writeToChildBadFileDescriptor", "src/twisted/internet/test/test_process.py::PotentialZombieWarningTests::test_deprecated", "src/twisted/internet/test/test_process.py::ReapingNonePidsLogsProperly::test__BaseProcess_reapProcess", "src/twisted/internet/test/test_process.py::ReapingNonePidsLogsProperly::test_registerReapProcessHandler", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_cloexecStayPut", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_closeNoCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_closeWithCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_inheritableConflict", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_moveNoCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_moveWithCloexec", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_nothing", "src/twisted/internet/test/test_process.py::GetFileActionsTests::test_stayPut" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-12-26 13:17:01+00:00
mit
6,131
twisted__twisted-12096
diff --git a/src/twisted/newsfragments/12096.feature b/src/twisted/newsfragments/12096.feature new file mode 100644 index 0000000000..a07999d034 --- /dev/null +++ b/src/twisted/newsfragments/12096.feature @@ -0,0 +1,1 @@ +twisted.web.wsgi request environment now contains the peer port number as `REMOTE_PORT`. \ No newline at end of file diff --git a/src/twisted/web/wsgi.py b/src/twisted/web/wsgi.py index 43227f40e3..29d1de8f2e 100644 --- a/src/twisted/web/wsgi.py +++ b/src/twisted/web/wsgi.py @@ -287,9 +287,11 @@ class _WSGIResponse: # All keys and values need to be native strings, i.e. of type str in # *both* Python 2 and Python 3, so says PEP-3333. + remotePeer = request.getClientAddress() self.environ = { "REQUEST_METHOD": _wsgiString(request.method), - "REMOTE_ADDR": _wsgiString(request.getClientAddress().host), + "REMOTE_ADDR": _wsgiString(remotePeer.host), + "REMOTE_PORT": _wsgiString(str(remotePeer.port)), "SCRIPT_NAME": _wsgiString(scriptName), "PATH_INFO": _wsgiString(pathInfo), "QUERY_STRING": _wsgiString(queryString), @@ -535,6 +537,9 @@ class WSGIResource: An L{IResource} implementation which delegates responsibility for all resources hierarchically inferior to it to a WSGI application. + The C{environ} argument passed to the application, includes the + C{REMOTE_PORT} key to complement the C{REMOTE_ADDR} key. + @ivar _reactor: An L{IReactorThreads} provider which will be passed on to L{_WSGIResponse} to schedule calls in the I/O thread.
twisted/twisted
50a7feb94995e595dae4c74c49e76d14f6d30140
diff --git a/src/twisted/web/test/test_wsgi.py b/src/twisted/web/test/test_wsgi.py index b6be4f0f4b..ccb736c6bf 100644 --- a/src/twisted/web/test/test_wsgi.py +++ b/src/twisted/web/test/test_wsgi.py @@ -715,7 +715,11 @@ class EnvironTests(WSGITestsMixin, TestCase): The C{'REMOTE_ADDR'} key of the C{environ} C{dict} passed to the application contains the address of the client making the request. """ - d = self.render("GET", "1.1", [], [""]) + + def channelFactory(): + return DummyChannel(peer=IPv4Address("TCP", "192.168.1.1", 12344)) + + d = self.render("GET", "1.1", [], [""], channelFactory=channelFactory) d.addCallback(self.environKeyEqual("REMOTE_ADDR", "192.168.1.1")) return d @@ -735,6 +739,20 @@ class EnvironTests(WSGITestsMixin, TestCase): return d + def test_remotePort(self): + """ + The C{'REMOTE_PORT'} key of the C{environ} C{dict} passed to the + application contains the port of the client making the request. + """ + + def channelFactory(): + return DummyChannel(peer=IPv4Address("TCP", "192.168.1.1", 12344)) + + d = self.render("GET", "1.1", [], [""], channelFactory=channelFactory) + d.addCallback(self.environKeyEqual("REMOTE_PORT", "12344")) + + return d + def test_headers(self): """ HTTP request headers are copied into the C{environ} C{dict} passed to
WSGI applications run inside Twisted Web don’t get access to the client port **Is your feature request related to a problem? Please describe.** The problem we’re trying to solve is that WSGI applications run inside Twisted Web don’t get access to the client port (though the client address is made available through REMOTE_ADDR). We have an application in which the client’s port is necessary. When looking at the [`_WSGIResponse` class](https://github.com/twisted/twisted/blob/11c9f5808da4383678c9ff830d74137efd32d22d/src/twisted/web/wsgi.py#L292), we notice that only `REMOTE_ADDR` is set: ``` # All keys and values need to be native strings, i.e. of type str in # *both* Python 2 and Python 3, so says PEP-3333. self.environ = { "REQUEST_METHOD": _wsgiString(request.method), "REMOTE_ADDR": _wsgiString(request.getClientAddress().host), <------ "SCRIPT_NAME": _wsgiString(scriptName), "PATH_INFO": _wsgiString(pathInfo), "QUERY_STRING": _wsgiString(queryString), "CONTENT_TYPE": _wsgiString(request.getHeader(b"content-type") or ""), "CONTENT_LENGTH": _wsgiString(request.getHeader(b"content-length") or ""), "SERVER_NAME": _wsgiString(request.getRequestHostname()), "SERVER_PORT": _wsgiString(str(request.getHost().port)), "SERVER_PROTOCOL": _wsgiString(request.clientproto), } ``` **Describe the solution you'd like** To provide support for retrieving the remote port as done with the remote IP address. This could be done by updating `environ` to include a new "REMOTE_PORT" attribute as following: ``` self.environ = { "REQUEST_METHOD": _wsgiString(request.method), "REMOTE_ADDR": _wsgiString(request.getClientAddress().host), <------ "REMOTE_PORT": _wsgiString(str(request.getClientAddress().port)), "SCRIPT_NAME": _wsgiString(scriptName), ``` **Describe alternatives you've considered** Besides implementing a monkey patch, another alternative is to try and retrieve the port value from the WSGI context, which might have undesired side affects. **Additional context**
0.0
50a7feb94995e595dae4c74c49e76d14f6d30140
[ "src/twisted/web/test/test_wsgi.py::EnvironTests::test_remotePort" ]
[ "src/twisted/web/test/test_wsgi.py::WSGIResourceTests::test_applicationAndRequestThrow", "src/twisted/web/test/test_wsgi.py::WSGIResourceTests::test_interfaces", "src/twisted/web/test/test_wsgi.py::WSGIResourceTests::test_unsupported", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_contentLength", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_contentLengthIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_contentType", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_contentTypeIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_environIsDict", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_headers", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_pathInfo", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_pathInfoIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_queryString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_queryStringIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_remoteAddr", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_remoteAddrIPv6", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_requestMethod", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_requestMethodIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_scriptName", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_scriptNameIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverName", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverNameIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverPort", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverPortIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverProtocol", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_serverProtocolIsNativeString", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiErrors", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiErrorsAcceptsOnlyNativeStringsInPython3", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiMultiprocess", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiMultithread", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiRunOnce", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiURLScheme", "src/twisted/web/test/test_wsgi.py::EnvironTests::test_wsgiVersion", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_iterable", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_iterableAfterRead", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readAll", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readNegative", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readNone", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readSome", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readTwice", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readline", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlineMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlineNegative", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlineNone", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlineSome", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlineTwice", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlines", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlinesAfterRead", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlinesMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlinesNegative", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlinesNone", "src/twisted/web/test/test_wsgi.py::InputStreamBytesIOTests::test_readlinesSome", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_iterable", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_iterableAfterRead", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readAll", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readNegative", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readNone", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readSome", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readTwice", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readline", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlineMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlineNegative", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlineNone", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlineSome", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlineTwice", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlines", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlinesAfterRead", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlinesMoreThan", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlinesNegative", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlinesNone", "src/twisted/web/test/test_wsgi.py::InputStreamTemporaryFileTests::test_readlinesSome", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_applicationProvidedContentType", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_applicationProvidedServerAndDate", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_content", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_delayedUntilContent", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_delayedUntilReturn", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headerKeyMustBeNativeString", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headerValueMustBeNativeString", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headers", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headersMustBeSequence", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headersMustEachBeSequence", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headersShouldBePlainList", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headersShouldEachBeTuple", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_headersShouldEachHaveKeyAndValue", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_multipleStartResponse", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_startResponseWithException", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_startResponseWithExceptionTooLate", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_status", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_statusMustBeNativeString", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_write", "src/twisted/web/test/test_wsgi.py::StartResponseTests::test_writeAcceptsOnlyByteStrings", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_applicationCalledInThread", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_applicationCloseException", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_applicationExceptionAfterStartResponse", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_applicationExceptionAfterWrite", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_applicationExceptionBeforeStartResponse", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_close", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_connectionClosedDuringIteration", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_iteratedValuesWrittenFromThread", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_statusWrittenFromThread", "src/twisted/web/test/test_wsgi.py::ApplicationTests::test_writeCalledFromThread" ]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2024-01-28 20:30:53+00:00
mit
6,132
twisted__twisted-12117
diff --git a/src/twisted/web/client.py b/src/twisted/web/client.py index e66b0cf317..b06f1bef28 100644 --- a/src/twisted/web/client.py +++ b/src/twisted/web/client.py @@ -1530,7 +1530,7 @@ class ContentDecoderAgent: return response -_canonicalHeaderName = Headers()._canonicalNameCaps +_canonicalHeaderName = Headers()._encodeName _defaultSensitiveHeaders = frozenset( [ b"Authorization", diff --git a/src/twisted/web/http_headers.py b/src/twisted/web/http_headers.py index f810f4bc2c..8b1d41adb6 100644 --- a/src/twisted/web/http_headers.py +++ b/src/twisted/web/http_headers.py @@ -6,9 +6,9 @@ An API for storing HTTP header names and values. """ -from collections.abc import Sequence as _Sequence from typing import ( AnyStr, + ClassVar, Dict, Iterator, List, @@ -26,17 +26,6 @@ from twisted.python.compat import cmp, comparable _T = TypeVar("_T") -def _dashCapitalize(name: bytes) -> bytes: - """ - Return a byte string which is capitalized using '-' as a word separator. - - @param name: The name of the header to capitalize. - - @return: The given header capitalized using '-' as a word separator. - """ - return b"-".join([word.capitalize() for word in name.split(b"-")]) - - def _sanitizeLinearWhitespace(headerComponent: bytes) -> bytes: r""" Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key @@ -65,13 +54,17 @@ class Headers: and values as opaque byte strings. @cvar _caseMappings: A L{dict} that maps lowercase header names - to their canonicalized representation. + to their canonicalized representation, for headers with unconventional + capitalization. + + @cvar _canonicalHeaderCache: A L{dict} that maps header names to their + canonicalized representation. @ivar _rawHeaders: A L{dict} mapping header names as L{bytes} to L{list}s of header values as L{bytes}. """ - _caseMappings = { + _caseMappings: ClassVar[Dict[bytes, bytes]] = { b"content-md5": b"Content-MD5", b"dnt": b"DNT", b"etag": b"ETag", @@ -81,6 +74,12 @@ class Headers: b"x-xss-protection": b"X-XSS-Protection", } + _canonicalHeaderCache: ClassVar[Dict[Union[bytes, str], bytes]] = {} + + _MAX_CACHED_HEADERS: ClassVar[int] = 10_000 + + __slots__ = ["_rawHeaders"] + def __init__( self, rawHeaders: Optional[Mapping[AnyStr, Sequence[AnyStr]]] = None, @@ -112,16 +111,36 @@ class Headers: def _encodeName(self, name: Union[str, bytes]) -> bytes: """ - Encode the name of a header (eg 'Content-Type') to an ISO-8859-1 encoded - bytestring if required. + Encode the name of a header (eg 'Content-Type') to an ISO-8859-1 + encoded bytestring if required. It will be canonicalized and + whitespace-sanitized. @param name: A HTTP header name @return: C{name}, encoded if required, lowercased """ - if isinstance(name, str): - return name.lower().encode("iso-8859-1") - return name.lower() + if canonicalName := self._canonicalHeaderCache.get(name, None): + return canonicalName + + bytes_name = name.encode("iso-8859-1") if isinstance(name, str) else name + + if bytes_name.lower() in self._caseMappings: + # Some headers have special capitalization: + result = self._caseMappings[bytes_name.lower()] + else: + result = _sanitizeLinearWhitespace( + b"-".join([word.capitalize() for word in bytes_name.split(b"-")]) + ) + + # In general, we should only see a very small number of header + # variations in the real world, so caching them is fine. However, an + # attacker could generate infinite header variations to fill up RAM, so + # we cap how many we cache. The performance degradation from lack of + # caching won't be that bad, and legit traffic won't hit it. + if len(self._canonicalHeaderCache) < self._MAX_CACHED_HEADERS: + self._canonicalHeaderCache[name] = result + + return result def copy(self): """ @@ -151,21 +170,9 @@ class Headers: """ self._rawHeaders.pop(self._encodeName(name), None) - @overload - def setRawHeaders(self, name: Union[str, bytes], values: Sequence[bytes]) -> None: - ... - - @overload - def setRawHeaders(self, name: Union[str, bytes], values: Sequence[str]) -> None: - ... - - @overload def setRawHeaders( self, name: Union[str, bytes], values: Sequence[Union[str, bytes]] ) -> None: - ... - - def setRawHeaders(self, name: Union[str, bytes], values: object) -> None: """ Sets the raw representation of the given header. @@ -179,29 +186,7 @@ class Headers: @return: L{None} """ - if not isinstance(values, _Sequence): - raise TypeError( - "Header entry %r should be sequence but found " - "instance of %r instead" % (name, type(values)) - ) - - if not isinstance(name, (bytes, str)): - raise TypeError( - f"Header name is an instance of {type(name)!r}, not bytes or str" - ) - - for count, value in enumerate(values): - if not isinstance(value, (bytes, str)): - raise TypeError( - "Header value at position %s is an instance of %r, not " - "bytes or str" - % ( - count, - type(value), - ) - ) - - _name = _sanitizeLinearWhitespace(self._encodeName(name)) + _name = self._encodeName(name) encodedValues: List[bytes] = [] for v in values: if isinstance(v, str): @@ -220,20 +205,7 @@ class Headers: @param value: The value to set for the named header. """ - if not isinstance(name, (bytes, str)): - raise TypeError( - f"Header name is an instance of {type(name)!r}, not bytes or str" - ) - - if not isinstance(value, (bytes, str)): - raise TypeError( - "Header value is an instance of %r, not " - "bytes or str" % (type(value),) - ) - - self._rawHeaders.setdefault( - _sanitizeLinearWhitespace(self._encodeName(name)), [] - ).append( + self._rawHeaders.setdefault(self._encodeName(name), []).append( _sanitizeLinearWhitespace( value.encode("utf8") if isinstance(value, str) else value ) @@ -277,19 +249,7 @@ class Headers: object, as L{bytes}. The keys are capitalized in canonical capitalization. """ - for k, v in self._rawHeaders.items(): - yield self._canonicalNameCaps(k), v - - def _canonicalNameCaps(self, name: bytes) -> bytes: - """ - Return the canonical name for the given header. - - @param name: The all-lowercase header name to capitalize in its - canonical form. - - @return: The canonical name of the header. - """ - return self._caseMappings.get(name, _dashCapitalize(name)) + return iter(self._rawHeaders.items()) __all__ = ["Headers"] diff --git a/src/twisted/web/newsfragments/12116.feature b/src/twisted/web/newsfragments/12116.feature new file mode 100644 index 0000000000..bd4b3bb23e --- /dev/null +++ b/src/twisted/web/newsfragments/12116.feature @@ -0,0 +1,1 @@ +twisted.web.http_headers now uses less CPU, making a small HTTP client request 10% faster or so. \ No newline at end of file
twisted/twisted
087afb8709b42f4d01bbf51f36657a6f1981c760
diff --git a/src/twisted/web/test/test_http_headers.py b/src/twisted/web/test/test_http_headers.py index 61374336b2..61dfd0bc33 100644 --- a/src/twisted/web/test/test_http_headers.py +++ b/src/twisted/web/test/test_http_headers.py @@ -86,38 +86,6 @@ class BytesHeadersTests(TestCase): self.assertTrue(h.hasHeader(b"Test")) self.assertEqual(h.getRawHeaders(b"test"), rawValue) - def test_rawHeadersTypeCheckingValuesIterable(self) -> None: - """ - L{Headers.setRawHeaders} requires values to be of type list. - """ - h = Headers() - self.assertRaises(TypeError, h.setRawHeaders, b"key", {b"Foo": b"bar"}) - - def test_rawHeadersTypeCheckingName(self) -> None: - """ - L{Headers.setRawHeaders} requires C{name} to be a L{bytes} or - L{str} string. - """ - h = Headers() - e = self.assertRaises(TypeError, h.setRawHeaders, None, [b"foo"]) - self.assertEqual( - e.args[0], - "Header name is an instance of <class 'NoneType'>, " "not bytes or str", - ) - - def test_rawHeadersTypeCheckingValuesAreString(self) -> None: - """ - L{Headers.setRawHeaders} requires values to a L{list} of L{bytes} or - L{str} strings. - """ - h = Headers() - e = self.assertRaises(TypeError, h.setRawHeaders, b"key", [b"bar", None]) - self.assertEqual( - e.args[0], - "Header value at position 1 is an instance of <class 'NoneType'>, " - "not bytes or str", - ) - def test_addRawHeader(self) -> None: """ L{Headers.addRawHeader} adds a new value for a given header. @@ -128,30 +96,6 @@ class BytesHeadersTests(TestCase): h.addRawHeader(b"test", b"panda") self.assertEqual(h.getRawHeaders(b"test"), [b"lemur", b"panda"]) - def test_addRawHeaderTypeCheckName(self) -> None: - """ - L{Headers.addRawHeader} requires C{name} to be a L{bytes} or L{str} - string. - """ - h = Headers() - e = self.assertRaises(TypeError, h.addRawHeader, None, b"foo") - self.assertEqual( - e.args[0], - "Header name is an instance of <class 'NoneType'>, " "not bytes or str", - ) - - def test_addRawHeaderTypeCheckValue(self) -> None: - """ - L{Headers.addRawHeader} requires value to be a L{bytes} or L{str} - string. - """ - h = Headers() - e = self.assertRaises(TypeError, h.addRawHeader, b"key", None) - self.assertEqual( - e.args[0], - "Header value is an instance of <class 'NoneType'>, " "not bytes or str", - ) - def test_getRawHeadersNoDefault(self) -> None: """ L{Headers.getRawHeaders} returns L{None} if the header is not found and @@ -232,21 +176,23 @@ class BytesHeadersTests(TestCase): h.removeHeader(b"test") self.assertEqual(list(h.getAllRawHeaders()), []) - def test_canonicalNameCaps(self) -> None: + def test_encodeName(self) -> None: """ - L{Headers._canonicalNameCaps} returns the canonical capitalization for + L{Headers._encodeName} returns the canonical capitalization for the given header. """ h = Headers() - self.assertEqual(h._canonicalNameCaps(b"test"), b"Test") - self.assertEqual(h._canonicalNameCaps(b"test-stuff"), b"Test-Stuff") - self.assertEqual(h._canonicalNameCaps(b"content-md5"), b"Content-MD5") - self.assertEqual(h._canonicalNameCaps(b"dnt"), b"DNT") - self.assertEqual(h._canonicalNameCaps(b"etag"), b"ETag") - self.assertEqual(h._canonicalNameCaps(b"p3p"), b"P3P") - self.assertEqual(h._canonicalNameCaps(b"te"), b"TE") - self.assertEqual(h._canonicalNameCaps(b"www-authenticate"), b"WWW-Authenticate") - self.assertEqual(h._canonicalNameCaps(b"x-xss-protection"), b"X-XSS-Protection") + self.assertEqual(h._encodeName(b"test"), b"Test") + self.assertEqual(h._encodeName(b"test-stuff"), b"Test-Stuff") + self.assertEqual(h._encodeName(b"content-md5"), b"Content-MD5") + self.assertEqual(h._encodeName(b"dnt"), b"DNT") + self.assertEqual(h._encodeName(b"etag"), b"ETag") + self.assertEqual(h._encodeName(b"p3p"), b"P3P") + self.assertEqual(h._encodeName(b"te"), b"TE") + self.assertEqual(h._encodeName(b"www-authenticate"), b"WWW-Authenticate") + self.assertEqual(h._encodeName(b"WWW-authenticate"), b"WWW-Authenticate") + self.assertEqual(h._encodeName(b"Www-Authenticate"), b"WWW-Authenticate") + self.assertEqual(h._encodeName(b"x-xss-protection"), b"X-XSS-Protection") def test_getAllRawHeaders(self) -> None: """ @@ -300,7 +246,7 @@ class BytesHeadersTests(TestCase): baz = b"baz" self.assertEqual( repr(Headers({foo: [bar, baz]})), - f"Headers({{{foo!r}: [{bar!r}, {baz!r}]}})", + f"Headers({{{foo.capitalize()!r}: [{bar!r}, {baz!r}]}})", ) def test_reprWithRawBytes(self) -> None: @@ -317,7 +263,7 @@ class BytesHeadersTests(TestCase): baz = b"baz\xe1" self.assertEqual( repr(Headers({foo: [bar, baz]})), - f"Headers({{{foo!r}: [{bar!r}, {baz!r}]}})", + f"Headers({{{foo.capitalize()!r}: [{bar!r}, {baz!r}]}})", ) def test_subclassRepr(self) -> None: @@ -334,7 +280,7 @@ class BytesHeadersTests(TestCase): self.assertEqual( repr(FunnyHeaders({foo: [bar, baz]})), - f"FunnyHeaders({{{foo!r}: [{bar!r}, {baz!r}]}})", + f"FunnyHeaders({{{foo.capitalize()!r}: [{bar!r}, {baz!r}]}})", ) def test_copy(self) -> None: @@ -352,6 +298,17 @@ class BytesHeadersTests(TestCase): i.addRawHeader(b"test", b"baz") self.assertEqual(h.getRawHeaders(b"test"), [b"foo", b"bar"]) + def test_max_cached_headers(self) -> None: + """ + Only a limited number of HTTP header names get cached. + """ + headers = Headers() + for i in range(Headers._MAX_CACHED_HEADERS + 200): + headers.addRawHeader(f"hello-{i}", "value") + self.assertEqual( + len(Headers._canonicalHeaderCache), Headers._MAX_CACHED_HEADERS + ) + class UnicodeHeadersTests(TestCase): """ @@ -435,13 +392,6 @@ class UnicodeHeadersTests(TestCase): self.assertTrue(h.hasHeader(b"\xe1")) self.assertEqual(h.getRawHeaders(b"\xe1"), [b"\xe2\x98\x83", b"foo"]) - def test_rawHeadersTypeChecking(self) -> None: - """ - L{Headers.setRawHeaders} requires values to be of type sequence - """ - h = Headers() - self.assertRaises(TypeError, h.setRawHeaders, "key", {"Foo": "bar"}) - def test_addRawHeader(self) -> None: """ L{Headers.addRawHeader} adds a new value for a given header. @@ -614,7 +564,7 @@ class UnicodeHeadersTests(TestCase): foo = "foo\u00E1" bar = "bar\u2603" baz = "baz" - fooEncoded = "'foo\\xe1'" + fooEncoded = "'Foo\\xe1'" barEncoded = "'bar\\xe2\\x98\\x83'" fooEncoded = "b" + fooEncoded barEncoded = "b" + barEncoded @@ -633,7 +583,7 @@ class UnicodeHeadersTests(TestCase): foo = "foo\u00E1" bar = "bar\u2603" baz = "baz" - fooEncoded = "b'foo\\xe1'" + fooEncoded = "b'Foo\\xe1'" barEncoded = "b'bar\\xe2\\x98\\x83'" class FunnyHeaders(Headers):
Speed up http_headers operations Handling HTTP headers is a significant percentage of time spent in the HTTP client (and probably the HTTP server as well). In particular, all the normalization (which happens both incoming and outgoing!) adds up.
0.0
087afb8709b42f4d01bbf51f36657a6f1981c760
[ "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_encodeName", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_max_cached_headers", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_repr", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_reprWithRawBytes", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_subclassRepr", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_repr", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_subclassRepr" ]
[ "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_addRawHeader", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_copy", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_getAllRawHeaders", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_getRawHeaders", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_getRawHeadersDefaultValue", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_getRawHeadersNoDefault", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_getRawHeadersWithDefaultMatchingValue", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_hasHeaderFalse", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_hasHeaderTrue", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_headersComparison", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_initializer", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_otherComparison", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_removeHeader", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_removeHeaderDoesntExist", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_sanitizeLinearWhitespace", "src/twisted/web/test/test_http_headers.py::BytesHeadersTests::test_setRawHeaders", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_addRawHeader", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_copy", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_getAllRawHeaders", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_getRawHeaders", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_getRawHeadersDefaultValue", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_getRawHeadersNoDefault", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_getRawHeadersWithDefaultMatchingValue", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_hasHeaderFalse", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_hasHeaderTrue", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_headersComparison", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_initializer", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_nameEncoding", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_nameNotEncodable", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_otherComparison", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_rawHeadersValueEncoding", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_removeHeader", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_removeHeaderDoesntExist", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_sanitizeLinearWhitespace", "src/twisted/web/test/test_http_headers.py::UnicodeHeadersTests::test_setRawHeaders", "src/twisted/web/test/test_http_headers.py::MixedHeadersTests::test_addRawHeader", "src/twisted/web/test/test_http_headers.py::MixedHeadersTests::test_setRawHeaders" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2024-03-15 18:30:20+00:00
mit
6,133
twosigma__marbles-112
diff --git a/marbles/core/marbles/core/marbles.py b/marbles/core/marbles/core/marbles.py index 750dca9..7d1ae37 100644 --- a/marbles/core/marbles/core/marbles.py +++ b/marbles/core/marbles/core/marbles.py @@ -245,7 +245,8 @@ Source ({filename}): if self._note is None: return None else: - formatted_note = self._note.format(**self.locals) + dedented_note = textwrap.dedent(self._note) + formatted_note = dedented_note.format(**self.locals) wrapper = _NoteWrapper(width=72, break_long_words=False, initial_indent='\t',
twosigma/marbles
f0c668be8344c70d4d63bc57e82c6f2da43c6925
diff --git a/marbles/core/tests/test_marbles.py b/marbles/core/tests/test_marbles.py index e6941f7..a69909b 100644 --- a/marbles/core/tests/test_marbles.py +++ b/marbles/core/tests/test_marbles.py @@ -102,91 +102,91 @@ class ExampleTestCaseMixin( def test_long_note(self): note = ''' -Onionskins - Although this cane-cut swirl usually has at its center a -clear glass core, it appears solidly colored because the clear core is -covered by a thin layer of opaque color and then covered again by a -thin layer of clear glass. Extremely popular and highly prized, -onionskins take their name from the layering of glass, like layers of -an onion. In contrast to end of day marbles, onion skins have two -pontils. The base color, usually white or yellow, was applied by -rolling clear glass marble in powdered glass. Accent colors were added -by rolling the heated piece over fragments of crashed glass, creating -the speckled effect. There are various types of onionskins: single -color, speckled, and segmented. Sometimes mica was added to the glass, -thus increasing its value. Onionskins were known to exist from the -beginning of the cane-cut marble industry. An early example, dated -between 1850 and 1860 was unearthed in the excavation of an old privy -in New Orleans.''' + Onionskins - Although this cane-cut swirl usually has at its center a + clear glass core, it appears solidly colored because the clear core is + covered by a thin layer of opaque color and then covered again by a + thin layer of clear glass. Extremely popular and highly prized, + onionskins take their name from the layering of glass, like layers of + an onion. In contrast to end of day marbles, onion skins have two + pontils. The base color, usually white or yellow, was applied by + rolling clear glass marble in powdered glass. Accent colors were added + by rolling the heated piece over fragments of crashed glass, creating + the speckled effect. There are various types of onionskins: single + color, speckled, and segmented. Sometimes mica was added to the glass, + thus increasing its value. Onionskins were known to exist from the + beginning of the cane-cut marble industry. An early example, dated + between 1850 and 1860 was unearthed in the excavation of an old privy + in New Orleans.''' self.assertTrue(False, note=note) def test_long_line_in_note(self): note = ''' -OnionskinsAlthoughthiscanecutswirlusuallyhasatitscenteraclearglasscoreitappears -solidly colored because the clear core is covered by a thin layer of -opaque color and then covered again by a thin layer of clear -glass. Extremely popular and highly prized, onionskins take their name -from the layering of glass, like layers of an onion. In contrast to -end of day marbles, onion skins have two pontils. The base color, -usually white or yellow, was applied by rolling clear glass marble in -powdered glass. Accent colors were added by rolling the heated piece -over fragments of crashed glass, creating the speckled effect. There -are various types of onionskins: single color, speckled, and -segmented. Sometimes mica was added to the glass, thus increasing its -value. Onionskins were known to exist from the beginning of the -cane-cut marble industry. An early example, dated between 1850 and -1860 was unearthed in the excavation of an old privy in New -Orleans.''' + OnionskinsAlthoughthiscanecutswirlusuallyhasatitscenteraclearglasscoreitappears + solidly colored because the clear core is covered by a thin layer of + opaque color and then covered again by a thin layer of clear + glass. Extremely popular and highly prized, onionskins take their name + from the layering of glass, like layers of an onion. In contrast to + end of day marbles, onion skins have two pontils. The base color, + usually white or yellow, was applied by rolling clear glass marble in + powdered glass. Accent colors were added by rolling the heated piece + over fragments of crashed glass, creating the speckled effect. There + are various types of onionskins: single color, speckled, and + segmented. Sometimes mica was added to the glass, thus increasing its + value. Onionskins were known to exist from the beginning of the + cane-cut marble industry. An early example, dated between 1850 and + 1860 was unearthed in the excavation of an old privy in New + Orleans.''' self.assertTrue(False, note=note) def test_multi_paragraphs_in_note(self): note = ''' -Onionskins - Although this cane-cut swirl usually has at its center a -clear glass core, it appears solidly colored because the clear core is -covered by a thin layer of opaque color and then covered again by a -thin layer of clear glass. Extremely popular and highly prized, -onionskins take their name from the layering of glass, like layers of -an onion. - -In contrast to end of day marbles, onion skins have two pontils. The -base color, usually white or yellow, was applied by rolling clear glass -marble in powdered glass. Accent colors were added by rolling the -heated piece over fragments of crashed glass, creating the speckled -effect. - -There are various types of onionskins: single color, speckled, and -segmented. Sometimes mica was added to the glass, thus increasing its -value. Onionskins were known to exist from the beginning of the -cane-cut marble industry. An early example, dated between 1850 and 1860 -was unearthed in the excavation of an old privy in New Orleans.''' + Onionskins - Although this cane-cut swirl usually has at its center a + clear glass core, it appears solidly colored because the clear core is + covered by a thin layer of opaque color and then covered again by a + thin layer of clear glass. Extremely popular and highly prized, + onionskins take their name from the layering of glass, like layers of + an onion. + + In contrast to end of day marbles, onion skins have two pontils. The + base color, usually white or yellow, was applied by rolling clear glass + marble in powdered glass. Accent colors were added by rolling the + heated piece over fragments of crashed glass, creating the speckled + effect. + + There are various types of onionskins: single color, speckled, and + segmented. Sometimes mica was added to the glass, thus increasing its + value. Onionskins were known to exist from the beginning of the + cane-cut marble industry. An early example, dated between 1850 and 1860 + was unearthed in the excavation of an old privy in New Orleans.''' self.assertTrue(False, note=note) def test_list_in_note(self): note = ''' -There are various types of onionskins: + There are various types of onionskins: - 1. single color, + 1. single color, - 2. speckled, + 2. speckled, - 3. and segmented. + 3. and segmented. - 42. Sometimes mica was added to the glass, thus increasing its -value. Onionskins were known to exist from the beginning of the cane- -cut marble industry. An early example, dated between 1850 and 1860 was -unearthed in the excavation of an old privy in New Orleans. + 42. Sometimes mica was added to the glass, thus increasing its + value. Onionskins were known to exist from the beginning of the cane- + cut marble industry. An early example, dated between 1850 and 1860 was + unearthed in the excavation of an old privy in New Orleans. -There are various types of onionskins: + There are various types of onionskins: - a) single color, + a) single color, - b) speckled, + b) speckled, - c) and segmented. + c) and segmented. - d) Sometimes mica was added to the glass, thus increasing its -value. Onionskins were known to exist from the beginning of the cane- -cut marble industry. An early example, dated between 1850 and 1860 was -unearthed in the excavation of an old privy in New Orleans.''' + d) Sometimes mica was added to the glass, thus increasing its + value. Onionskins were known to exist from the beginning of the cane- + cut marble industry. An early example, dated between 1850 and 1860 was + unearthed in the excavation of an old privy in New Orleans.''' self.assertTrue(False, note=note) def test_assert_raises_success(self):
Dedent note before reformatting We want to allow users to write notes as triple-quoted multiline strings that are: 1. indented in the source ```python class MyTestCase(marbles.core.TestCase): def test_bar(self): note = '''Welcome to your new marbles test suite! We're so glad you're here. Here are some things you can do: 1. foo 2. bar ''' self.assertTrue(False, note=note) ``` 2. lined up all the way to the left of the test output ```bash marbles.marbles.AnnotatedAssertionError: False is not true Source: 38 > 39 self.assertTrue(False, note=note) 40 Locals: Note: Welcome to your new marbles test suite! We're so glad you're here. Here are some things you can do: 1. foo 2. bar ---------------------------------------------------------------------- Ran 1 tests in 0.002s FAILED (failures=1) ``` Currently, in order to achieve 2, users have to align their multiline strings all the way to the left in the source, or they have to do their own dedenting before passing the note to an assertion. We can do this dedenting for users by calling [`textwrap.dedent`](https://docs.python.org/3.7/library/textwrap.html#textwrap.dedent) on the note before we do the remaining reformatting.
0.0
f0c668be8344c70d4d63bc57e82c6f2da43c6925
[ "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_note_wrapping" ]
[ "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_annotated_assertion_error_not_raised", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_annotated_assertion_error_raised", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_assert_raises_failure", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_assert_raises_missing_note", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_assert_raises_success", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_fail_handles_note_properly", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_fail_rejects_extra_args", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_fail_works_when_invoked_by_builtin_assertions", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_missing_annotation", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_missing_msg_ok", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_missing_note_dict", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_odd_argument_order_ok", "marbles/core/tests/test_marbles.py::InterfaceTestCase::test_string_equality", "marbles/core/tests/test_marbles.py::TestAssertionLoggingFailure::test_success", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_assert_raises_kwargs_msg", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_assert_raises_without_msg", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_assert_stmt_indicates_line", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_assert_stmt_surrounding_lines", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_custom_assertions", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_custom_assertions_kwargs", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_exclude_ignored_locals", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_exclude_internal_mangled_locals", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_get_stack", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_kwargs_stick_together", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_locals_hidden_when_all_private", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_locals_hidden_when_missing", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_locals_shown_when_present", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_missing_msg_dict", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_missing_msg_kwargs_note", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_multiline_locals_indentation", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_named_assert_args", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_note_rich_format_strings", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_odd_argument_order", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_positional_assert_args", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_positional_msg_kwargs_note", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_use_kwargs_form", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_verify_annotation_dict_missing_keys", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_verify_annotation_locals", "marbles/core/tests/test_marbles.py::TestContextualAssertionError::test_verify_annotation_none" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-11-08 02:38:09+00:00
mit
6,134