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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spdx__tools-python-588
|
diff --git a/src/spdx/clitools/pyspdxtools.py b/src/spdx/clitools/pyspdxtools.py
index e246176..f2d480e 100644
--- a/src/spdx/clitools/pyspdxtools.py
+++ b/src/spdx/clitools/pyspdxtools.py
@@ -29,7 +29,7 @@ from spdx.writer.write_anything import write_file
@click.command()
[email protected]("--infile", "-i", help="The file containing the document to be validated or converted.")
[email protected]("--infile", "-i", required=True, help="The file containing the document to be validated or converted.")
@click.option(
"--outfile",
"-o",
|
spdx/tools-python
|
95d6ce143dac35825d8184edffabb48d4a71f12a
|
diff --git a/tests/spdx/test_cli.py b/tests/spdx/test_cli.py
new file mode 100644
index 0000000..3966039
--- /dev/null
+++ b/tests/spdx/test_cli.py
@@ -0,0 +1,45 @@
+import os
+
+import pytest
+from click.testing import CliRunner
+
+from spdx.clitools.pyspdxtools import main
+
+
[email protected](
+ "options",
+ [
+ ("--infile", os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json")),
+ ("-i", os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json"), "--novalidation"),
+ (
+ "-i",
+ os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json"),
+ "--novalidation",
+ "--version",
+ "SPDX-2.3",
+ ),
+ ("-i", os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json"), "-o", "-"),
+ ],
+)
+def test_cli_with_system_exit_code_0(options):
+ runner = CliRunner()
+
+ result = runner.invoke(main, options)
+
+ assert result.exit_code == 0
+
+
[email protected](
+ "options",
+ [
+ (),
+ ("-i", os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json"), "--version"),
+ ("-i", os.path.join(os.path.dirname(__file__), "data/SPDXJSONExample-v2.3.spdx.json"), "-o"),
+ ],
+)
+def test_cli_with_system_exit_code_2(options):
+ runner = CliRunner()
+
+ result = runner.invoke(main, options)
+
+ assert result.exit_code == 2
|
CLI raises error if no arguments provided
If we only call `pyspdxtools` without any argument an `AttributeError` is raised. We should instead give a hint on how to correctly use the CLI and which arguments are possible.
|
0.0
|
95d6ce143dac35825d8184edffabb48d4a71f12a
|
[
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_2[options0]"
] |
[
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_0[options0]",
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_0[options1]",
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_0[options2]",
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_0[options3]",
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_2[options1]",
"tests/spdx/test_cli.py::test_cli_with_system_exit_code_2[options2]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-17 12:04:57+00:00
|
apache-2.0
| 5,635 |
|
spdx__tools-python-590
|
diff --git a/src/spdx/parser/jsonlikedict/file_parser.py b/src/spdx/parser/jsonlikedict/file_parser.py
index eb59fcc..3f4b565 100644
--- a/src/spdx/parser/jsonlikedict/file_parser.py
+++ b/src/spdx/parser/jsonlikedict/file_parser.py
@@ -10,7 +10,10 @@ from spdx.model.file import File, FileType
from spdx.model.spdx_no_assertion import SpdxNoAssertion
from spdx.model.spdx_none import SpdxNone
from spdx.parser.jsonlikedict.checksum_parser import ChecksumParser
-from spdx.parser.jsonlikedict.dict_parsing_functions import parse_field_or_log_error
+from spdx.parser.jsonlikedict.dict_parsing_functions import (
+ parse_field_or_log_error,
+ parse_field_or_no_assertion_or_none,
+)
from spdx.parser.jsonlikedict.license_expression_parser import LicenseExpressionParser
from spdx.parser.logger import Logger
from spdx.parser.parsing_functions import construct_or_raise_parsing_error, raise_parsing_error_if_logger_has_messages
@@ -37,7 +40,9 @@ class FileParser:
attribution_texts: List[str] = file_dict.get("attributionTexts", [])
comment: Optional[str] = file_dict.get("comment")
- copyright_text: Optional[str] = file_dict.get("copyrightText")
+ copyright_text: Optional[Union[str, SpdxNoAssertion, SpdxNone]] = parse_field_or_no_assertion_or_none(
+ file_dict.get("copyrightText")
+ )
file_contributors: List[str] = file_dict.get("fileContributors", [])
file_types: List[FileType] = parse_field_or_log_error(
logger, file_dict.get("fileTypes"), self.parse_file_types
diff --git a/src/spdx/parser/jsonlikedict/package_parser.py b/src/spdx/parser/jsonlikedict/package_parser.py
index c79fd11..090a7ad 100644
--- a/src/spdx/parser/jsonlikedict/package_parser.py
+++ b/src/spdx/parser/jsonlikedict/package_parser.py
@@ -58,7 +58,9 @@ class PackageParser:
logger, package_dict.get("checksums"), self.checksum_parser.parse_checksum, field_is_list=True
)
comment: Optional[str] = package_dict.get("comment")
- copyright_text: Optional[str] = package_dict.get("copyrightText")
+ copyright_text: Optional[Union[str, SpdxNoAssertion, SpdxNone]] = parse_field_or_no_assertion_or_none(
+ package_dict.get("copyrightText")
+ )
description: Optional[str] = package_dict.get("description")
download_location: Optional[Union[str, SpdxNoAssertion, SpdxNone]] = parse_field_or_no_assertion_or_none(
package_dict.get("downloadLocation")
@@ -78,7 +80,9 @@ class PackageParser:
elif files_analyzed.lower() == "false":
files_analyzed = False
- homepage: Optional[str] = package_dict.get("homepage")
+ homepage: Optional[Union[str, SpdxNoAssertion, SpdxNone]] = parse_field_or_no_assertion_or_none(
+ package_dict.get("homepage")
+ )
license_comments: Optional[str] = package_dict.get("licenseComments")
license_concluded = parse_field_or_log_error(
logger, package_dict.get("licenseConcluded"), self.license_expression_parser.parse_license_expression
diff --git a/src/spdx/parser/jsonlikedict/snippet_parser.py b/src/spdx/parser/jsonlikedict/snippet_parser.py
index 52d2194..c4f5250 100644
--- a/src/spdx/parser/jsonlikedict/snippet_parser.py
+++ b/src/spdx/parser/jsonlikedict/snippet_parser.py
@@ -10,7 +10,10 @@ from spdx.model.snippet import Snippet
from spdx.model.spdx_no_assertion import SpdxNoAssertion
from spdx.model.spdx_none import SpdxNone
from spdx.parser.error import SPDXParsingError
-from spdx.parser.jsonlikedict.dict_parsing_functions import parse_field_or_log_error
+from spdx.parser.jsonlikedict.dict_parsing_functions import (
+ parse_field_or_log_error,
+ parse_field_or_no_assertion_or_none,
+)
from spdx.parser.jsonlikedict.license_expression_parser import LicenseExpressionParser
from spdx.parser.logger import Logger
from spdx.parser.parsing_functions import construct_or_raise_parsing_error
@@ -43,7 +46,9 @@ class SnippetParser:
attribution_texts: List[str] = snippet_dict.get("attributionTexts", [])
comment: Optional[str] = snippet_dict.get("comment")
- copyright_text: Optional[str] = snippet_dict.get("copyrightText")
+ copyright_text: Optional[Union[str, SpdxNoAssertion, SpdxNone]] = parse_field_or_no_assertion_or_none(
+ snippet_dict.get("copyrightText")
+ )
license_comment: Optional[str] = snippet_dict.get("licenseComments")
license_concluded: Optional[Union[LicenseExpression, SpdxNoAssertion, SpdxNone]] = parse_field_or_log_error(
logger, snippet_dict.get("licenseConcluded"), self.license_expression_parser.parse_license_expression
|
spdx/tools-python
|
3204bda8bb4cb99de97bd08d13cd31cbcb8e8344
|
diff --git a/tests/spdx/parser/jsonlikedict/test_file_parser.py b/tests/spdx/parser/jsonlikedict/test_file_parser.py
index e99c039..6aacf44 100644
--- a/tests/spdx/parser/jsonlikedict/test_file_parser.py
+++ b/tests/spdx/parser/jsonlikedict/test_file_parser.py
@@ -9,12 +9,21 @@ from license_expression import Licensing
from spdx.model.checksum import Checksum, ChecksumAlgorithm
from spdx.model.file import FileType
from spdx.model.spdx_no_assertion import SpdxNoAssertion
+from spdx.model.spdx_none import SpdxNone
from spdx.parser.error import SPDXParsingError
from spdx.parser.jsonlikedict.dict_parsing_functions import parse_list_of_elements
from spdx.parser.jsonlikedict.file_parser import FileParser
-def test_parse_file():
[email protected](
+ "copyright_text, expected_copyright_text",
+ [
+ ("Copyright 2008-2010 John Smith", "Copyright 2008-2010 John Smith"),
+ ("NOASSERTION", SpdxNoAssertion()),
+ ("NONE", SpdxNone()),
+ ],
+)
+def test_parse_file(copyright_text, expected_copyright_text):
file_parser = FileParser()
file_dict = {
"SPDXID": "SPDXRef-File",
@@ -25,7 +34,7 @@ def test_parse_file():
],
"comment": "The concluded license was taken from the package level that the file was included in.\nThis "
"information was found in the COPYING.txt file in the xyz directory.",
- "copyrightText": "Copyright 2008-2010 John Smith",
+ "copyrightText": copyright_text,
"fileContributors": [
"The Regents of the University of California",
"Modified by Paul Mundt [email protected]",
@@ -66,7 +75,7 @@ def test_parse_file():
== "The concluded license was taken from the package level that the file was included in.\nThis information "
"was found in the COPYING.txt file in the xyz directory."
)
- assert file.copyright_text == "Copyright 2008-2010 John Smith"
+ assert file.copyright_text == expected_copyright_text
assert file.file_types == [FileType.SOURCE]
TestCase().assertCountEqual(
file.contributors,
diff --git a/tests/spdx/parser/jsonlikedict/test_package_parser.py b/tests/spdx/parser/jsonlikedict/test_package_parser.py
index 00cecbd..bb0fea4 100644
--- a/tests/spdx/parser/jsonlikedict/test_package_parser.py
+++ b/tests/spdx/parser/jsonlikedict/test_package_parser.py
@@ -11,12 +11,66 @@ from spdx.model.actor import Actor, ActorType
from spdx.model.checksum import Checksum, ChecksumAlgorithm
from spdx.model.package import ExternalPackageRef, ExternalPackageRefCategory, PackagePurpose, PackageVerificationCode
from spdx.model.spdx_no_assertion import SpdxNoAssertion
+from spdx.model.spdx_none import SpdxNone
from spdx.parser.error import SPDXParsingError
from spdx.parser.jsonlikedict.dict_parsing_functions import parse_list_of_elements
from spdx.parser.jsonlikedict.package_parser import PackageParser
-def test_parse_package():
[email protected](
+ "homepage, expected_homepage, download_location, expected_download_location, "
+ "copyright_text, expected_copyright_text, originator, expected_originator, supplier, expected_supplier",
+ [
+ (
+ "http://ftp.gnu.org/gnu/glibc",
+ "http://ftp.gnu.org/gnu/glibc",
+ "NOASSERTION",
+ SpdxNoAssertion(),
+ "NONE",
+ SpdxNone(),
+ "Organization: ExampleCodeInspect ([email protected])",
+ Actor(ActorType.ORGANIZATION, "ExampleCodeInspect", "[email protected]"),
+ "NOASSERTION",
+ SpdxNoAssertion(),
+ ),
+ (
+ "NOASSERTION",
+ SpdxNoAssertion(),
+ "NONE",
+ SpdxNone(),
+ "Copyright 2008-2010 John Smith",
+ "Copyright 2008-2010 John Smith",
+ None,
+ None,
+ None,
+ None,
+ ),
+ (
+ "NONE",
+ SpdxNone(),
+ "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz",
+ "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz",
+ "NOASSERTION",
+ SpdxNoAssertion(),
+ "NOASSERTION",
+ SpdxNoAssertion(),
+ "Person: Jane Doe ([email protected])",
+ Actor(ActorType.PERSON, "Jane Doe", "[email protected]"),
+ ),
+ ],
+)
+def test_parse_package(
+ homepage,
+ expected_homepage,
+ download_location,
+ expected_download_location,
+ copyright_text,
+ expected_copyright_text,
+ originator,
+ expected_originator,
+ supplier,
+ expected_supplier,
+):
package_parser = PackageParser()
package_dict = {
@@ -42,11 +96,11 @@ def test_parse_package():
},
],
"comment": "This is a comment.",
- "copyrightText": "Copyright 2008-2010 John Smith",
+ "copyrightText": copyright_text,
"description": "The GNU C Library defines functions that are specified by the ISO C standard, as well as "
"additional features specific to POSIX and other derivatives of the Unix operating system, and "
"extensions specific to GNU systems.",
- "downloadLocation": "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz",
+ "downloadLocation": download_location,
"externalRefs": [
{
"referenceCategory": "SECURITY",
@@ -62,14 +116,14 @@ def test_parse_package():
},
],
"filesAnalyzed": True,
- "homepage": "http://ftp.gnu.org/gnu/glibc",
+ "homepage": homepage,
"licenseComments": "The license for this project changed with the release of version x.y. The version of the "
"project included here post-dates the license change.",
"licenseConcluded": "(LGPL-2.0-only OR LicenseRef-3)",
"licenseDeclared": "(LGPL-2.0-only AND LicenseRef-3)",
"licenseInfoFromFiles": ["GPL-2.0-only", "LicenseRef-2", "LicenseRef-1", "NOASSERTION"],
"name": "glibc",
- "originator": "Organization: ExampleCodeInspect ([email protected])",
+ "originator": originator,
"packageFileName": "glibc-2.11.1.tar.gz",
"packageVerificationCode": {
"packageVerificationCodeExcludedFiles": ["./package.spdx"],
@@ -79,7 +133,7 @@ def test_parse_package():
"releaseDate": "2012-01-29T18:30:22Z",
"sourceInfo": "uses glibc-2_11-branch from git://sourceware.org/git/glibc.git.",
"summary": "GNU C library.",
- "supplier": "Person: Jane Doe ([email protected])",
+ "supplier": supplier,
"validUntilDate": "2014-01-29T18:30:22Z",
"versionInfo": "2.11.1",
}
@@ -88,11 +142,11 @@ def test_parse_package():
assert package.spdx_id == "SPDXRef-Package"
assert package.name == "glibc"
- assert package.download_location == "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz"
+ assert package.download_location == expected_download_location
assert package.version == "2.11.1"
assert package.file_name == "glibc-2.11.1.tar.gz"
- assert package.supplier == Actor(ActorType.PERSON, "Jane Doe", "[email protected]")
- assert package.originator == Actor(ActorType.ORGANIZATION, "ExampleCodeInspect", "[email protected]")
+ assert package.supplier == expected_supplier
+ assert package.originator == expected_originator
assert package.files_analyzed is True
assert package.verification_code == PackageVerificationCode(
value="d6a770ba38583ed4bb4525bd96e50461655d2758", excluded_files=["./package.spdx"]
@@ -110,7 +164,7 @@ def test_parse_package():
),
],
)
- assert package.homepage == "http://ftp.gnu.org/gnu/glibc"
+ assert package.homepage == expected_homepage
assert package.source_info == "uses glibc-2_11-branch from git://sourceware.org/git/glibc.git."
assert package.license_concluded == Licensing().parse("(LGPL-2.0-only OR LicenseRef-3)")
TestCase().assertCountEqual(
@@ -128,7 +182,7 @@ def test_parse_package():
== "The license for this project changed with the release of version x.y. The version of the project included"
" here post-dates the license change."
)
- assert package.copyright_text == "Copyright 2008-2010 John Smith"
+ assert package.copyright_text == expected_copyright_text
assert package.summary == "GNU C library."
assert (
package.description
diff --git a/tests/spdx/parser/jsonlikedict/test_snippet_parser.py b/tests/spdx/parser/jsonlikedict/test_snippet_parser.py
index 10b0fb2..1cbceb9 100644
--- a/tests/spdx/parser/jsonlikedict/test_snippet_parser.py
+++ b/tests/spdx/parser/jsonlikedict/test_snippet_parser.py
@@ -7,11 +7,20 @@ import pytest
from license_expression import Licensing
from spdx.model.spdx_no_assertion import SpdxNoAssertion
+from spdx.model.spdx_none import SpdxNone
from spdx.parser.error import SPDXParsingError
from spdx.parser.jsonlikedict.snippet_parser import SnippetParser
-def test_parse_snippet():
[email protected](
+ "copyright_text, expected_copyright_text",
+ [
+ ("Copyright 2008-2010 John Smith", "Copyright 2008-2010 John Smith"),
+ ("NOASSERTION", SpdxNoAssertion()),
+ ("NONE", SpdxNone()),
+ ],
+)
+def test_parse_snippet(copyright_text, expected_copyright_text):
snippet_parser = SnippetParser()
snippet_dict = {
@@ -19,7 +28,7 @@ def test_parse_snippet():
"comment": "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a "
"commercial scanner identified it as being derived from file foo.c in package xyz which is licensed"
" under GPL-2.0.",
- "copyrightText": "Copyright 2008-2010 John Smith",
+ "copyrightText": copyright_text,
"licenseComments": "The concluded license was taken from package xyz, from which the snippet was copied into "
"the current file. The concluded license information was found in the COPYING.txt file in "
"package xyz.",
@@ -48,7 +57,7 @@ def test_parse_snippet():
== "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a commercial "
"scanner identified it as being derived from file foo.c in package xyz which is licensed under GPL-2.0."
)
- assert snippet.copyright_text == "Copyright 2008-2010 John Smith"
+ assert snippet.copyright_text == expected_copyright_text
assert (
snippet.license_comment
== "The concluded license was taken from package xyz, from which the snippet was copied into the current file."
|
JSON parser: homepage of package not parsed correctly
The `homepage` field of a package could be `"NOASSERTION"` or `"NONE"`.
When parsing a file like the one below
```
{
"spdxVersion": "SPDX-2.3",
"documentNamespace": "https://true",
"creationInfo": {
"creators": [
"Person: Mee (mee)"
],
"created": "2023-04-17T12:34:39Z",
"licenseListVersion": "3.20"
},
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "Test 2",
"packages": [
{
"SPDXID": "SPDXRef-package",
"name": "Test",
"downloadLocation": "NOASSERTION",
"homepage": "NOASSERTION"
}]
}
```
a `ValidationError` is raised. This originates from the JSON parser which doesn't process the field correctly.
|
0.0
|
3204bda8bb4cb99de97bd08d13cd31cbcb8e8344
|
[
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_file[NOASSERTION-expected_copyright_text1]",
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_file[NONE-expected_copyright_text2]",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_package[http://ftp.gnu.org/gnu/glibc-http://ftp.gnu.org/gnu/glibc-NOASSERTION-expected_download_location0-NONE-expected_copyright_text0-Organization:",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_package[NOASSERTION-expected_homepage1-NONE-expected_download_location1-Copyright",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_package[NONE-expected_homepage2-http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz-http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz-NOASSERTION-expected_copyright_text2-NOASSERTION-expected_originator2-Person:",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_snippet[NOASSERTION-expected_copyright_text1]",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_snippet[NONE-expected_copyright_text2]"
] |
[
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_file[Copyright",
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_incomplete_file",
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_invalid_files",
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_file_types",
"tests/spdx/parser/jsonlikedict/test_file_parser.py::test_parse_invalid_file_types",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_incomplete_package[incomplete_package_dict0-expected_message0]",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_incomplete_package[incomplete_package_dict1-expected_message1]",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_invalid_package",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_packages",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_external_ref",
"tests/spdx/parser/jsonlikedict/test_package_parser.py::test_parse_invalid_external_package_ref_category",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_snippet[Copyright",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_incomplete_snippet",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_snippet_with_invalid_snippet_range",
"tests/spdx/parser/jsonlikedict/test_snippet_parser.py::test_parse_invalid_snippet_range"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-17 13:11:23+00:00
|
apache-2.0
| 5,636 |
|
spdx__tools-python-724
|
diff --git a/src/spdx_tools/spdx/parser/actor_parser.py b/src/spdx_tools/spdx/parser/actor_parser.py
index 734b413..14cc4ff 100644
--- a/src/spdx_tools/spdx/parser/actor_parser.py
+++ b/src/spdx_tools/spdx/parser/actor_parser.py
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
import re
-from beartype.typing import Match, Optional, Pattern
+from beartype.typing import Match, Pattern
from spdx_tools.spdx.model import Actor, ActorType
from spdx_tools.spdx.parser.error import SPDXParsingError
@@ -14,8 +14,8 @@ class ActorParser:
@staticmethod
def parse_actor(actor: str) -> Actor:
tool_re: Pattern = re.compile(r"^Tool:\s*(.+)", re.UNICODE)
- person_re: Pattern = re.compile(r"^Person:\s*(([^(])+)(\((.*)\))?", re.UNICODE)
- org_re: Pattern = re.compile(r"^Organization:\s*(([^(])+)(\((.*)\))?", re.UNICODE)
+ person_re: Pattern = re.compile(r"^Person:\s*(?:(.*)\((.*)\)|(.*))$", re.UNICODE)
+ org_re: Pattern = re.compile(r"^Organization:\s*(?:(.*)\((.*)\)|(.*))$", re.UNICODE)
tool_match: Match = tool_re.match(actor)
person_match: Match = person_re.match(actor)
org_match: Match = org_re.match(actor)
@@ -24,34 +24,30 @@ class ActorParser:
name: str = tool_match.group(1).strip()
if not name:
raise SPDXParsingError([f"No name for Tool provided: {actor}."])
- creator = construct_or_raise_parsing_error(Actor, dict(actor_type=ActorType.TOOL, name=name))
+ return construct_or_raise_parsing_error(Actor, dict(actor_type=ActorType.TOOL, name=name))
- elif person_match:
- name: str = person_match.group(1).strip()
- if not name:
- raise SPDXParsingError([f"No name for Person provided: {actor}."])
- email: Optional[str] = ActorParser.get_email_or_none(person_match)
- creator = construct_or_raise_parsing_error(
- Actor, dict(actor_type=ActorType.PERSON, name=name, email=email)
- )
+ if person_match:
+ actor_type = ActorType.PERSON
+ match = person_match
elif org_match:
- name: str = org_match.group(1).strip()
- if not name:
- raise SPDXParsingError([f"No name for Organization provided: {actor}."])
- email: Optional[str] = ActorParser.get_email_or_none(org_match)
- creator = construct_or_raise_parsing_error(
- Actor, dict(actor_type=ActorType.ORGANIZATION, name=name, email=email)
- )
+ actor_type = ActorType.ORGANIZATION
+ match = org_match
else:
raise SPDXParsingError([f"Actor {actor} doesn't match any of person, organization or tool."])
- return creator
-
- @staticmethod
- def get_email_or_none(match: Match) -> Optional[str]:
- email_match = match.group(4)
- if email_match and email_match.strip():
- email = email_match.strip()
+ if match.group(3):
+ return construct_or_raise_parsing_error(
+ Actor, dict(actor_type=actor_type, name=match.group(3).strip(), email=None)
+ )
else:
- email = None
- return email
+ name = match.group(1)
+ if not name:
+ raise SPDXParsingError([f"No name for Actor provided: {actor}."])
+ else:
+ name = name.strip()
+
+ email = match.group(2).strip()
+
+ return construct_or_raise_parsing_error(
+ Actor, dict(actor_type=actor_type, name=name, email=email if email else None)
+ )
|
spdx/tools-python
|
30af851dbf1165b2021480f85d9eb42f066e07a2
|
diff --git a/tests/spdx/parser/tagvalue/test_annotation_parser.py b/tests/spdx/parser/tagvalue/test_annotation_parser.py
index 2047561..629fe72 100644
--- a/tests/spdx/parser/tagvalue/test_annotation_parser.py
+++ b/tests/spdx/parser/tagvalue/test_annotation_parser.py
@@ -57,7 +57,7 @@ def test_parse_annotation():
"not match specified grammar rule. Line: 1', 'Error while parsing "
"AnnotationDate: Token did not match specified grammar rule. Line: 2']",
),
- ("Annotator: Person: ()", "Error while parsing Annotation: [['No name for Person provided: Person: ().']]"),
+ ("Annotator: Person: ()", "Error while parsing Annotation: [['No name for Actor provided: Person: ().']]"),
(
"AnnotationType: REVIEW",
"Element Annotation is not the current element in scope, probably the "
diff --git a/tests/spdx/test_actor_parser.py b/tests/spdx/test_actor_parser.py
index 17d12a2..2400279 100644
--- a/tests/spdx/test_actor_parser.py
+++ b/tests/spdx/test_actor_parser.py
@@ -21,7 +21,16 @@ from spdx_tools.spdx.parser.error import SPDXParsingError
"[email protected]",
),
("Organization: Example organization ( )", ActorType.ORGANIZATION, "Example organization", None),
+ ("Person: Example person ()", ActorType.PERSON, "Example person", None),
+ ("Person: Example person ", ActorType.PERSON, "Example person", None),
("Tool: Example tool ", ActorType.TOOL, "Example tool", None),
+ ("Tool: Example tool ([email protected])", ActorType.TOOL, "Example tool ([email protected])", None),
+ (
+ "Organization: (c) Chris Sainty ([email protected])",
+ ActorType.ORGANIZATION,
+ "(c) Chris Sainty",
+ "[email protected]",
+ ),
],
)
def test_parse_actor(actor_string, expected_type, expected_name, expected_mail):
@@ -42,6 +51,8 @@ def test_parse_actor(actor_string, expected_type, expected_name, expected_mail):
["Actor Perso: Jane Doe ([email protected]) doesn't match any of person, organization or tool."],
),
("Toole Example Tool ()", ["Actor Toole Example Tool () doesn't match any of person, organization or tool."]),
+ ("Organization:", ["No name for Actor provided: Organization:."]),
+ ("Person: ( )", ["No name for Actor provided: Person: ( )."]),
],
)
def test_parse_invalid_actor(actor_string, expected_message):
|
Is this organization name really invalid?
I'm getting the following error because of this Organization name:
~~~text
Organization: (c) Chris Sainty
~~~
The regex is the following:
~~~text
Organization:\s*(([^(])+)(\((.*)\))?
~~~
The documentation says the following:
~~~text
Organization: organization name and optional (<email>)
~~~
https://spdx.github.io/spdx-spec/v2.2.2/package-information/#76-package-originator-field
Should we update the regex inside this library, or is the organization name invalid?
|
0.0
|
30af851dbf1165b2021480f85d9eb42f066e07a2
|
[
"tests/spdx/parser/tagvalue/test_annotation_parser.py::test_parse_invalid_annotation[Annotator:",
"tests/spdx/test_actor_parser.py::test_parse_actor[Organization:",
"tests/spdx/test_actor_parser.py::test_parse_invalid_actor[Organization:-expected_message2]",
"tests/spdx/test_actor_parser.py::test_parse_invalid_actor[Person:"
] |
[
"tests/spdx/parser/tagvalue/test_annotation_parser.py::test_parse_annotation",
"tests/spdx/parser/tagvalue/test_annotation_parser.py::test_parse_invalid_annotation[AnnotationType:",
"tests/spdx/test_actor_parser.py::test_parse_actor[Person:",
"tests/spdx/test_actor_parser.py::test_parse_actor[Tool:",
"tests/spdx/test_actor_parser.py::test_parse_invalid_actor[Perso:",
"tests/spdx/test_actor_parser.py::test_parse_invalid_actor[Toole"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-05 13:57:54+00:00
|
apache-2.0
| 5,637 |
|
spdx__tools-python-746
|
diff --git a/src/spdx_tools/spdx/validation/uri_validators.py b/src/spdx_tools/spdx/validation/uri_validators.py
index d9c23f9..d3a4237 100644
--- a/src/spdx_tools/spdx/validation/uri_validators.py
+++ b/src/spdx_tools/spdx/validation/uri_validators.py
@@ -9,7 +9,8 @@ from uritools import isabsuri, urisplit
url_pattern = (
"(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/|ssh:\\/\\/|git:\\/\\/|svn:\\/\\/|sftp:"
- "\\/\\/|ftp:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+){0,100}\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?"
+ "\\/\\/|ftp:\\/\\/)?([\\w\\-.!~*'()%;:&=+$,]+@)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+){0,100}\\.[a-z]{2,5}"
+ "(:[0-9]{1,5})?(\\/.*)?"
)
supported_download_repos: str = "(git|hg|svn|bzr)"
git_pattern = "(git\\+git@[a-zA-Z0-9\\.\\-]+:[a-zA-Z0-9/\\\\.@\\-]+)"
|
spdx/tools-python
|
ee95e603c9c774e696edd544131b801ee9bebaea
|
diff --git a/tests/spdx/validation/test_uri_validators.py b/tests/spdx/validation/test_uri_validators.py
index ffe3008..069cb1b 100644
--- a/tests/spdx/validation/test_uri_validators.py
+++ b/tests/spdx/validation/test_uri_validators.py
@@ -34,6 +34,7 @@ def test_invalid_url(input_value):
"git+https://git.myproject.org/MyProject.git",
"git+http://git.myproject.org/MyProject",
"git+ssh://git.myproject.org/MyProject.git",
+ "git+ssh://[email protected]/MyProject.git",
"git+git://git.myproject.org/MyProject",
"[email protected]:MyProject",
"git://git.myproject.org/MyProject#src/somefile.c",
|
Error validating download location with git+ssh URI
When using git URLs to reference packages in npm, the URL often gets normalized to a form like:
```
git+ssh://[email protected]/foo/bar.git#b7e1e0fb20cff47bcca4be90d0c6f83a45e51e9c
```
When using a URL of this form as a `downloadLocation` value, it fails validation due to the `git@` portion of the URL.
Can the URL regex be expanded to allow for the [`userinfo`](https://datatracker.ietf.org/doc/html/rfc2396#section-3.2.2) portion of the URI?
https://github.com/spdx/tools-python/blob/f15a64fdd3c2b889c613997fc35da908a794c607/src/spdx_tools/spdx/validation/uri_validators.py#L10-L12
|
0.0
|
ee95e603c9c774e696edd544131b801ee9bebaea
|
[
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+ssh://[email protected]/MyProject.git]"
] |
[
"tests/spdx/validation/test_uri_validators.py::test_valid_url[https://some.url]",
"tests/spdx/validation/test_uri_validators.py::test_valid_url[https://spdx.org/spdxdocs/spdx-tools-v1.2-3F2504E0-4F89-41D3-9A0C-0305E82...]",
"tests/spdx/validation/test_uri_validators.py::test_valid_url[http://some.url]",
"tests/spdx/validation/test_uri_validators.py::test_valid_url[http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_url[:::::]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_url[http://testurl]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git://git.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+https://git.myproject.org/MyProject.git]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+http://git.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+ssh://git.myproject.org/MyProject.git]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+git://git.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[[email protected]:MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git://git.myproject.org/MyProject#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+https://git.myproject.org/MyProject#src/Class.java]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git://git.myproject.org/MyProject.git@master]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+https://git.myproject.org/[email protected]]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git://git.myproject.org/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+https://git.myproject.org/MyProject.git@master#/src/MyClass.cpp]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[git+https://git.myproject.org/MyProject@da39a3ee5e6b4b0d3255bfef95601890afd80709#lib/variable.rb]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+http://hg.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+ssh://hg.myproject.org/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject#src/Class.java]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject@da39a3ee5e6b]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject@2019]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/[email protected]]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject@special_feature]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject@master#/src/MyClass.cpp]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[hg+https://hg.myproject.org/MyProject@da39a3ee5e6b#lib/variable.rb]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn://svn.myproject.org/svn/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+svn://svn.myproject.org/svn/MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+http://svn.myproject.org/svn/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/svn/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject#src/Class.java]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject/trunk#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject/trunk/src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/svn/MyProject/trunk@2019]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject@123#/src/MyClass.cpp]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[svn+https://svn.myproject.org/MyProject/trunk@1234#lib/variable/variable.rb]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+https://bzr.myproject.org/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+http://bzr.myproject.org/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+sftp://myproject.org/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+ssh://myproject.org/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+ftp://myproject.org/MyProject/trunk]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+lp:MyProject]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+https://bzr.myproject.org/MyProject/trunk#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+https://bzr.myproject.org/MyProject/trunk#src/Class.java]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+https://bzr.myproject.org/MyProject/trunk@2019]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+http://bzr.myproject.org/MyProject/[email protected]]",
"tests/spdx/validation/test_uri_validators.py::test_valid_package_download_location[bzr+https://bzr.myproject.org/MyProject/trunk@2019#src/somefile.c]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_package_download_location[:::::]",
"tests/spdx/validation/test_uri_validators.py::test_valid_uri[https://some.uri]",
"tests/spdx/validation/test_uri_validators.py::test_valid_uri[http:////some]",
"tests/spdx/validation/test_uri_validators.py::test_valid_uri[https://spdx.org/spdxdocs/spdx-tools-v1.2-3F2504E0-4F89-41D3-9A0C-0305E82...]",
"tests/spdx/validation/test_uri_validators.py::test_valid_uri[h://someweirdtest^?]",
"tests/spdx/validation/test_uri_validators.py::test_valid_uri[https://some.uri",
"tests/spdx/validation/test_uri_validators.py::test_invalid_uri[/invalid/uri]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_uri[http//uri]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_uri[http://some#uri]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_uri[some/uri]",
"tests/spdx/validation/test_uri_validators.py::test_invalid_uri[some"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-14 22:09:36+00:00
|
apache-2.0
| 5,638 |
|
spdx__tools-python-757
|
diff --git a/src/spdx_tools/spdx/writer/tagvalue/package_writer.py b/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
index 9be4ec4..f61474f 100644
--- a/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
+++ b/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
@@ -33,7 +33,7 @@ def write_package(package: Package, text_output: TextIO):
write_actor("PackageOriginator", package.originator, text_output)
write_value("PackageDownloadLocation", package.download_location, text_output)
- write_value("FilesAnalyzed", package.files_analyzed, text_output)
+ write_value("FilesAnalyzed", str(package.files_analyzed).lower(), text_output)
if package.verification_code:
package_verification_code = get_package_verification_code_string(package.verification_code)
write_value("PackageVerificationCode", package_verification_code, text_output)
|
spdx/tools-python
|
44196efd14de18aa1363a6ffd6c8c332433e1056
|
diff --git a/tests/spdx/writer/tagvalue/test_package_writer.py b/tests/spdx/writer/tagvalue/test_package_writer.py
index 26c8f9a..994931e 100644
--- a/tests/spdx/writer/tagvalue/test_package_writer.py
+++ b/tests/spdx/writer/tagvalue/test_package_writer.py
@@ -27,7 +27,7 @@ def test_package_writer():
call(f"PackageSupplier: Person: {package.supplier.name} ({package.supplier.email})\n"),
call(f"PackageOriginator: Person: {package.originator.name} ({package.originator.email})\n"),
call(f"PackageDownloadLocation: {package.download_location}\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call(f"PackageVerificationCode: {package.verification_code.value} (excludes: ./exclude.py)\n"),
call("PackageChecksum: SHA1: 71c4025dd9897b364f3ebbb42c484ff43d00791c\n"),
call(f"PackageHomePage: {package.homepage}\n"),
diff --git a/tests/spdx/writer/tagvalue/test_tagvalue_writer.py b/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
index 86e7a2f..487ee0d 100644
--- a/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
+++ b/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
@@ -114,7 +114,7 @@ def test_correct_order_of_elements():
call("PackageName: Test Package A\n"),
call("SPDXID: SPDXRef-Package-A\n"),
call("PackageDownloadLocation: \n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## File Information\n"),
call("FileName: Test File B\n"),
@@ -130,7 +130,7 @@ def test_correct_order_of_elements():
call("PackageName: Test Package B\n"),
call("SPDXID: SPDXRef-Package-B\n"),
call("PackageDownloadLocation: \n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("\n"),
]
@@ -199,7 +199,7 @@ def test_same_file_in_multiple_packages():
call("PackageName: Example package A\n"),
call("SPDXID: SPDXRef-Package-A\n"),
call("PackageDownloadLocation: https://download.com\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## File Information\n"),
call("FileName: Example file\n"),
@@ -210,7 +210,7 @@ def test_same_file_in_multiple_packages():
call("PackageName: Example package B\n"),
call("SPDXID: SPDXRef-Package-B\n"),
call("PackageDownloadLocation: https://download.com\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## Relationships\n"),
call("Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-Package-A\n"),
|
Conversion from JSON tag:value gives invalid SPDX
hello.spdx.json contains:
```
"filesAnalyzed": true,
```
Converting from JSON to tag:value
hello.spdx contains:
```
FilesAnalyzed: True
```
that is invalid as tags and format properties are case sensitive.
[hello.spdx.json.txt](https://github.com/spdx/tools-python/files/12539153/hello.spdx.json.txt)
[hello.spdx.txt](https://github.com/spdx/tools-python/files/12539154/hello.spdx.txt)
|
0.0
|
44196efd14de18aa1363a6ffd6c8c332433e1056
|
[
"tests/spdx/writer/tagvalue/test_package_writer.py::test_package_writer",
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_correct_order_of_elements",
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_same_file_in_multiple_packages"
] |
[
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_write_tag_value"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-08 12:22:28+00:00
|
apache-2.0
| 5,639 |
|
spdx__tools-python-758
|
diff --git a/src/spdx_tools/spdx/parser/tagvalue/parser.py b/src/spdx_tools/spdx/parser/tagvalue/parser.py
index ec843cc..a11f086 100644
--- a/src/spdx_tools/spdx/parser/tagvalue/parser.py
+++ b/src/spdx_tools/spdx/parser/tagvalue/parser.py
@@ -427,7 +427,14 @@ class Parser:
if "files_analyzed" in self.current_element:
self.current_element["logger"].append(f"Multiple values for {p[1]} found. Line: {p.lineno(1)}")
return
- self.current_element["files_analyzed"] = p[2] in ["true", "True"]
+ if p[2] == "true":
+ self.current_element["files_analyzed"] = True
+ elif p[2] == "false":
+ self.current_element["files_analyzed"] = False
+ else:
+ self.current_element["logger"].append(
+ f'The value of FilesAnalyzed must be either "true" or "false", but is: {p[2]}'
+ )
@grammar_rule("primary_package_purpose : PRIMARY_PACKAGE_PURPOSE LINE")
def p_primary_package_purpose(self, p):
diff --git a/src/spdx_tools/spdx/writer/tagvalue/package_writer.py b/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
index 9be4ec4..f61474f 100644
--- a/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
+++ b/src/spdx_tools/spdx/writer/tagvalue/package_writer.py
@@ -33,7 +33,7 @@ def write_package(package: Package, text_output: TextIO):
write_actor("PackageOriginator", package.originator, text_output)
write_value("PackageDownloadLocation", package.download_location, text_output)
- write_value("FilesAnalyzed", package.files_analyzed, text_output)
+ write_value("FilesAnalyzed", str(package.files_analyzed).lower(), text_output)
if package.verification_code:
package_verification_code = get_package_verification_code_string(package.verification_code)
write_value("PackageVerificationCode", package_verification_code, text_output)
|
spdx/tools-python
|
44196efd14de18aa1363a6ffd6c8c332433e1056
|
diff --git a/tests/spdx/parser/tagvalue/test_package_parser.py b/tests/spdx/parser/tagvalue/test_package_parser.py
index e38351b..470f1e2 100644
--- a/tests/spdx/parser/tagvalue/test_package_parser.py
+++ b/tests/spdx/parser/tagvalue/test_package_parser.py
@@ -22,7 +22,7 @@ def test_parse_package():
"SPDXID: SPDXRef-Package",
"PackageVersion: 1:22.36.1-8+deb11u1",
"PackageDownloadLocation: http://example.com/test",
- "FilesAnalyzed: True",
+ "FilesAnalyzed: true",
"PackageSummary: <text>Test package</text>",
"PackageSourceInfo: <text>Version 1.0 of test</text>",
"PackageFileName: test-1.0.zip",
@@ -123,6 +123,12 @@ def test_parse_package():
"match specified grammar rule. Line: 2', 'Error while parsing "
"ValidUntilDate: Token did not match specified grammar rule. Line: 3']",
),
+ (
+ f"SPDXID:{DOCUMENT_SPDX_ID}\nPackageName: TestPackage\nSPDXID:SPDXRef-Package\n"
+ "PackageDownloadLocation: download.com\nFilesAnalyzed: FALSE",
+ "Error while parsing Package: "
+ '[\'The value of FilesAnalyzed must be either "true" or "false", but is: FALSE\']',
+ ),
],
)
def test_parse_invalid_package(package_str, expected_message):
diff --git a/tests/spdx/writer/tagvalue/test_package_writer.py b/tests/spdx/writer/tagvalue/test_package_writer.py
index 26c8f9a..994931e 100644
--- a/tests/spdx/writer/tagvalue/test_package_writer.py
+++ b/tests/spdx/writer/tagvalue/test_package_writer.py
@@ -27,7 +27,7 @@ def test_package_writer():
call(f"PackageSupplier: Person: {package.supplier.name} ({package.supplier.email})\n"),
call(f"PackageOriginator: Person: {package.originator.name} ({package.originator.email})\n"),
call(f"PackageDownloadLocation: {package.download_location}\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call(f"PackageVerificationCode: {package.verification_code.value} (excludes: ./exclude.py)\n"),
call("PackageChecksum: SHA1: 71c4025dd9897b364f3ebbb42c484ff43d00791c\n"),
call(f"PackageHomePage: {package.homepage}\n"),
diff --git a/tests/spdx/writer/tagvalue/test_tagvalue_writer.py b/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
index 86e7a2f..487ee0d 100644
--- a/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
+++ b/tests/spdx/writer/tagvalue/test_tagvalue_writer.py
@@ -114,7 +114,7 @@ def test_correct_order_of_elements():
call("PackageName: Test Package A\n"),
call("SPDXID: SPDXRef-Package-A\n"),
call("PackageDownloadLocation: \n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## File Information\n"),
call("FileName: Test File B\n"),
@@ -130,7 +130,7 @@ def test_correct_order_of_elements():
call("PackageName: Test Package B\n"),
call("SPDXID: SPDXRef-Package-B\n"),
call("PackageDownloadLocation: \n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("\n"),
]
@@ -199,7 +199,7 @@ def test_same_file_in_multiple_packages():
call("PackageName: Example package A\n"),
call("SPDXID: SPDXRef-Package-A\n"),
call("PackageDownloadLocation: https://download.com\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## File Information\n"),
call("FileName: Example file\n"),
@@ -210,7 +210,7 @@ def test_same_file_in_multiple_packages():
call("PackageName: Example package B\n"),
call("SPDXID: SPDXRef-Package-B\n"),
call("PackageDownloadLocation: https://download.com\n"),
- call("FilesAnalyzed: True\n"),
+ call("FilesAnalyzed: true\n"),
call("\n"),
call("## Relationships\n"),
call("Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-Package-A\n"),
|
Tags and format properties are case sensitive
The spec says: "Tags and format properties are case sensitive".
The document contains:
```
FilesAnalyzed: TRUE
```
pyspdxtools -i hello.spdx
ERROR:root:The document is invalid. The following issues have been found:
package must contain no elements if files_analyzed is False, but found [Relationship(spdx_element_id='SPDXRef-Package-hello', relationship_type=<RelationshipType.CONTAINS: 6>, related_spdx_element_id='SPDXRef-hello-binary', comment=None), Relationship(spdx_element_id='SPDXRef-Package-hello', relationship_type=<RelationshipType.CONTAINS: 6>, related_spdx_element_id='SPDXRef-Makefile', comment=None), Relationship(spdx_element_id='SPDXRef-Package-hello', relationship_type=<RelationshipType.CONTAINS: 6>, related_spdx_element_id='SPDXRef-hello-src', comment=None)]
license_info_from_files must be None if files_analyzed is False, but is: [LicenseSymbol('GPL-3.0-or-later', aliases=('GPL-3.0+', 'LicenseRef-GPL-3.0-or-later'), is_exception=False)]
verification_code must be None if files_analyzed is False, but is: PackageVerificationCode(value='9d20237bb72087e87069f96afb41c6ca2fa2a342', excluded_files=[])
The error message is misleading.
It should say that TRUE is not a correct value for FilesAnalyzed, instead of saying that FilesAnalyzed is False and outputing an error message assuming that FilesAnalyzed is false.
[hello.spdx.txt](https://github.com/spdx/tools-python/files/12538780/hello.spdx.txt)
|
0.0
|
44196efd14de18aa1363a6ffd6c8c332433e1056
|
[
"tests/spdx/parser/tagvalue/test_package_parser.py::test_parse_invalid_package[SPDXID:SPDXRef-DOCUMENT\\nPackageName:",
"tests/spdx/writer/tagvalue/test_package_writer.py::test_package_writer",
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_correct_order_of_elements",
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_same_file_in_multiple_packages"
] |
[
"tests/spdx/parser/tagvalue/test_package_parser.py::test_parse_package",
"tests/spdx/parser/tagvalue/test_package_parser.py::test_parse_invalid_package[PackageDownloadLocation:",
"tests/spdx/parser/tagvalue/test_package_parser.py::test_parse_invalid_package[PackageName:",
"tests/spdx/writer/tagvalue/test_tagvalue_writer.py::test_write_tag_value"
] |
{
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-08 12:46:52+00:00
|
apache-2.0
| 5,640 |
|
spdx__tools-python-772
|
diff --git a/src/spdx_tools/spdx/parser/tagvalue/parser.py b/src/spdx_tools/spdx/parser/tagvalue/parser.py
index a11f086..32be114 100644
--- a/src/spdx_tools/spdx/parser/tagvalue/parser.py
+++ b/src/spdx_tools/spdx/parser/tagvalue/parser.py
@@ -14,7 +14,7 @@
import re
from beartype.typing import Any, Dict, List
-from license_expression import get_spdx_licensing
+from license_expression import ExpressionError, get_spdx_licensing
from ply import yacc
from ply.yacc import LRParser
@@ -233,7 +233,13 @@ class Parser:
@grammar_rule("license_or_no_assertion_or_none : LINE")
def p_license(self, p):
- p[0] = get_spdx_licensing().parse(p[1])
+ try:
+ p[0] = get_spdx_licensing().parse(p[1])
+ except ExpressionError as err:
+ error_message = f"Error while parsing license expression: {p[1]}"
+ if err.args:
+ error_message += f": {err.args[0]}"
+ self.current_element["logger"].append(error_message)
@grammar_rule("actor_or_no_assertion : PERSON_VALUE\n | ORGANIZATION_VALUE")
def p_actor_values(self, p):
|
spdx/tools-python
|
32e74cdc8a39bc3b4119bc6e77f3804d09a05418
|
diff --git a/tests/spdx/parser/tagvalue/test_tag_value_parser.py b/tests/spdx/parser/tagvalue/test_tag_value_parser.py
index 33defcb..9f347fc 100644
--- a/tests/spdx/parser/tagvalue/test_tag_value_parser.py
+++ b/tests/spdx/parser/tagvalue/test_tag_value_parser.py
@@ -98,3 +98,41 @@ def test_document_with_mixed_values():
"Element Package is not the current element in scope, probably the expected "
"tag to start the element (PackageName) is missing. Line: 4"
]
+
+
+def test_faulty_license_expression():
+ parser = Parser()
+ document_str = "\n".join(
+ [
+ f"SPDXID:{DOCUMENT_SPDX_ID}",
+ "FileName: File with faulty license expression",
+ "SPDXID: SPDXRef-File",
+ "FileChecksum: SHA1: d6a770ba38583ed4bb4525bd96e50461655d2759",
+ "LicenseConcluded: LicenseRef-foo/bar",
+ "PackageName: Package with faulty license expression",
+ "SPDXID: SPDXRef-Package",
+ "PackageDownloadLocation: www.download.com",
+ "PackageLicenseConcluded: LicenseRef-bar/foo",
+ "SnippetSPDXID: SPDXRef-Snippet",
+ "SnippetName: Snippet with faulty license expression",
+ "SnippetLicenseConcluded: LicenseRef-foo/foo",
+ ]
+ )
+
+ with pytest.raises(SPDXParsingError) as err:
+ parser.parse(document_str)
+
+ assert err.value.get_messages() == [
+ 'Error while parsing File: ["Error while parsing license expression: '
+ "LicenseRef-foo/bar: Invalid license key: the valid characters are: letters "
+ "and numbers, underscore, dot, colon or hyphen signs and spaces: "
+ "'LicenseRef-foo/bar'\"]",
+ 'Error while parsing Package: ["Error while parsing license expression: '
+ "LicenseRef-bar/foo: Invalid license key: the valid characters are: letters "
+ "and numbers, underscore, dot, colon or hyphen signs and spaces: "
+ "'LicenseRef-bar/foo'\"]",
+ 'Error while parsing Snippet: ["Error while parsing license expression: '
+ "LicenseRef-foo/foo: Invalid license key: the valid characters are: letters "
+ "and numbers, underscore, dot, colon or hyphen signs and spaces: "
+ "'LicenseRef-foo/foo'\"]",
+ ]
|
Exception not catched with LicenseRef- containing slash
[slash.spdx.txt](https://github.com/spdx/tools-python/files/13284277/slash.spdx.txt)
File contains the following line:
```
LicenseConcluded: LicenseRef-foo/bar
```
which is invalid due to the slash.
This results in a big ugly error.
The exception should be catched.
```
pyspdxtools -i slash.spdx
Traceback (most recent call last):
File "/opt/homebrew/bin/pyspdxtools", line 8, in <module>
sys.exit(main())
^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/clitools/pyspdxtools.py", line 61, in main
document: Document = parse_file(infile)
^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/parser/parse_anything.py", line 25, in parse_file
return tagvalue_parser.parse_from_file(file_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/parser/tagvalue/tagvalue_parser.py", line 12, in parse_from_file
document: Document = parser.parse(data)
^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/parser/tagvalue/parser.py", line 524, in parse
self.yacc.parse(text, lexer=self.lex)
File "/opt/homebrew/lib/python3.11/site-packages/ply/yacc.py", line 333, in parse
return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/ply/yacc.py", line 1120, in parseopt_notrack
p.callable(pslice)
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/parser/tagvalue/parser.py", line 236, in p_license
p[0] = get_spdx_licensing().parse(p[1])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 540, in parse
tokens = list(self.tokenize(
^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 604, in tokenize
for token in tokens:
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 997, in replace_with_subexpression_by_license_symbol
for token_group in token_groups:
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 936, in build_token_groups_for_with_subexpression
tokens = list(tokens)
^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 598, in <genexpr>
tokens = (t for t in tokens if t.string and t.string.strip())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 922, in build_symbols_from_unknown_tokens
for symtok in build_token_with_symbol():
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 902, in build_token_with_symbol
toksym = LicenseSymbol(string)
^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/license_expression/__init__.py", line 1214, in __init__
raise ExpressionError(
license_expression.ExpressionError: Invalid license key: the valid characters are: letters and numbers, underscore, dot, colon or hyphen signs and spaces: 'LicenseRef-foo/bar'
```
|
0.0
|
32e74cdc8a39bc3b4119bc6e77f3804d09a05418
|
[
"tests/spdx/parser/tagvalue/test_tag_value_parser.py::test_faulty_license_expression"
] |
[
"tests/spdx/parser/tagvalue/test_tag_value_parser.py::test_parse_unknown_tag",
"tests/spdx/parser/tagvalue/test_tag_value_parser.py::test_building_contains_relationship",
"tests/spdx/parser/tagvalue/test_tag_value_parser.py::test_build_contains_relationship_with_error",
"tests/spdx/parser/tagvalue/test_tag_value_parser.py::test_document_with_mixed_values"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-11-09 15:30:12+00:00
|
apache-2.0
| 5,641 |
|
spdx__tools-python-778
|
diff --git a/src/spdx_tools/spdx/writer/tagvalue/tagvalue_writer_helper_functions.py b/src/spdx_tools/spdx/writer/tagvalue/tagvalue_writer_helper_functions.py
index 907c155..98f6702 100644
--- a/src/spdx_tools/spdx/writer/tagvalue/tagvalue_writer_helper_functions.py
+++ b/src/spdx_tools/spdx/writer/tagvalue/tagvalue_writer_helper_functions.py
@@ -83,7 +83,9 @@ def scan_relationships(
files_by_spdx_id = {file.spdx_id: file for file in files}
packages_spdx_ids = [package.spdx_id for package in packages]
for relationship in relationships:
- if (
+ if relationship.related_spdx_element_id in [SpdxNoAssertion(), SpdxNone()]:
+ relationships_to_write.append(relationship)
+ elif (
relationship.relationship_type == RelationshipType.CONTAINS
and relationship.spdx_element_id in packages_spdx_ids
and relationship.related_spdx_element_id in files_by_spdx_id.keys()
|
spdx/tools-python
|
e0c83cdf11863d40f26e1da4b940eebb769fe3f3
|
diff --git a/tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py b/tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py
index d101fd3..4949b43 100644
--- a/tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py
+++ b/tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, call, mock_open, patch
import pytest
-from spdx_tools.spdx.model import ActorType, RelationshipType, SpdxNoAssertion
+from spdx_tools.spdx.model import ActorType, RelationshipType, SpdxNoAssertion, SpdxNone
from spdx_tools.spdx.writer.tagvalue.tagvalue_writer_helper_functions import scan_relationships, write_actor
from tests.spdx.fixtures import actor_fixture, file_fixture, package_fixture, relationship_fixture
@@ -16,6 +16,18 @@ def test_scan_relationships():
packages = [package_fixture(spdx_id=first_package_spdx_id), package_fixture(spdx_id=second_package_spdx_id)]
file_spdx_id = "SPDXRef-File"
files = [file_fixture(spdx_id=file_spdx_id)]
+ no_assertion_relationship = relationship_fixture(
+ spdx_element_id=second_package_spdx_id,
+ relationship_type=RelationshipType.CONTAINS,
+ related_spdx_element_id=SpdxNoAssertion(),
+ comment=None,
+ )
+ none_relationship = relationship_fixture(
+ spdx_element_id=second_package_spdx_id,
+ relationship_type=RelationshipType.CONTAINS,
+ related_spdx_element_id=SpdxNone(),
+ comment=None,
+ )
relationships = [
relationship_fixture(
spdx_element_id=first_package_spdx_id,
@@ -29,11 +41,13 @@ def test_scan_relationships():
related_spdx_element_id=file_spdx_id,
comment=None,
),
+ no_assertion_relationship,
+ none_relationship,
]
relationships_to_write, contained_files_by_package_id = scan_relationships(relationships, packages, files)
- assert relationships_to_write == []
+ assert relationships_to_write == [no_assertion_relationship, none_relationship]
assert contained_files_by_package_id == {first_package_spdx_id: files, second_package_spdx_id: files}
|
Valid SPDX cannot be converted from JSON to tag:value
[bug.spdx.json](https://github.com/spdx/tools-python/files/13452674/bug.spdx.json)
File ```bug.spdx.json```is valid SPDX:
```
pyspdxtools -i bug.spdx.json
```
But it cannot be converted to tag:value:
```
pyspdxtools -i bug.spdx.json -o bug.spdx
Traceback (most recent call last):
File "/opt/homebrew/bin/pyspdxtools", line 8, in <module>
sys.exit(main())
^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/clitools/pyspdxtools.py", line 96, in main
write_file(document, outfile, validate=False)
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/writer/write_anything.py", line 22, in write_file
tagvalue_writer.write_document_to_file(document, file_name, validate)
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/writer/tagvalue/tagvalue_writer.py", line 39, in write_document_to_file
write_document_to_stream(document, out, validate, drop_duplicates)
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/writer/tagvalue/tagvalue_writer.py", line 34, in write_document_to_stream
write_document(document, stream)
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/writer/tagvalue/tagvalue_writer.py", line 43, in write_document
relationships_to_write, contained_files_by_package_id = scan_relationships(
^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/spdx_tools/spdx/writer/tagvalue/tagvalue_writer_helper_functions.py", line 89, in scan_relationships
and relationship.related_spdx_element_id in files_by_spdx_id.keys()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'SpdxNoAssertion'
```
|
0.0
|
e0c83cdf11863d40f26e1da4b940eebb769fe3f3
|
[
"tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py::test_scan_relationships"
] |
[
"tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py::test_write_actor[element_to_write0-expected_calls0]",
"tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py::test_write_actor[element_to_write1-expected_calls1]",
"tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py::test_write_actor[element_to_write2-expected_calls2]",
"tests/spdx/writer/tagvalue/test_tagvalue_writer_helper_functions.py::test_write_actor[element_to_write3-expected_calls3]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-07 15:21:32+00:00
|
apache-2.0
| 5,642 |
|
spdx__tools-python-98
|
diff --git a/spdx/parsers/rdf.py b/spdx/parsers/rdf.py
index 7aa98a5..568aa06 100644
--- a/spdx/parsers/rdf.py
+++ b/spdx/parsers/rdf.py
@@ -266,12 +266,7 @@ class LicenseParser(BaseParser):
for _, _, lics_member in self.graph.triples(
(lics_set, self.spdx_namespace['member'], None)):
try:
- if (lics_member, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:
- lics = self.handle_extracted_license(lics_member)
- if lics is not None:
- licenses.append(lics)
- else:
- licenses.append(self.handle_lics(lics_member))
+ licenses.append(self.handle_lics(lics_member))
except CardinalityError:
self.value_error('LICS_LIST_MEMBER', lics_member)
break
@@ -935,6 +930,9 @@ class Parser(PackageParser, FileParser, SnippetParser, ReviewParser, AnnotationP
for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['CreationInfo'])):
self.parse_creation_info(s)
+
+ for s, _p, o in self.graph.triples((None, None, self.spdx_namespace['ExtractedLicensingInfo'])):
+ self.handle_extracted_license(s)
for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['Package'])):
self.parse_package(s)
|
spdx/tools-python
|
276e30d5ddeae98e4cefb455b4d245506e6345b1
|
diff --git a/tests/test_rdf_parser.py b/tests/test_rdf_parser.py
new file mode 100644
index 0000000..c212837
--- /dev/null
+++ b/tests/test_rdf_parser.py
@@ -0,0 +1,54 @@
+import unittest
+import re
+from unittest import TestCase
+from spdx.parsers.rdf import Parser
+from spdx.parsers.rdfbuilders import Builder
+from spdx.parsers.loggers import StandardLogger
+from tests import utils_test
+
+class TestParser(TestCase):
+
+ def test_extracted_licenses(self):
+ parser = Parser(Builder(), StandardLogger())
+ test_file = utils_test.get_test_loc('../../data/SPDXRdfExample.rdf', test_data_dir=utils_test.test_data_dir)
+ with open(test_file, 'r') as file:
+ document, _ = parser.parse(file)
+ assert len(document.extracted_licenses) == 4
+ # It is needed to sort the list because the order changes when parsing
+ licenses = sorted(document.extracted_licenses)
+ assert licenses[0].identifier.toPython() == 'LicenseRef-1'
+ assert licenses[1].identifier.toPython() == 'LicenseRef-2'
+ assert licenses[2].identifier.toPython() == 'LicenseRef-3'
+ assert licenses[3].identifier.toPython() == 'LicenseRef-4'
+
+ def test_pkg_lic_decl(self):
+ parser = Parser(Builder(), StandardLogger())
+ test_file = utils_test.get_test_loc('../../data/SPDXRdfExample.rdf', test_data_dir=utils_test.test_data_dir)
+ with open(test_file, 'r') as file:
+ document, _ = parser.parse(file)
+ # It is needed to ckeck it as sorted lists because the order changes when parsing
+ lic_expected = ['Apache-2.0', 'LicenseRef-1', 'LicenseRef-2', 'LicenseRef-3', 'LicenseRef-4', 'MPL-1.1']
+ lic_result = sorted(document.package.license_declared.identifier.split(' AND '))
+ assert lic_result == lic_expected
+
+ def test_pkg_lic_conc(self):
+ parser = Parser(Builder(), StandardLogger())
+ test_file = utils_test.get_test_loc('../../data/SPDXRdfExample.rdf', test_data_dir=utils_test.test_data_dir)
+ with open(test_file, 'r') as file:
+ document, _ = parser.parse(file)
+ # It is needed to ckeck it as sorted lists because the order changes when parsing
+ lic_expected = ['Apache-1.0', 'Apache-2.0', 'LicenseRef-1', 'LicenseRef-2', 'LicenseRef-3', 'LicenseRef-4', 'MPL-1.1']
+ lic_result = sorted(document.package.conc_lics.identifier.split(' AND '))
+ assert lic_result == lic_expected
+
+ def test_file_lic_conc(self):
+ parser = Parser(Builder(), StandardLogger())
+ test_file = utils_test.get_test_loc('../../data/SPDXRdfExample.rdf', test_data_dir=utils_test.test_data_dir)
+ with open(test_file, 'r') as file:
+ document, _ = parser.parse(file)
+ files = sorted(document.package.files)
+ assert files[0].conc_lics.identifier.toPython() == 'LicenseRef-1'
+ assert files[1].conc_lics.identifier == 'Apache-2.0'
+
+if __name__ == '__main__':
+ unittest.main()
|
Duplicate extracted licenses when parsing from RDF
The field Document.extracted_licenses contains duplicate ExtractedLicense objects when they are parsed from RDF files.
It can be noticed by running [parse_rdf.py](https://github.com/spdx/tools-python/blob/master/examples/parse_rdf.py).
Input: [SPDXRdfExample.rdf](https://github.com/spdx/tools-python/blob/master/data/SPDXRdfExample.rdf)
Output:
```
doc comment: This is a sample spreadsheet
Creators:
Person: Gary O'Neall
Tool: SourceAuditor-V1.2
Organization: Source Auditor Inc.
Document review information:
Reviewer: Person: Suzanne Reviewer
Date: 2011-03-13 00:00:00
Comment: Another example reviewer.
Reviewer: Person: Joe Reviewer
Date: 2010-02-10 00:00:00
Comment: This is just an example. Some of the non-standard licenses look like they are actually BSD 3 clause licenses
Creation comment: This is an example of an SPDX spreadsheet format
Package Name: SPDX Translator
Package Version: Version 0.9.2
Package Download Location: http://www.spdx.org/tools
Package Homepage: None
Package Checksum: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
Package verification code: 4e3211c67a2d28fced849ee1bb76e7391b93feba
Package excluded from verif: SpdxTranslatorSpdx.txt,SpdxTranslatorSpdx.rdf
Package license concluded: LicenseRef-4 AND LicenseRef-2 AND Apache-1.0 AND LicenseRef-3 AND LicenseRef-1 AND Apache-2.0 AND MPL-1.1
Package license declared: MPL-1.1 AND Apache-2.0 AND LicenseRef-3 AND LicenseRef-2 AND LicenseRef-4 AND LicenseRef-1
Package licenses from files:
LicenseRef-1
LicenseRef-3
Apache-1.0
MPL-1.1
LicenseRef-4
LicenseRef-2
Apache-2.0
Package Copyright text: Copyright 2010, 2011 Source Auditor Inc.
Package summary: SPDX Translator utility
Package description: This utility translates and SPDX RDF XML document to a spreadsheet, translates a spreadsheet to an SPDX RDF XML document and translates an SPDX RDFa document to an SPDX RDF XML document.
Package Files:
File name: Jenna-2.6.3/jena-2.6.3-sources.jar
File type: ARCHIVE
File Checksum: 3ab4e1c67a2d28fced849ee1bb76e7391b93f125
File license concluded: LicenseRef-1
File license info in file: LicenseRef-1
File artifact of project name: Jena
File name: src/org/spdx/parser/DOAPProject.java
File type: SOURCE
File Checksum: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
File license concluded: Apache-2.0
File license info in file: Apache-2.0
File artifact of project name:
Document Extracted licenses:
Identifier: LicenseRef-4
Name: None
Identifier: LicenseRef-2
Name: None
Identifier: LicenseRef-3
Name: CyberNeko License
Identifier: LicenseRef-1
Name: None
Identifier: LicenseRef-3
Name: CyberNeko License
Identifier: LicenseRef-2
Name: None
Identifier: LicenseRef-4
Name: None
Identifier: LicenseRef-1
Name: None
Annotations:
Annotator: Person: Jim Reviewer
Annotation Date: 2012-06-13 00:00:00
Annotation Comment: This is just an example. Some of the non-standard licenses look like they are actually BSD 3 clause licenses
Annotation Type: REVIEW
Annotation SPDX Identifier: https://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301#SPDXRef-45
```
|
0.0
|
276e30d5ddeae98e4cefb455b4d245506e6345b1
|
[
"tests/test_rdf_parser.py::TestParser::test_extracted_licenses"
] |
[
"tests/test_rdf_parser.py::TestParser::test_pkg_lic_conc",
"tests/test_rdf_parser.py::TestParser::test_file_lic_conc",
"tests/test_rdf_parser.py::TestParser::test_pkg_lic_decl"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-04-07 08:32:02+00:00
|
apache-2.0
| 5,643 |
|
spectacles-ci__spectacles-179
|
diff --git a/spectacles/cli.py b/spectacles/cli.py
index 9b7a275..15f244f 100644
--- a/spectacles/cli.py
+++ b/spectacles/cli.py
@@ -5,17 +5,14 @@ from yaml.parser import ParserError
import argparse
import logging
import os
-from typing import Callable, Iterable, List
+from typing import Callable, Iterable, List, Optional
from spectacles import __version__
from spectacles.runner import Runner
from spectacles.client import LookerClient
-from spectacles.exceptions import SpectaclesException, ValidationError
-from spectacles.logger import GLOBAL_LOGGER as logger, FileFormatter
+from spectacles.exceptions import SpectaclesException, ValidationError, SqlError
+from spectacles.logger import GLOBAL_LOGGER as logger, set_file_handler
import spectacles.printer as printer
-LOG_FILENAME = "spectacles.log"
-LOG_FILEPATH = Path()
-
class ConfigFileAction(argparse.Action):
"""Parses an arbitrary config file and assigns its values as arg defaults."""
@@ -142,7 +139,7 @@ def handle_exceptions(function: Callable) -> Callable:
logger.debug(error, exc_info=True)
logger.error(
f'Encountered unexpected {error.__class__.__name__}: "{error}"\n'
- f"Full error traceback logged to {LOG_FILEPATH}\n\n"
+ f"Full error traceback logged to file.\n\n"
+ printer.dim(
"For support, please create an issue at "
"https://github.com/spectacles-ci/spectacles/issues"
@@ -154,23 +151,6 @@ def handle_exceptions(function: Callable) -> Callable:
return wrapper
-def set_file_handler(directory: str) -> None:
-
- global LOG_FILEPATH
-
- log_directory = Path(directory)
- LOG_FILEPATH = Path(log_directory / LOG_FILENAME)
- log_directory.mkdir(exist_ok=True)
-
- fh = logging.FileHandler(LOG_FILEPATH)
- fh.setLevel(logging.DEBUG)
-
- formatter = FileFormatter("%(asctime)s %(levelname)s | %(message)s")
- fh.setFormatter(formatter)
-
- logger.addHandler(fh)
-
-
@handle_exceptions
def main():
"""Runs main function. This is the entry point."""
@@ -191,6 +171,7 @@ def main():
)
elif args.command == "sql":
run_sql(
+ args.log_dir,
args.project,
args.branch,
args.explores,
@@ -440,6 +421,31 @@ def _build_assert_subparser(
)
+def log_failing_sql(
+ error: SqlError,
+ log_dir: str,
+ model_name: str,
+ explore_name: str,
+ dimension_name: Optional[str] = None,
+):
+
+ file_name = (
+ model_name
+ + "__"
+ + explore_name
+ + ("__" + dimension_name if dimension_name else "")
+ + ".sql"
+ )
+ file_path = Path(log_dir) / "queries" / file_name
+ print(file_path)
+
+ logger.debug(f"Logging failing SQL query for '{error.path}' to '{file_path}'")
+ logger.debug(f"Failing SQL for {error.path}: \n{error.sql}")
+
+ with open(file_path, "w") as file:
+ file.write(error.sql)
+
+
def run_connect(
base_url: str, client_id: str, client_secret: str, port: int, api_version: float
) -> None:
@@ -471,6 +477,7 @@ def run_assert(
def run_sql(
+ log_dir,
project,
branch,
explores,
@@ -508,9 +515,17 @@ def run_sql(
for explore in iter_errors(model.explores):
if explore.error:
printer.print_sql_error(explore.error)
+ log_failing_sql(explore.error, log_dir, model.name, explore.name)
else:
for dimension in iter_errors(explore.dimensions):
printer.print_sql_error(dimension.error)
+ log_failing_sql(
+ dimension.error,
+ log_dir,
+ model.name,
+ explore.name,
+ dimension.name,
+ )
logger.info("")
raise ValidationError
diff --git a/spectacles/logger.py b/spectacles/logger.py
index 2c3696f..844fd49 100644
--- a/spectacles/logger.py
+++ b/spectacles/logger.py
@@ -1,7 +1,8 @@
+from pathlib import Path
import logging
import colorama # type: ignore
-
+LOG_FILENAME = "spectacles.log"
COLORS = {
"red": colorama.Fore.RED,
"green": colorama.Fore.GREEN,
@@ -12,6 +13,33 @@ COLORS = {
"reset": colorama.Style.RESET_ALL,
}
+logger = logging.getLogger("spectacles")
+logger.setLevel(logging.DEBUG)
+
+ch = logging.StreamHandler()
+ch.setLevel(logging.INFO)
+
+logger.addHandler(ch)
+
+GLOBAL_LOGGER = logger
+
+
+def set_file_handler(log_dir: str) -> None:
+ log_dir_path = Path(log_dir)
+ LOG_FILEPATH = log_dir_path / LOG_FILENAME
+ log_dir_path.mkdir(exist_ok=True)
+
+ # Create subfolder to save the SQL for failed queries
+ (log_dir_path / "queries").mkdir(exist_ok=True)
+
+ fh = logging.FileHandler(LOG_FILEPATH)
+ fh.setLevel(logging.DEBUG)
+
+ formatter = FileFormatter("%(asctime)s %(levelname)s | %(message)s")
+ fh.setFormatter(formatter)
+
+ logger.addHandler(fh)
+
def delete_color_codes(text: str) -> str:
for escape_sequence in COLORS.values():
@@ -24,14 +52,3 @@ class FileFormatter(logging.Formatter):
message = super().format(record=record)
formatted = delete_color_codes(message)
return formatted
-
-
-logger = logging.getLogger("spectacles")
-logger.setLevel(logging.DEBUG)
-
-ch = logging.StreamHandler()
-ch.setLevel(logging.INFO)
-
-logger.addHandler(ch)
-
-GLOBAL_LOGGER = logger
|
spectacles-ci/spectacles
|
fc28a0e44ab4c29e549e219e940c7db405408da3
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 76dc2cc..60380eb 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1,8 +1,9 @@
from unittest.mock import patch
import pytest
from constants import ENV_VARS
-from spectacles.cli import main, create_parser, handle_exceptions
-from spectacles.exceptions import SpectaclesException, ValidationError
+from pathlib import Path
+from spectacles.cli import main, create_parser, handle_exceptions, log_failing_sql
+from spectacles.exceptions import SpectaclesException, ValidationError, SqlError
@pytest.fixture
@@ -181,3 +182,51 @@ def test_bad_config_file_parameter(mock_parse_config, clean_env, parser):
def test_parse_remote_reset_with_assert(env, parser):
args = parser.parse_args(["assert", "--remote-reset"])
assert args.remote_reset
+
+
+def test_logging_failing_explore_sql(tmpdir):
+ error = SqlError(
+ path="example_explore",
+ message="example error message",
+ sql="select example_explore.example_dimension_1 from model",
+ explore_url="https://example.looker.com/x/12345",
+ )
+
+ query_directory = Path(tmpdir / "queries")
+ query_directory.mkdir(exist_ok=True)
+ query_file = Path(query_directory / "explore_model__example_explore.sql")
+
+ log_failing_sql(error, tmpdir, "explore_model", "example_explore")
+ content = open(query_file).read()
+
+ assert Path.exists(query_file)
+ assert content == "select example_explore.example_dimension_1 from model"
+
+
+def test_logging_failing_dimension_sql(tmpdir):
+ error = SqlError(
+ path="example_explore",
+ message="example error message",
+ sql="select example_explore.example_dimension_1 from model",
+ explore_url="https://example.looker.com/x/12345",
+ )
+
+ query_directory = Path(tmpdir / "queries")
+ query_directory.mkdir(exist_ok=True)
+ query_file = (
+ query_directory
+ / "explore_model__example_explore__example_explore.example_dimension_1.sql"
+ )
+
+ log_failing_sql(
+ error,
+ tmpdir,
+ "explore_model",
+ "example_explore",
+ "example_explore.example_dimension_1",
+ )
+
+ content = open(query_file).read()
+
+ assert content == "select example_explore.example_dimension_1 from model"
+ assert Path.exists(query_file)
|
Failing SQL is not saved to file
After some architectural changes, failing SQL queries are no longer being logged to file. We need to reintroduce this feature. It should probably live in `cli.py`, using the value of the `sql` key in the dictionary returned by the runner.
Previously, in single-dimension mode, spectacles would create a folder per explore with a `.sql` file for each dimension query. In batch mode, it would create a `.sql` file per explore in the base directory.
These files were all created in the `logs` directory.
|
0.0
|
fc28a0e44ab4c29e549e219e940c7db405408da3
|
[
"tests/test_cli.py::test_help",
"tests/test_cli.py::test_handle_exceptions_unhandled_error[ValueError-1]",
"tests/test_cli.py::test_handle_exceptions_unhandled_error[SpectaclesException-100]",
"tests/test_cli.py::test_handle_exceptions_unhandled_error[ValidationError-102]",
"tests/test_cli.py::test_parse_args_with_no_arguments_supplied",
"tests/test_cli.py::test_parse_args_with_one_argument_supplied",
"tests/test_cli.py::test_parse_args_with_only_cli",
"tests/test_cli.py::test_parse_args_with_only_config_file",
"tests/test_cli.py::test_parse_args_with_incomplete_config_file",
"tests/test_cli.py::test_parse_args_with_only_env_vars",
"tests/test_cli.py::test_parse_args_with_incomplete_env_vars",
"tests/test_cli.py::test_arg_precedence",
"tests/test_cli.py::test_env_var_override_argparse_default",
"tests/test_cli.py::test_config_override_argparse_default",
"tests/test_cli.py::test_bad_config_file_parameter",
"tests/test_cli.py::test_parse_remote_reset_with_assert",
"tests/test_cli.py::test_logging_failing_explore_sql",
"tests/test_cli.py::test_logging_failing_dimension_sql"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-04 16:04:16+00:00
|
mit
| 5,644 |
|
spectacles-ci__spectacles-90
|
diff --git a/spectacles/cli.py b/spectacles/cli.py
index 5dcdd5c..e03bfab 100644
--- a/spectacles/cli.py
+++ b/spectacles/cli.py
@@ -173,7 +173,7 @@ def main():
args.client_secret,
args.port,
args.api_version,
- args.batch,
+ args.mode,
)
@@ -285,22 +285,15 @@ def _build_sql_subparser(
"--branch", action=EnvVarAction, env_var="LOOKER_GIT_BRANCH", required=True
)
subparser.add_argument("--explores", nargs="+", default=["*.*"])
- subparser.add_argument("--batch", action="store_true")
+ subparser.add_argument(
+ "--mode", choices=["batch", "single", "hybrid"], default="batch"
+ )
def connect(
base_url: str, client_id: str, client_secret: str, port: int, api_version: float
) -> None:
- """Tests the connection and credentials for the Looker API.
-
- Args:
- base_url: Base URL for the Looker instance, e.g. https://mycompany.looker.com.
- client_id: Looker API client ID.
- client_secret: Looker API client secret.
- port: Desired API port to use for requests.
- api_version: Desired API version to use for requests.
-
- """
+ """Tests the connection and credentials for the Looker API."""
LookerClient(base_url, client_id, client_secret, port, api_version)
@@ -313,30 +306,13 @@ def sql(
client_secret,
port,
api_version,
- batch,
+ mode,
) -> None:
- """Runs and validates the SQL for each selected LookML dimension.
-
- Args:
- project: Name of the Looker project to use.
- branch: Name of the Git branch to check out.
- explores: List of selector strings in 'model_name.explore_name' format.
- The '*' wildcard selects all models or explores. For instance,
- 'model_name.*' would select all explores in the 'model_name' model.
- base_url: Base URL for the Looker instance, e.g. https://mycompany.looker.com.
- client_id: Looker API client ID.
- client_secret: Looker API client secret.
- port: Desired API port to use for requests.
- api_version: Desired API version to use for requests.
- batch: When true, runs one query per explore (using all dimensions). When
- false, runs one query per dimension. Batch mode increases query speed
- but can only return the first error encountered for each dimension.
-
- """
+ """Runs and validates the SQL for each selected LookML dimension."""
runner = Runner(
base_url, project, branch, client_id, client_secret, port, api_version
)
- errors = runner.validate_sql(explores, batch)
+ errors = runner.validate_sql(explores, mode)
if errors:
for error in sorted(errors, key=lambda x: x["path"]):
printer.print_sql_error(error)
diff --git a/spectacles/lookml.py b/spectacles/lookml.py
index 16c1200..aef3450 100644
--- a/spectacles/lookml.py
+++ b/spectacles/lookml.py
@@ -9,11 +9,12 @@ class LookMlObject:
class Dimension(LookMlObject):
- def __init__(self, name: str, type: str, sql: str, url: str):
+ def __init__(self, name: str, type: str, sql: str, url: Optional[str]):
self.name = name
self.type = type
self.sql = sql
self.url = url
+ self.queried: bool = False
self.error: Optional[SqlError] = None
if re.search(r"spectacles\s*:\s*ignore", sql, re.IGNORECASE):
self.ignore = True
@@ -39,7 +40,7 @@ class Dimension(LookMlObject):
@property
def errored(self):
- return bool(self.error)
+ return bool(self.error) if self.queried else None
@errored.setter
def errored(self, value):
@@ -62,6 +63,7 @@ class Explore(LookMlObject):
def __init__(self, name: str, dimensions: List[Dimension] = None):
self.name = name
self.dimensions = [] if dimensions is None else dimensions
+ self.queried: bool = False
self.error: Optional[SqlError] = None
def __eq__(self, other):
@@ -72,9 +74,12 @@ class Explore(LookMlObject):
@property
def errored(self):
- return bool(self.error) or any(
- dimensions.errored for dimensions in self.dimensions
- )
+ if self.queried:
+ return bool(self.error) or any(
+ dimension.errored for dimension in self.dimensions
+ )
+ else:
+ return None
@errored.setter
def errored(self, value: bool):
@@ -83,6 +88,17 @@ class Explore(LookMlObject):
for dimensions in self.dimensions:
dimensions.errored = value
+ @property
+ def queried(self):
+ return any(dimension.queried for dimension in self.dimensions)
+
+ @queried.setter
+ def queried(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("Value for queried must be boolean.")
+ for dimensions in self.dimensions:
+ dimensions.queried = value
+
def get_errored_dimensions(self):
for dimension in self.dimensions:
if dimension.errored:
@@ -115,7 +131,10 @@ class Model(LookMlObject):
@property
def errored(self):
- return any(explore.errored for explore in self.explores)
+ if self.queried:
+ return any(explore.errored for explore in self.explores)
+ else:
+ return None
@errored.setter
def errored(self, value: bool):
@@ -124,6 +143,17 @@ class Model(LookMlObject):
for explore in self.explores:
explore.errored = value
+ @property
+ def queried(self):
+ return any(explore.queried for explore in self.explores)
+
+ @queried.setter
+ def queried(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("Value for queried must be boolean.")
+ for explore in self.explores:
+ explore.queried = value
+
def get_errored_explores(self):
for explore in self.explores:
if explore.errored:
@@ -150,7 +180,10 @@ class Project(LookMlObject):
@property
def errored(self):
- return any(model.errored for model in self.models)
+ if self.queried:
+ return any(model.errored for model in self.models)
+ else:
+ return None
@errored.setter
def errored(self, value: bool):
@@ -159,6 +192,17 @@ class Project(LookMlObject):
for model in self.models:
model.errored = value
+ @property
+ def queried(self):
+ return any(model.queried for model in self.models)
+
+ @queried.setter
+ def queried(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("Value for queried must be boolean.")
+ for model in self.models:
+ model.queried = value
+
def get_errored_models(self):
for model in self.models:
if model.errored:
diff --git a/spectacles/runner.py b/spectacles/runner.py
index 6699a47..8042bcb 100644
--- a/spectacles/runner.py
+++ b/spectacles/runner.py
@@ -36,8 +36,8 @@ class Runner:
)
self.client.update_session(project, branch)
- def validate_sql(self, selectors: List[str], batch: bool = False) -> List[dict]:
+ def validate_sql(self, selectors: List[str], mode: str = "batch") -> List[dict]:
sql_validator = SqlValidator(self.client, self.project)
sql_validator.build_project(selectors)
- errors = sql_validator.validate(batch)
+ errors = sql_validator.validate(mode)
return [vars(error) for error in errors]
diff --git a/spectacles/validators.py b/spectacles/validators.py
index f56aa11..53033a8 100644
--- a/spectacles/validators.py
+++ b/spectacles/validators.py
@@ -159,7 +159,7 @@ class SqlValidator(Validator):
self.project.models = selected_models
- def validate(self, batch: bool = False) -> List[SqlError]:
+ def validate(self, mode: str = "batch") -> List[SqlError]:
"""Queries selected explores and returns any errors.
Args:
@@ -175,22 +175,42 @@ class SqlValidator(Validator):
printer.print_header(
f"Begin testing {explore_count} "
f"{'explore' if explore_count == 1 else 'explores'} "
- f"[{'batch' if batch else 'single-dimension'} mode]"
+ f"[{mode} mode]"
)
- loop = asyncio.get_event_loop()
+ errors = self._query(mode)
+ if mode == "hybrid":
+ errors = self._query(mode)
+
+ for model in sorted(self.project.models, key=lambda x: x.name):
+ for explore in sorted(model.explores, key=lambda x: x.name):
+ if explore.errored:
+ logger.info(
+ f"✗ {printer.red(model.name + '.' + explore.name)} failed"
+ )
+ else:
+ logger.info(
+ f"✓ {printer.green(model.name + '.' + explore.name)} passed"
+ )
+
+ return errors
+
+ def _query(self, mode: str = "batch") -> List[SqlError]:
+ loop = asyncio.new_event_loop()
session = aiohttp.ClientSession(
loop=loop, headers=self.client.session.headers, timeout=self.timeout
)
tasks = []
for model in self.project.models:
for explore in model.explores:
- if batch:
+ if mode == "batch" or (mode == "hybrid" and not explore.queried):
+ logger.debug("Querying one explore at at time")
task = loop.create_task(
self._query_explore(session, model, explore)
)
tasks.append(task)
- else:
+ elif mode == "single" or (mode == "hybrid" and explore.errored):
+ logger.debug("Querying one dimension at at time")
for dimension in explore.dimensions:
task = loop.create_task(
self._query_dimension(session, model, explore, dimension)
@@ -219,19 +239,38 @@ class SqlValidator(Validator):
if tasks_to_check or query_task_ids:
time.sleep(0.5)
- for model in sorted(self.project.models, key=lambda x: x.name):
- for explore in sorted(model.explores, key=lambda x: x.name):
- if explore.errored:
- logger.info(
- f"✗ {printer.red(model.name + '.' + explore.name)} failed"
- )
- else:
- logger.info(
- f"✓ {printer.green(model.name + '.' + explore.name)} passed"
- )
-
return errors
+ @staticmethod
+ def _extract_error_details(query_result: dict) -> dict:
+ data = query_result["data"]
+ if isinstance(data, dict):
+ errors = data.get("errors") or [data.get("error")]
+ first_error = errors[0]
+ message = first_error["message_details"]
+ if not isinstance(message, str):
+ raise TypeError(
+ "Unexpected message type. Expected a str, "
+ f"received type {type(message)}: {message}"
+ )
+ sql = data["sql"]
+ if first_error.get("sql_error_loc"):
+ line_number = first_error["sql_error_loc"]["line"]
+ else:
+ line_number = None
+ elif isinstance(data, list):
+ message = data[0]
+ line_number = None
+ sql = None
+ else:
+ raise TypeError(
+ "Unexpected error response type. "
+ "Expected a dict or a list, "
+ f"received type {type(data)}: {data}"
+ )
+
+ return {"message": message, "sql": sql, "line_number": line_number}
+
def _get_query_results(
self, query_task_ids: List[str]
) -> Tuple[List[str], List[SqlError]]:
@@ -245,49 +284,33 @@ class SqlValidator(Validator):
if query_status in ("running", "added", "expired"):
still_running.append(query_task_id)
- elif query_status == "complete":
- pass
- elif query_status == "error":
- response = query_result["data"]
- if isinstance(response, dict):
- response_error = response["errors"][0]
- message = response_error["message_details"]
- if not isinstance(message, str):
- raise TypeError(
- "Unexpected message type. Expected a str, "
- f"received type {type(message)}: {message}"
- )
- sql = response["sql"]
- if response_error.get("sql_error_loc"):
- line_number = response_error["sql_error_loc"]["line"]
- else:
- line_number = None
- elif isinstance(response, list):
- message = response[0]
- line_number = None
- sql = None
- else:
- raise TypeError(
- f"Unexpected error response type. Expected a dict or a list, "
- f"received type {type(response)}: {response}"
- )
-
+ continue
+ elif query_status in ("complete", "error"):
lookml_object = self.query_tasks[query_task_id]
- error = SqlError(
- path=lookml_object.name,
- message=message,
- sql=sql,
- line_number=line_number,
- url=getattr(lookml_object, "url", None),
- )
- lookml_object.error = error
- errors.append(error)
+ lookml_object.queried = True
else:
raise SpectaclesException(
f'Unexpected query result status "{query_status}" '
"returned by the Looker API"
)
+ if query_status == "error":
+ try:
+ details = self._extract_error_details(query_result)
+ except (KeyError, TypeError, IndexError) as error:
+ raise SpectaclesException(
+ "Encountered an unexpected API query result format, "
+ "unable to extract error details. "
+ f"The query result was: {query_result}"
+ ) from error
+ sql_error = SqlError(
+ path=lookml_object.name,
+ url=getattr(lookml_object, "url", None),
+ **details,
+ )
+ lookml_object.error = sql_error
+ errors.append(sql_error)
+
return still_running, errors
async def _query_explore(
|
spectacles-ci/spectacles
|
54491008f20c6c68c7c6f4fae64a8596c83abb70
|
diff --git a/tests/test_sql_validator.py b/tests/test_sql_validator.py
index 958ca3a..7acd5c9 100644
--- a/tests/test_sql_validator.py
+++ b/tests/test_sql_validator.py
@@ -5,6 +5,7 @@ import pytest
from spectacles.lookml import Project, Model, Explore, Dimension
from spectacles.client import LookerClient
from spectacles.validators import SqlValidator
+from spectacles.exceptions import SpectaclesException
TEST_BASE_URL = "https://test.looker.com"
TEST_CLIENT_ID = "test_client_id"
@@ -90,7 +91,11 @@ def test_get_query_results_task_running(mock_get_query_task_multi_results, valid
@patch("spectacles.client.LookerClient.get_query_task_multi_results")
-def test_get_query_results_task_complete(mock_get_query_task_multi_results, validator):
+def test_get_query_results_task_complete(
+ mock_get_query_task_multi_results, validator, project
+):
+ lookml_object = project.models[0].explores[0]
+ validator.query_tasks = {"query_task_a": lookml_object}
mock_response = {"status": "complete"}
mock_get_query_task_multi_results.return_value = {"query_task_a": mock_response}
still_running, errors = validator._get_query_results(["query_task_a"])
@@ -136,11 +141,13 @@ def test_get_query_results_task_error_list(
@patch("spectacles.client.LookerClient.get_query_task_multi_results")
def test_get_query_results_task_error_other(
- mock_get_query_task_multi_results, validator
+ mock_get_query_task_multi_results, validator, project
):
+ lookml_object = project.models[0].explores[0]
+ validator.query_tasks = {"query_task_a": lookml_object}
mock_response = {"status": "error", "data": "some string"}
mock_get_query_task_multi_results.return_value = {"query_task_a": mock_response}
- with pytest.raises(TypeError):
+ with pytest.raises(SpectaclesException):
still_running, errors = validator._get_query_results(["query_task_a"])
@@ -157,5 +164,5 @@ def test_get_query_results_non_str_message_details(
"data": {"errors": [{"message_details": mock_message}], "sql": mock_sql},
}
mock_get_query_task_multi_results.return_value = {"query_task_a": mock_response}
- with pytest.raises(TypeError):
+ with pytest.raises(SpectaclesException):
still_running, errors = validator._get_query_results(["query_task_a"])
|
Possible option of batch + single dimension mode
We want to try to make runs as efficient as possible and quickly drill down into the errors.
_In theory_, explore mode is fastest because it only runs one query per explore. However, it lacks the granularity of the single dimension mode to find all errors.
We should explore an option where spectacles runs in explore mode first to identify all failing explores and then runs in single dimension mode only on those explores. This _could_ be faster.
|
0.0
|
54491008f20c6c68c7c6f4fae64a8596c83abb70
|
[
"tests/test_sql_validator.py::test_get_query_results_task_error_other",
"tests/test_sql_validator.py::test_get_query_results_non_str_message_details"
] |
[
"tests/test_sql_validator.py::test_build_project",
"tests/test_sql_validator.py::test_get_query_results_task_running",
"tests/test_sql_validator.py::test_get_query_results_task_complete",
"tests/test_sql_validator.py::test_get_query_results_task_error_dict",
"tests/test_sql_validator.py::test_get_query_results_task_error_list"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-31 03:47:37+00:00
|
mit
| 5,645 |
|
spencerahill__aospy-232
|
diff --git a/aospy/calc.py b/aospy/calc.py
index aaabe53..1591ba2 100644
--- a/aospy/calc.py
+++ b/aospy/calc.py
@@ -524,7 +524,7 @@ class Calc(object):
**{reg.name + '_pressure': coord}
)
reg_dat.update(**{reg.name: data_out})
- return OrderedDict(sorted(reg_dat.items(), key=lambda t: t[0]))
+ return xr.Dataset(reg_dat)
def _apply_all_time_reductions(self, full_ts, monthly_ts, eddy_ts):
"""Apply all requested time reductions to the data."""
@@ -587,6 +587,9 @@ class Calc(object):
reduced = self._apply_all_time_reductions(full, monthly, eddy)
logging.info("Writing desired gridded outputs to disk.")
for dtype_time, data in reduced.items():
+ data = _add_metadata_as_attrs(data, self.var.units,
+ self.var.description,
+ self.dtype_out_vert)
self.save(data, dtype_time, dtype_out_vert=self.dtype_out_vert,
save_files=True, write_to_tar=write_to_tar)
return self
@@ -601,15 +604,13 @@ class Calc(object):
reg_data = xr.open_dataset(path)
except (EOFError, RuntimeError, IOError):
reg_data = xr.Dataset()
- # Add the new data to the dictionary or Dataset.
- # Same method works for both.
reg_data.update(data)
data_out = reg_data
else:
data_out = data
if isinstance(data_out, xr.DataArray):
data_out = xr.Dataset({self.name: data_out})
- data_out.to_netcdf(path, engine='scipy')
+ data_out.to_netcdf(path, engine='netcdf4', format='NETCDF3_64BIT')
def _write_to_tar(self, dtype_out_time):
"""Add the data to the tar file in tar_out_direc."""
@@ -767,3 +768,25 @@ class Calc(object):
if plot_units:
data = self.var.to_plot_units(data, dtype_vert=dtype_out_vert)
return data
+
+def _add_metadata_as_attrs(data, units, description, dtype_out_vert):
+ """Add metadata attributes to Dataset or DataArray"""
+ if isinstance(data, xr.DataArray):
+ return _add_metadata_as_attrs_da(data, units, description,
+ dtype_out_vert)
+ else:
+ for name, arr in data.data_vars.items():
+ _add_metadata_as_attrs_da(arr, units, description,
+ dtype_out_vert)
+ return data
+
+def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
+ """Add metadata attributes to DataArray"""
+ if dtype_out_vert == 'vert_int':
+ if units != '':
+ units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
+ else:
+ units = '(vertical integral of quantity with unspecified units)'
+ data.attrs['units'] = units
+ data.attrs['description'] = description
+ return data
diff --git a/docs/examples.rst b/docs/examples.rst
index 8045770..a1759a0 100644
--- a/docs/examples.rst
+++ b/docs/examples.rst
@@ -395,10 +395,18 @@ Each :py:class:`aospy.Calc` object includes the paths to the output
and the results of each output type
-.. ipython:: pythoon
+.. ipython:: python
calcs[0].data_out
+.. note::
+
+ Notice that the variable's name and description have been copied
+ to the resulting Dataset (and hence also to the netCDF file saved
+ to disk). This enables you to better understand what the physical
+ quantity is, even if you don't have the original ``Var`` definition
+ on hand.
+
.. note::
You may have noticed that ``subset_...`` and ``raw_...``
diff --git a/docs/whats-new.rst b/docs/whats-new.rst
index b93abb0..b4eb019 100644
--- a/docs/whats-new.rst
+++ b/docs/whats-new.rst
@@ -22,12 +22,15 @@ Breaking Changes
Documentation
~~~~~~~~~~~~~
-Corrected link to documentation badge on repository main page (:pull:213). By DaCoEx <https://github.com/dacoex>_.
+Corrected link to documentation badge on repository main page
+(:pull:213). By DaCoEx <https://github.com/dacoex>_.
-=======
Enhancements
~~~~~~~~~~~~
+- Add units and description from ``Var`` objects to output netcdf
+ files (closes :issue:`201` via :pull:`232`). By `Micah Kim
+ <https://github.com/micahkim23>`_.
- Remove potentially confusing attributes from example netcdf files.
(closes :issue:`214` via :pull:`216`). By `Micah Kim
<https://github.com/micahkim23>`_.
@@ -37,13 +40,18 @@ Bug Fixes
- Cast input DataArrays with datatype ``np.float32`` to ``np.float64``
as a workaround for incorrectly computed means on float32 arrays in
- bottleneck (see
- `pydata/xarray#1346 <https://github.com/pydata/xarray/issues/1346>`_).
- If one would like to disable this behavior (i.e. restore the original
- behavior before this fix), one can set the ``upcast_float32`` keyword
- argument in their DataLoaders to ``False``.
- Fixes :issue:`217` via :pull:`218`. By `Spencer Clark
+ bottleneck (see `pydata/xarray#1346
+ <https://github.com/pydata/xarray/issues/1346>`_). If one would
+ like to disable this behavior (i.e. restore the original behavior
+ before this fix), one can set the ``upcast_float32`` keyword
+ argument in their DataLoaders to ``False``. Fixes :issue:`217` via
+ :pull:`218`. By `Spencer Clark
<https://github.com/spencerkclark>`_.
+- Switch from using ``scipy`` to ``netcdf4`` as the engine when
+ writing to netCDF files to avoid bugs when using ``libnetcdf``
+ version 4.5.0 (:pull:`235`). By `Spencer Hill
+ <https://github.com/spencerahill>`_.
+
Testing
~~~~~~~
@@ -101,8 +109,9 @@ Enhancements
Dependencies
~~~~~~~~~~~~
-- ``multiprocess`` is no longer required for submitting ``aospy`` calculations
- in parallel (see discussion in :issue:`169` and pull request :pull:`172`).
+- ``multiprocess`` is no longer required for submitting ``aospy``
+ calculations in parallel (see discussion in :issue:`169` and pull
+ request :pull:`172`).
- ``aospy`` now requires an installation of ``dask`` with version
greater than or equal to 0.14 (see discussion in pull request
:pull:`172`).
@@ -129,13 +138,13 @@ Bug Fixes
included data from outside the Timestamp-valid range (fixed in
:pull:`189`). By
`Spencer Clark <https://github.com/spencerkclark>`_.
-- Toggle the ``mask_and_scale`` option to ``True`` when reading in netCDF files
- to enable missing values encoded as floats to be converted to NaN's
- (fixes :issue:`190` via :pull:`192`). By
+- Toggle the ``mask_and_scale`` option to ``True`` when reading in
+ netCDF files to enable missing values encoded as floats to be
+ converted to NaN's (fixes :issue:`190` via :pull:`192`). By
`Spencer Clark <https://github.com/spencerkclark>`_.
-- Force regional calculations to mask gridcell weights where the loaded
- datapoints were invalid instead of just masking points outside the desired
- region (fixes :issue:`190` via :pull:`192`). By
+- Force regional calculations to mask gridcell weights where the
+ loaded datapoints were invalid instead of just masking points
+ outside the desired region (fixes :issue:`190` via :pull:`192`). By
`Spencer Clark <https://github.com/spencerkclark>`_.
- Retain original input data's mask during gridpoint-by-gridpoint
temporal averages (fixes :issue:`193` via :pull:`196`). By `Spencer
|
spencerahill/aospy
|
2ef0b9a90a3752db229d51fb531a5387801dcd41
|
diff --git a/aospy/test/test_calc_basic.py b/aospy/test/test_calc_basic.py
index 3cd2311..b2fd4d3 100755
--- a/aospy/test/test_calc_basic.py
+++ b/aospy/test/test_calc_basic.py
@@ -4,13 +4,35 @@ import datetime
from os.path import isfile
import shutil
import unittest
+import pytest
-from aospy.calc import Calc, CalcInterface
+import xarray as xr
+
+from aospy.calc import Calc, CalcInterface, _add_metadata_as_attrs
from .data.objects.examples import (
example_proj, example_model, example_run, condensation_rain,
precip, sphum, globe, sahel
)
+def _test_output_attrs(calc, dtype_out):
+ data = xr.open_dataset(calc.path_out[dtype_out])
+ expected_units = calc.var.units
+ if calc.dtype_out_vert == 'vert_int':
+ if expected_units != '':
+ expected_units = ("(vertical integral of {0}):"
+ " {0} m)").format(expected_units)
+ else:
+ expected_units = ("(vertical integral of quantity"
+ " with unspecified units)")
+ expected_description = calc.var.description
+ for name, arr in data.data_vars.items():
+ assert expected_units == arr.attrs['units']
+ assert expected_description == arr.attrs['description']
+
+def _test_files_and_attrs(calc, dtype_out):
+ assert isfile(calc.path_out[dtype_out])
+ assert isfile(calc.path_tar_out)
+ _test_output_attrs(calc, dtype_out)
class TestCalcBasic(unittest.TestCase):
def setUp(self):
@@ -35,8 +57,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['av'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'av')
def test_annual_ts(self):
calc_int = CalcInterface(intvl_out='ann',
@@ -44,8 +65,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['ts'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'ts')
def test_seasonal_mean(self):
calc_int = CalcInterface(intvl_out='djf',
@@ -53,8 +73,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['av'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'av')
def test_seasonal_ts(self):
calc_int = CalcInterface(intvl_out='djf',
@@ -62,8 +81,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['ts'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'ts')
def test_monthly_mean(self):
calc_int = CalcInterface(intvl_out=1,
@@ -71,8 +89,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['av'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'av')
def test_monthly_ts(self):
calc_int = CalcInterface(intvl_out=1,
@@ -80,8 +97,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['ts'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'ts')
def test_simple_reg_av(self):
calc_int = CalcInterface(intvl_out='ann',
@@ -90,8 +106,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['reg.av'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'reg.av')
def test_simple_reg_ts(self):
calc_int = CalcInterface(intvl_out='ann',
@@ -100,8 +115,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['reg.ts'])
- assert isfile(calc.path_tar_out)
+ _test_files_and_attrs(calc, 'reg.ts')
def test_complex_reg_av(self):
calc_int = CalcInterface(intvl_out='ann',
@@ -110,9 +124,7 @@ class TestCalcBasic(unittest.TestCase):
**self.test_params)
calc = Calc(calc_int)
calc.compute()
- assert isfile(calc.path_out['reg.av'])
- assert isfile(calc.path_tar_out)
-
+ _test_files_and_attrs(calc, 'reg.av')
class TestCalcComposite(TestCalcBasic):
def setUp(self):
@@ -143,5 +155,37 @@ class TestCalc3D(TestCalcBasic):
'dtype_out_vert': 'vert_int'
}
[email protected](
+ ('units', 'description', 'dtype_out_vert', 'expected_units',
+ 'expected_description'),
+ [('', '', None, '', ''),
+ ('m', '', None, 'm', ''),
+ ('', 'rain', None, '', 'rain'),
+ ('m', 'rain', None, 'm', 'rain'),
+ ('', '', 'vert_av', '', ''),
+ ('m', '', 'vert_av', 'm', ''),
+ ('', 'rain', 'vert_av', '', 'rain'),
+ ('m', 'rain', 'vert_av', 'm', 'rain'),
+ ('', '', 'vert_int',
+ '(vertical integral of quantity with unspecified units)', ''),
+ ('m', '', 'vert_int',
+ '(vertical integral of m): m kg m^-2)', ''),
+ ('', 'rain', 'vert_int',
+ '(vertical integral of quantity with unspecified units)', 'rain'),
+ ('m', 'rain', 'vert_int',
+ '(vertical integral of m): m kg m^-2)', 'rain')]
+)
+def test_attrs(units, description, dtype_out_vert, expected_units,
+ expected_description):
+ da = xr.DataArray(None)
+ ds = xr.Dataset({'bar': 'foo', 'boo': 'baz'})
+ da = _add_metadata_as_attrs(da, units, description, dtype_out_vert)
+ ds = _add_metadata_as_attrs(ds, units, description, dtype_out_vert)
+ assert expected_units == da.attrs['units']
+ assert expected_description == da.attrs['description']
+ for name, arr in ds.data_vars.items():
+ assert expected_units == arr.attrs['units']
+ assert expected_description == arr.attrs['description']
+
if __name__ == '__main__':
unittest.main()
|
Adding units/description to netcdf files
Currently, the descriptions/units in Var objects are not saved in the output netcdf files. It would be nice if this was the case.
|
0.0
|
2ef0b9a90a3752db229d51fb531a5387801dcd41
|
[
"aospy/test/test_calc_basic.py::test_attrs[--None--]",
"aospy/test/test_calc_basic.py::test_attrs[m--None-m-]",
"aospy/test/test_calc_basic.py::test_attrs[-rain-None--rain]",
"aospy/test/test_calc_basic.py::test_attrs[m-rain-None-m-rain]",
"aospy/test/test_calc_basic.py::test_attrs[--vert_av--]",
"aospy/test/test_calc_basic.py::test_attrs[m--vert_av-m-]",
"aospy/test/test_calc_basic.py::test_attrs[-rain-vert_av--rain]",
"aospy/test/test_calc_basic.py::test_attrs[m-rain-vert_av-m-rain]",
"aospy/test/test_calc_basic.py::test_attrs[--vert_int-(vertical",
"aospy/test/test_calc_basic.py::test_attrs[m--vert_int-(vertical",
"aospy/test/test_calc_basic.py::test_attrs[-rain-vert_int-(vertical",
"aospy/test/test_calc_basic.py::test_attrs[m-rain-vert_int-(vertical"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-11-12 02:52:30+00:00
|
apache-2.0
| 5,646 |
|
spencerahill__aospy-269
|
diff --git a/.gitignore b/.gitignore
index 86f00e0..b2bbf4d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -62,6 +62,7 @@ htmlcov/
nosetests.xml
coverage.xml
*,cover
+.pytest_cache/
# Translations
*.mo
diff --git a/aospy/data_loader.py b/aospy/data_loader.py
index 4bf057b..3962eb9 100644
--- a/aospy/data_loader.py
+++ b/aospy/data_loader.py
@@ -6,7 +6,12 @@ import warnings
import numpy as np
import xarray as xr
-from .internal_names import ETA_STR, GRID_ATTRS, TIME_STR, TIME_BOUNDS_STR
+from .internal_names import (
+ ETA_STR,
+ GRID_ATTRS,
+ TIME_STR,
+ TIME_BOUNDS_STR,
+)
from .utils import times, io
@@ -63,8 +68,8 @@ def grid_attrs_to_aospy_names(data):
Data returned with coordinates consistent with aospy
conventions
"""
+ dims_and_vars = set(data.variables).union(set(data.dims))
for name_int, names_ext in GRID_ATTRS.items():
- dims_and_vars = set(data.variables).union(set(data.dims))
data_coord_name = set(names_ext).intersection(dims_and_vars)
if data_coord_name:
data = data.rename({data_coord_name.pop(): name_int})
@@ -174,7 +179,7 @@ def _prep_time_data(ds):
Dataset, int, int
The processed Dataset and minimum and maximum years in the loaded data
"""
- ds = times.ensure_time_as_dim(ds)
+ ds = times.ensure_time_as_index(ds)
ds, min_year, max_year = times.numpy_datetime_workaround_encode_cf(ds)
if TIME_BOUNDS_STR in ds:
ds = times.ensure_time_avg_has_cf_metadata(ds)
@@ -275,6 +280,7 @@ class DataLoader(object):
coords=self.coords, start_date=start_date, end_date=end_date,
time_offset=time_offset, **DataAttrs
)
+
ds, min_year, max_year = _prep_time_data(ds)
ds = set_grid_attrs_as_coords(ds)
da = _sel_var(ds, var, self.upcast_float32)
diff --git a/aospy/utils/times.py b/aospy/utils/times.py
index 688417f..08b0c89 100644
--- a/aospy/utils/times.py
+++ b/aospy/utils/times.py
@@ -540,13 +540,14 @@ def assert_matching_time_coord(arr1, arr2):
raise ValueError(message.format(arr1[TIME_STR], arr2[TIME_STR]))
-def ensure_time_as_dim(ds):
- """Ensures that time is an indexable dimension on relevant quantites
+def ensure_time_as_index(ds):
+ """Ensures that time is an indexed coordinate on relevant quantites.
- In xarray, scalar coordinates cannot be indexed. We rely
- on indexing in the time dimension throughout the code; therefore
- we need this helper method to (if needed) convert a scalar time coordinate
- to a dimension.
+ Sometimes when the data we load from disk has only one timestep, the
+ indexing of time-defined quantities in the resulting xarray.Dataset gets
+ messed up, in that the time bounds array and data variables don't get
+ indexed by time, even though they should. Therefore, we need this helper
+ function to (possibly) correct this.
Note that this must be applied before CF-conventions are decoded; otherwise
it casts ``np.datetime64[ns]`` as ``int`` values.
@@ -559,38 +560,14 @@ def ensure_time_as_dim(ds):
Returns
-------
Dataset
- """
- if TIME_STR not in ds.dims:
- time = convert_scalar_to_indexable_coord(ds[TIME_STR])
- ds = ds.set_coords(TIME_STR)
- for name in ds.variables:
- if ((name not in GRID_ATTRS_NO_TIMES) and
- (name != TIME_STR)):
- da = ds[name]
- da, _ = xr.broadcast(da, time)
- da[TIME_STR] = time
- ds[name] = da
- return ds
-
-def convert_scalar_to_indexable_coord(scalar_da):
- """Convert a scalar coordinate to an indexable one.
-
- In xarray, scalar coordinates cannot be indexed. This converts
- a scalar coordinate-containing ``DataArray`` to one that can
- be indexed using ``da.sel`` and ``da.isel``.
-
- Parameters
- ----------
- scalar_da : DataArray
- Must contain a scalar coordinate
-
- Returns
- -------
- DataArray
"""
- data = [scalar_da.values.item()]
- da = xr.DataArray(data, coords=[data], dims=[scalar_da.name],
- name=scalar_da.name)
- da.attrs = scalar_da.attrs
- return da
+ time_indexed_coords = {TIME_WEIGHTS_STR, TIME_BOUNDS_STR}
+ time_indexed_vars = set(ds.data_vars).union(time_indexed_coords)
+ time_indexed_vars = time_indexed_vars.intersection(ds.variables)
+ for name in time_indexed_vars:
+ if TIME_STR not in ds[name].indexes:
+ da = ds[name].expand_dims(TIME_STR)
+ da[TIME_STR] = ds[TIME_STR]
+ ds[name] = da
+ return ds
diff --git a/docs/whats-new.rst b/docs/whats-new.rst
index 7996ff6..6ce763e 100644
--- a/docs/whats-new.rst
+++ b/docs/whats-new.rst
@@ -25,6 +25,10 @@ Breaking Changes
object, pass it directly the parameters that previously would have
been passed to ``CalcInterface`` (fixes :issue:`249` via
:pull:`250`). By `Spencer Hill <https://github.com/spencerahill>`_.
+- Deprecate ``utils.times.convert_scalar_to_indexable_coord``, since
+ as of xarray version 0.10.3 release, the functionality is no longer
+ necessary (fixes :issue:`268` via :pull:`269`. By `Spencer Hill
+ <https://github.com/spencerahill>`_.
Documentation
~~~~~~~~~~~~~
@@ -110,8 +114,9 @@ Dependencies
- ``aospy`` now requires a minimum version of ``distributed`` of
1.17.1 (fixes :issue:`210` via :pull:`211`).
-- ``aospy`` now requires a minimum version of ``xarray`` of 0.10.0.
- See discussion in :issue:`199` and :pull:`240` for more details.
+- ``aospy`` now requires a minimum version of ``xarray`` of 0.10.3.
+ See discussion in :issue:`199`, :pull:`240`, :issue:`268`, and
+ :pull:`269` for more details.
.. _whats-new.0.2:
diff --git a/setup.py b/setup.py
index b237c6e..bb659f5 100644
--- a/setup.py
+++ b/setup.py
@@ -33,7 +33,7 @@ setuptools.setup(
'toolz >= 0.7.2',
'dask >= 0.14',
'distributed >= 1.17.1',
- 'xarray >= 0.10.0',
+ 'xarray >= 0.10.3',
'cloudpickle >= 0.2.1'],
tests_require=['pytest >= 2.7.1',
'pytest-catchlog >= 1.0'],
|
spencerahill/aospy
|
7e3e5becb6920c3c5987a6dfd0a398c85d918ae4
|
diff --git a/aospy/test/test_utils_times.py b/aospy/test/test_utils_times.py
index 5e287fd..00b4216 100755
--- a/aospy/test/test_utils_times.py
+++ b/aospy/test/test_utils_times.py
@@ -30,8 +30,7 @@ from aospy.utils.times import (
_assert_has_data_for_time,
add_uniform_time_weights,
assert_matching_time_coord,
- ensure_time_as_dim,
- convert_scalar_to_indexable_coord,
+ ensure_time_as_index,
sel_time,
yearly_average
)
@@ -433,37 +432,46 @@ def test_assert_matching_time_coord():
assert_matching_time_coord(arr1, arr2)
-def test_ensure_time_as_dim():
- arr = xr.DataArray([3, 4], coords=[[1, 2]], dims=[TIME_STR])
+def test_ensure_time_as_index_no_change():
+ # Already properly indexed, so shouldn't be modified.
+ arr = xr.DataArray([-23, 42.4], coords=[[1, 2]], dims=[TIME_STR])
arr[TIME_STR].attrs['units'] = 'days since 2000-01-01 00:00:00'
arr[TIME_STR].attrs['calendar'] = 'standard'
ds = arr.to_dataset(name='a')
- assert TIME_STR in ds.dims
- assert ds.identical(ensure_time_as_dim(ds))
+ ds.coords[TIME_WEIGHTS_STR] = xr.DataArray(
+ [1, 1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
+ )
+ ds.coords[TIME_BOUNDS_STR] = xr.DataArray(
+ [[0.5, 1.5], [1.5, 2.5]], dims=[TIME_STR, BOUNDS_STR],
+ coords={TIME_STR: arr[TIME_STR]}
+ )
+ xr.testing.assert_identical(ds, ensure_time_as_index(ds))
- scalar_time_in_ds = ds.isel(**{TIME_STR: 0})
- assert TIME_STR not in scalar_time_in_ds.dims
- result = ensure_time_as_dim(scalar_time_in_ds)
- arr = xr.DataArray([3], coords=[[1]], dims=[TIME_STR])
+def test_ensure_time_as_index_with_change():
+ # Time bounds array doesn't index time initially, which gets fixed.
+ arr = xr.DataArray([-93], dims=[TIME_STR], coords={TIME_STR: [3]})
arr[TIME_STR].attrs['units'] = 'days since 2000-01-01 00:00:00'
arr[TIME_STR].attrs['calendar'] = 'standard'
+ ds = arr.to_dataset(name='a')
+ ds.coords[TIME_WEIGHTS_STR] = xr.DataArray(
+ [1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
+ )
+ ds.coords[TIME_BOUNDS_STR] = xr.DataArray(
+ [[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
+ coords={TIME_STR: arr[TIME_STR]}
+ )
+ ds = ds.isel(**{TIME_STR: 0}).expand_dims(TIME_STR)
+ actual = ensure_time_as_index(ds)
expected = arr.to_dataset(name='a')
- xr.testing.assert_identical(result, expected)
-
-
-def test_convert_scalar_to_indexable_coord():
- da = xr.DataArray([3, 4], coords=[[1, 2]], dims=['a'], name='b')
- da['a'].attrs['test'] = 'c'
- scalar_coord = da.isel(a=0)['a']
- assert 'a' not in scalar_coord.dims
-
- indexable_coord = convert_scalar_to_indexable_coord(scalar_coord)
- assert 'a' in indexable_coord.dims
-
- expected = xr.DataArray([1], coords=[[1]], dims=['a'], name='a')
- expected.attrs['test'] = 'c'
- xr.testing.assert_identical(indexable_coord, expected)
+ expected.coords[TIME_WEIGHTS_STR] = xr.DataArray(
+ [1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
+ )
+ expected.coords[TIME_BOUNDS_STR] = xr.DataArray(
+ [[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
+ coords={TIME_STR: arr[TIME_STR]}
+ )
+ xr.testing.assert_identical(actual, expected)
def test_sel_time():
|
Failing test_calc_basic tests after updating xarray from 10.2 to 10.3
Originally noted [here](https://github.com/spencerahill/aospy/pull/266#issuecomment-383776179)
All of the failures are the same error. Note that this one doesn't involve regional averaging, so it's unrelated to what I'm implementing in #266. Here's the traceback of one:
```
$ py.test test_calc_basic.py::TestCalc3D::test_monthly_ts
================================================================== test session starts ==================================================================
platform darwin -- Python 3.6.3, pytest-3.2.3, py-1.5.1, pluggy-0.4.0
rootdir: /Users/shill/Dropbox/py/aospy, inifile: setup.cfg
plugins: catchlog-1.2.2, hypothesis-3.50.2
collected 1 item
test_calc_basic.py F
======================================================================= FAILURES ========================================================================
______________________________________________________________ TestCalc3D.test_monthly_ts _______________________________________________________________
self = <aospy.test.test_calc_basic.TestCalc3D testMethod=test_monthly_ts>
def test_monthly_ts(self):
calc = Calc(intvl_out=1, dtype_out_time='ts', **self.test_params)
> calc.compute()
calc = <aospy.Calc instance: sphum, example_proj, example_model, example_run>
self = <aospy.test.test_calc_basic.TestCalc3D testMethod=test_monthly_ts>
test_calc_basic.py:88:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../calc.py:569: in compute
self.end_date),
../calc.py:415: in _get_all_data
for n, var in enumerate(self.variables)]
../calc.py:415: in <listcomp>
for n, var in enumerate(self.variables)]
../calc.py:367: in _get_input_data
**self.data_loader_attrs)
../data_loader.py:278: in load_variable
ds, min_year, max_year = _prep_time_data(ds)
../data_loader.py:180: in _prep_time_data
ds = times.ensure_time_avg_has_cf_metadata(ds)
../utils/times.py:417: in ensure_time_avg_has_cf_metadata
raw_start_date = ds[TIME_BOUNDS_STR].isel(**{TIME_STR: 0, BOUNDS_STR: 0})
../../../../miniconda3/envs/py36/lib/python3.6/site-packages/xarray/core/dataarray.py:754: in isel
ds = self._to_temp_dataset().isel(drop=drop, **indexers)
../../../../miniconda3/envs/py36/lib/python3.6/site-packages/xarray/core/dataset.py:1391: in isel
indexers_list = self._validate_indexers(indexers)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <xarray.Dataset>
Dimensions: (bounds: 2)
Coordinates:
time_bounds (bounds) float64 dask.array<shape=(2,), ... time_weights float64 ...
Data variables:
<this-array> (bounds) float64 dask.array<shape=(2,), chunksize=(2,)>
indexers = {'bounds': 0, 'time': 0}
def _validate_indexers(self, indexers):
""" Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
"""
from .dataarray import DataArray
invalid = [k for k in indexers if k not in self.dims]
if invalid:
> raise ValueError("dimensions %r do not exist" % invalid)
E ValueError: dimensions ['time'] do not exist
DataArray = <class 'xarray.core.dataarray.DataArray'>
indexers = {'bounds': 0, 'time': 0}
invalid = ['time']
self = <xarray.Dataset>
Dimensions: (bounds: 2)
Coordinates:
time_bounds (bounds) float64 dask.array<shape=(2,), ... time_weights float64 ...
Data variables:
<this-array> (bounds) float64 dask.array<shape=(2,), chunksize=(2,)>
```
|
0.0
|
7e3e5becb6920c3c5987a6dfd0a398c85d918ae4
|
[
"aospy/test/test_utils_times.py::test_apply_time_offset",
"aospy/test/test_utils_times.py::test_ensure_datetime_valid_input",
"aospy/test/test_utils_times.py::test_ensure_datetime_invalid_input",
"aospy/test/test_utils_times.py::test_datetime_or_default",
"aospy/test/test_utils_times.py::test_numpy_datetime_range_workaround",
"aospy/test/test_utils_times.py::test_month_indices",
"aospy/test/test_utils_times.py::test_month_conditional",
"aospy/test/test_utils_times.py::test_extract_months",
"aospy/test/test_utils_times.py::test_extract_months_single_month",
"aospy/test/test_utils_times.py::test_ensure_time_avg_has_cf_metadata",
"aospy/test/test_utils_times.py::test_add_uniform_time_weights",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time",
"aospy/test/test_utils_times.py::test_assert_matching_time_coord",
"aospy/test/test_utils_times.py::test_ensure_time_as_index_no_change",
"aospy/test/test_utils_times.py::test_ensure_time_as_index_with_change",
"aospy/test/test_utils_times.py::test_sel_time",
"aospy/test/test_utils_times.py::test_yearly_average_no_mask",
"aospy/test/test_utils_times.py::test_yearly_average_masked_data",
"aospy/test/test_utils_times.py::test_average_time_bounds"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-25 23:32:59+00:00
|
apache-2.0
| 5,647 |
|
spencerahill__aospy-322
|
diff --git a/aospy/utils/times.py b/aospy/utils/times.py
index beaea13..702e3ec 100644
--- a/aospy/utils/times.py
+++ b/aospy/utils/times.py
@@ -55,8 +55,7 @@ def apply_time_offset(time, years=0, months=0, days=0, hours=0):
freq=None)
"""
return (pd.to_datetime(time.values) +
- pd.tseries.offsets.DateOffset(years=years, months=months,
- days=days, hours=hours))
+ pd.DateOffset(years=years, months=months, days=days, hours=hours))
def average_time_bounds(ds):
@@ -512,12 +511,15 @@ def ensure_time_as_index(ds):
time_indexed_coords = {TIME_WEIGHTS_STR, TIME_BOUNDS_STR}
time_indexed_vars = set(ds.data_vars).union(time_indexed_coords)
time_indexed_vars = time_indexed_vars.intersection(ds.variables)
+ variables_to_replace = {}
for name in time_indexed_vars:
if TIME_STR not in ds[name].indexes:
- da = ds[name].expand_dims(TIME_STR)
- da[TIME_STR] = ds[TIME_STR]
- ds[name] = da
- return ds
+ da = ds[name]
+ if TIME_STR not in da.dims:
+ da = ds[name].expand_dims(TIME_STR)
+ da = da.assign_coords(**{TIME_STR: ds[TIME_STR]})
+ variables_to_replace[name] = da
+ return ds.assign(**variables_to_replace)
def infer_year(date):
|
spencerahill/aospy
|
17d0d7245f745c51303ae5dc923a8e8888552bcb
|
diff --git a/aospy/test/test_utils_times.py b/aospy/test/test_utils_times.py
index ce94760..3fe4bd4 100755
--- a/aospy/test/test_utils_times.py
+++ b/aospy/test/test_utils_times.py
@@ -49,9 +49,10 @@ def test_apply_time_offset():
# test lengths 0, 1, and >1 of input time array
for periods in range(3):
times = pd.date_range(start=start, freq='M', periods=periods)
+ times = pd.to_datetime(times.values) # Workaround for pandas bug
actual = apply_time_offset(xr.DataArray(times), years=years,
months=months, days=days, hours=hours)
- desired = (times + pd.tseries.offsets.DateOffset(
+ desired = (times + pd.DateOffset(
years=years, months=months, days=days, hours=hours
))
assert actual.identical(desired)
@@ -455,6 +456,7 @@ def test_ensure_time_as_index_with_change():
coords={TIME_STR: arr[TIME_STR]}
)
ds = ds.isel(**{TIME_STR: 0}).expand_dims(TIME_STR)
+ initial_ds = ds.copy()
actual = ensure_time_as_index(ds)
expected = arr.to_dataset(name='a')
expected.coords[TIME_WEIGHTS_STR] = xr.DataArray(
@@ -465,6 +467,9 @@ def test_ensure_time_as_index_with_change():
coords={TIME_STR: arr[TIME_STR]}
)
xr.testing.assert_identical(actual, expected)
+ # Make sure input Dataset was not mutated by the call
+ # to ensure_time_as_index
+ xr.testing.assert_identical(ds, initial_ds)
def test_sel_time():
|
New failure in test_apply_time_offset
After reverting to xarray 0.11, c.f. #319, the test suite loads without error but has one failure, which I've pasted below. @spencerkclark, since this seems cftime-related (or adjacent), I'm going to punt this one to you.
```python
test_apply_time_offset ___________________________________________________________________
cls = <class 'pandas.core.arrays.datetimes.DatetimeArray'>
index = <DatetimeArray>
['1898-06-30 00:00:00', '1898-07-30 00:00:00']
Length: 2, dtype: datetime64[ns], freq = <MonthEnd>, kwargs = {}, inferred = None
on_freq = <DatetimeArray>
['1898-06-30 00:00:00', '1898-07-31 00:00:00']
Length: 2, dtype: datetime64[ns]
@classmethod
def _validate_frequency(cls, index, freq, **kwargs):
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
The frequency to validate
"""
if is_period_dtype(cls):
# Frequency validation is not meaningful for Period Array/Index
return None
inferred = index.inferred_freq
if index.size == 0 or inferred == freq.freqstr:
return None
try:
on_freq = cls._generate_range(start=index[0], end=None,
periods=len(index), freq=freq,
**kwargs)
if not np.array_equal(index.asi8, on_freq.asi8):
> raise ValueError
E ValueError
../../pandas/core/arrays/datetimelike.py:884: ValueError
During handling of the above exception, another exception occurred:
def test_apply_time_offset():
start = datetime.datetime(1900, 5, 10)
years, months, days, hours = -2, 1, 7, 3
# test lengths 0, 1, and >1 of input time array
for periods in range(3):
times = pd.date_range(start=start, freq='M', periods=periods)
actual = apply_time_offset(xr.DataArray(times), years=years,
months=months, days=days, hours=hours)
desired = (times + pd.tseries.offsets.DateOffset(
> years=years, months=months, days=days, hours=hours
))
test_utils_times.py:55:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../pandas/core/indexes/datetimelike.py:489: in __add__
result = self._data.__add__(maybe_unwrap_index(other))
../../pandas/core/arrays/datetimelike.py:1190: in __add__
result = self._add_offset(other)
../../pandas/core/arrays/datetimes.py:737: in _add_offset
result = offset.apply_index(values)
pandas/_libs/tslibs/offsets.pyx:116: in pandas._libs.tslibs.offsets.apply_index_wraps.wrapper
???
../../pandas/tseries/offsets.py:278: in apply_index
i = type(i)(shifted, freq=i.freq, dtype=i.dtype)
../../pandas/core/arrays/datetimes.py:351: in __init__
type(self)._validate_frequency(self, freq)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
cls = <class 'pandas.core.arrays.datetimes.DatetimeArray'>
index = <DatetimeArray>
['1898-06-30 00:00:00', '1898-07-30 00:00:00']
Length: 2, dtype: datetime64[ns], freq = <MonthEnd>, kwargs = {}, inferred = None
on_freq = <DatetimeArray>
['1898-06-30 00:00:00', '1898-07-31 00:00:00']
Length: 2, dtype: datetime64[ns]
@classmethod
def _validate_frequency(cls, index, freq, **kwargs):
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
The frequency to validate
"""
if is_period_dtype(cls):
# Frequency validation is not meaningful for Period Array/Index
return None
inferred = index.inferred_freq
if index.size == 0 or inferred == freq.freqstr:
return None
try:
on_freq = cls._generate_range(start=index[0], end=None,
periods=len(index), freq=freq,
**kwargs)
if not np.array_equal(index.asi8, on_freq.asi8):
raise ValueError
except ValueError as e:
if "non-fixed" in str(e):
# non-fixed frequencies are not meaningful for timedelta64;
# we retain that error message
raise e
# GH#11587 the main way this is reached is if the `np.array_equal`
# check above is False. This can also be reached if index[0]
# is `NaT`, in which case the call to `cls._generate_range` will
# raise a ValueError, which we re-raise with a more targeted
# message.
raise ValueError('Inferred frequency {infer} from passed values '
'does not conform to passed frequency {passed}'
> .format(infer=inferred, passed=freq.freqstr))
E ValueError: Inferred frequency None from passed values does not conform to passed frequency M
../../pandas/core/arrays/datetimelike.py:897: ValueError
```
|
0.0
|
17d0d7245f745c51303ae5dc923a8e8888552bcb
|
[
"aospy/test/test_utils_times.py::test_ensure_time_as_index_with_change"
] |
[
"aospy/test/test_utils_times.py::test_apply_time_offset",
"aospy/test/test_utils_times.py::test_monthly_mean_ts_single_month",
"aospy/test/test_utils_times.py::test_monthly_mean_ts_submonthly",
"aospy/test/test_utils_times.py::test_monthly_mean_ts_monthly",
"aospy/test/test_utils_times.py::test_monthly_mean_ts_na",
"aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date0]",
"aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date1]",
"aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date2]",
"aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[2000-01-01]",
"aospy/test/test_utils_times.py::test_ensure_datetime_invalid_input",
"aospy/test/test_utils_times.py::test_datetime_or_default",
"aospy/test/test_utils_times.py::test_month_indices",
"aospy/test/test_utils_times.py::test_month_conditional",
"aospy/test/test_utils_times.py::test_extract_months",
"aospy/test/test_utils_times.py::test_extract_months_single_month",
"aospy/test/test_utils_times.py::test_ensure_time_avg_has_cf_metadata",
"aospy/test/test_utils_times.py::test_add_uniform_time_weights",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[noleap-DatetimeNoLeap]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[365_day-DatetimeNoLeap]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[360_day-Datetime360Day]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[julian-DatetimeJulian]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[all_leap-DatetimeAllLeap]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[366_day-DatetimeAllLeap]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[gregorian-DatetimeGregorian]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[proleptic_gregorian-DatetimeProlepticGregorian]",
"aospy/test/test_utils_times.py::test_assert_has_data_for_time_str_input",
"aospy/test/test_utils_times.py::test_assert_matching_time_coord",
"aospy/test/test_utils_times.py::test_ensure_time_as_index_no_change",
"aospy/test/test_utils_times.py::test_sel_time",
"aospy/test/test_utils_times.py::test_yearly_average_no_mask",
"aospy/test/test_utils_times.py::test_yearly_average_masked_data",
"aospy/test/test_utils_times.py::test_average_time_bounds",
"aospy/test/test_utils_times.py::test_infer_year[date0-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date1-2000]",
"aospy/test/test_utils_times.py::test_infer_year[2000-2000]",
"aospy/test/test_utils_times.py::test_infer_year[2000-01-2000]",
"aospy/test/test_utils_times.py::test_infer_year[2000-01-01-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date5-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date6-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date7-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date8-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date9-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date10-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date11-2000]",
"aospy/test/test_utils_times.py::test_infer_year[date12-2000]",
"aospy/test/test_utils_times.py::test_infer_year_invalid[-0001]",
"aospy/test/test_utils_times.py::test_infer_year_invalid[A001]",
"aospy/test/test_utils_times.py::test_infer_year_invalid[01]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-datetime.datetime]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-np.datetime64]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-str]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-noleap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-365_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-360_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-julian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-all_leap]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-366_day]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-proleptic_gregorian]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-datetime.datetime]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-np.datetime64]",
"aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-str]"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-30 17:43:30+00:00
|
apache-2.0
| 5,648 |
|
sphinx-contrib__matlabdomain-226
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 73861fa..23f5a6b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,3 +1,11 @@
+sphinxcontrib-matlabdomain-0.X.Y (2023-MM-DD)
+==============================================
+
+* Fixed `Issue 225`. Empty ``@classfolder`` would throw an assertion error.
+
+.. _Issue 225: https://github.com/sphinx-contrib/matlabdomain/issues/225
+
+
sphinxcontrib-matlabdomain-0.20.2 (2023-09-15)
==============================================
diff --git a/sphinxcontrib/mat_types.py b/sphinxcontrib/mat_types.py
index b4adfb4..4eb17db 100644
--- a/sphinxcontrib/mat_types.py
+++ b/sphinxcontrib/mat_types.py
@@ -251,6 +251,10 @@ def analyze(app):
# Find the class entity class.
class_entities = [e for e in cf_entity.entities if isinstance(e[1], MatClass)]
func_entities = [e for e in cf_entity.entities if isinstance(e[1], MatFunction)]
+
+ empty_class_folder = not class_entities and not func_entities
+ if empty_class_folder:
+ continue
assert len(class_entities) == 1
cls = class_entities[0][1]
|
sphinx-contrib/matlabdomain
|
b52664cf1b4ab3f9a5e0ab39ebe0d7d8973d548b
|
diff --git a/tests/helper.py b/tests/helper.py
index d1a345b..803d224 100644
--- a/tests/helper.py
+++ b/tests/helper.py
@@ -17,7 +17,7 @@ if sphinx_version_info[0] >= 7 and sphinx_version_info[1] >= 2:
from pathlib import Path
def rootdir(the_file):
- return Path(os.path.dirname(__file__)).absolute()
+ return Path(os.path.dirname(__file__)).resolve().absolute()
else:
from sphinx.testing.path import path as sphinx_path
diff --git a/tests/test_data/@EmptyClassFolder/readme.txt b/tests/test_data/@EmptyClassFolder/readme.txt
new file mode 100644
index 0000000..0cc80f9
--- /dev/null
+++ b/tests/test_data/@EmptyClassFolder/readme.txt
@@ -0,0 +1,1 @@
+Intentionally empty folder. Tests https://github.com/sphinx-contrib/matlabdomain/issues/225
diff --git a/tests/test_matlabify.py b/tests/test_matlabify.py
index 6e14d68..5c0a3bb 100644
--- a/tests/test_matlabify.py
+++ b/tests/test_matlabify.py
@@ -52,6 +52,7 @@ def test_module(mod):
expected_items = {
"+package",
"@ClassFolder",
+ "@EmptyClassFolder",
"Application",
"ClassAbstract",
"ClassExample",
|
Vague error when there is an empty @ClassFolder
Due to some kind of Git quirk, I sometimes end up with empty directories in my MATLAB file tree. They could be class directories, like `@Test`. It turns out that if this is the case, building the documentation fails with a very vague error which I had been scratching my head over for quite some time now:
```
Extension error (sphinxcontrib.matlab):
Handler <function analyze at 0x000002A1322DE340> for event 'builder-inited' threw an exception (exception: )
```
I usually build using `make html` but when running using `sphinx-build` the verbosity is better and I found out that this error is due to the assertion in `mat_types.py:254`:
```
Traceback (most recent call last):
File "C:\...\.venv\Lib\site-packages\sphinx\events.py", line 97, in emit
results.append(listener.handler(self.app, *args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\...\.venv\Lib\site-packages\sphinxcontrib\matlab.py", line 844, in analyze
mat_types.analyze(app)
File "C:\...\.venv\Lib\site-packages\sphinxcontrib\mat_types.py", line 254, in analyze
assert len(class_entities) == 1
AssertionError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\...\.venv\Lib\site-packages\sphinx\cmd\build.py", line 293, in build_main
app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\...\.venv\Lib\site-packages\sphinx\application.py", line 272, in __init__
self._init_builder()
File "C:\...\.venv\Lib\site-packages\sphinx\application.py", line 343, in _init_builder
self.events.emit('builder-inited')
File "C:\...\.venv\Lib\site-packages\sphinx\events.py", line 108, in emit
raise ExtensionError(__("Handler %r for event %r threw an exception") %
sphinx.errors.ExtensionError: Handler <function analyze at 0x000001FBDA819C60> for event 'builder-inited' threw an exception (exception: )
```
I can imagine that others might run into this issue, too, so is it perhaps an idea to handle this situation?
|
0.0
|
b52664cf1b4ab3f9a5e0ab39ebe0d7d8973d548b
|
[
"tests/test_matlabify.py::test_script",
"tests/test_matlabify.py::test_module",
"tests/test_matlabify.py::test_parse_twice",
"tests/test_matlabify.py::test_classes",
"tests/test_matlabify.py::test_abstract_class",
"tests/test_matlabify.py::test_class_method",
"tests/test_matlabify.py::test_submodule_class",
"tests/test_matlabify.py::test_folder_class",
"tests/test_matlabify.py::test_function",
"tests/test_matlabify.py::test_function_getter",
"tests/test_matlabify.py::test_package_function",
"tests/test_matlabify.py::test_class_with_get_method"
] |
[
"tests/test_matlabify.py::test_unknown"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-10 10:02:44+00:00
|
bsd-2-clause
| 5,649 |
|
sphinx-gallery__sphinx-gallery-1005
|
diff --git a/.gitignore b/.gitignore
index 2ca5414..5c35e97 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@
__pycache__/
*.py[cod]
.coverage*
+.vscode
# C extensions
*.so
diff --git a/README.rst b/README.rst
index 5f868ad..ee844f3 100644
--- a/README.rst
+++ b/README.rst
@@ -25,40 +25,39 @@ HTML gallery of examples from any set of Python scripts.
Who uses Sphinx-Gallery
=======================
-* `Sphinx-Gallery <https://sphinx-gallery.github.io/stable/auto_examples/index.html>`_
+An incomplete list:
.. projects_list_start
-* `Scikit-learn <http://scikit-learn.org/stable/auto_examples/index.html>`_
-* `Nilearn <https://nilearn.github.io/stable/auto_examples/index.html>`_
-* `MNE-python <https://mne.tools/stable/auto_examples/index.html>`_
-* `PyStruct <https://pystruct.github.io/auto_examples/index.html>`_
+* `Apache TVM <https://tvm.apache.org/docs/tutorial/index.html>`_
+* `Astropy <https://docs.astropy.org/en/stable/generated/examples/index.html>`_
+* `Biotite <https://www.biotite-python.org/examples/gallery/index.html>`_
+* `Auto-sklearn <https://automl.github.io/auto-sklearn/master/examples/index.html>`_
+* `Cartopy <https://scitools.org.uk/cartopy/docs/latest/gallery/>`_
+* `Fury <https://fury.gl/latest/auto_examples/index.html>`_
* `GIMLi <https://www.pygimli.org/_examples_auto/index.html>`_
+* `Matplotlib <https://matplotlib.org/stable/index.html>`_:
+* `MNE-python <https://mne.tools/stable/auto_examples/index.html>`_
* `Nestle <http://kylebarbary.com/nestle/examples/index.html>`_
+* `NetworkX <https://networkx.org/documentation/stable/auto_examples/index.html>`_
+* `Neuraxle <https://www.neuraxle.org/stable/examples/index.html>`_
+* `Nilearn <https://nilearn.github.io/stable/auto_examples/index.html>`_
+* `OpenML-Python <https://openml.github.io/openml-python/main/examples/index.html>`_
+* `Optuna <https://optuna.readthedocs.io/en/stable/tutorial/index.html>`_
+* `PlasmaPy <https://docs.plasmapy.org/en/latest/examples.html>`_
* `pyRiemann <https://pyriemann.readthedocs.io/en/latest/index.html>`_
-* `scikit-image <https://scikit-image.org/docs/dev/auto_examples/>`_
-* `Astropy <https://docs.astropy.org/en/stable/generated/examples/index.html>`_
-* `SunPy <https://docs.sunpy.org/en/stable/generated/gallery/index.html>`_
+* `PyStruct <https://pystruct.github.io/auto_examples/index.html>`_
* `PySurfer <https://pysurfer.github.io/>`_
-* `Matplotlib <https://matplotlib.org/stable/index.html>`_:
- `Examples <https://matplotlib.org/stable/gallery/index.html>`_ and
- `Tutorials <https://matplotlib.org/stable/tutorials/index.html>`_
* `PyTorch tutorials <https://pytorch.org/tutorials>`_
-* `Cartopy <https://scitools.org.uk/cartopy/docs/latest/gallery/>`_
* `PyVista <https://docs.pyvista.org/examples/>`_
+* `Radis <https://radis.readthedocs.io/en/latest/auto_examples/index.html>`_
+* `scikit-image <https://scikit-image.org/docs/dev/auto_examples/>`_
+* `Scikit-learn <http://scikit-learn.org/stable/auto_examples/index.html>`_
* `SimPEG <https://docs.simpeg.xyz/content/examples/>`_
-* `PlasmaPy <https://docs.plasmapy.org/en/latest/examples.html>`_
-* `Fury <https://fury.gl/latest/auto_examples/index.html>`_
-* `NetworkX <https://networkx.org/documentation/stable/auto_examples/index.html>`_
-* `Optuna <https://optuna.readthedocs.io/en/stable/tutorial/index.html>`_
-* `Auto-sklearn <https://automl.github.io/auto-sklearn/master/examples/index.html>`_
-* `OpenML-Python <https://openml.github.io/openml-python/main/examples/index.html>`_
-* `TorchIO <https://torchio.readthedocs.io/auto_examples/index.html>`_
-* `Neuraxle <https://www.neuraxle.org/stable/examples/index.html>`_
-* `Biotite <https://www.biotite-python.org/examples/gallery/index.html>`_
-* `Apache TVM <https://tvm.apache.org/docs/tutorial/index.html>`_
+* `Sphinx-Gallery <https://sphinx-gallery.github.io/stable/auto_examples/index.html>`_
* `Tonic <https://tonic.readthedocs.io/en/latest/auto_examples/index.html>`_
-* `Radis <https://radis.readthedocs.io/en/latest/auto_examples/index.html>`_
+* `TorchIO <https://torchio.readthedocs.io/auto_examples/index.html>`_
+* `SunPy <https://docs.sunpy.org/en/stable/generated/gallery/index.html>`_
.. projects_list_end
@@ -87,8 +86,8 @@ the file sizes of the generated PNG files.
.. installation-end-content
-Install as a Sphinx-Gallery developer
--------------------------------------
+Contributing
+============
You can get the latest development source from our `Github repository
<https://github.com/sphinx-gallery/sphinx-gallery>`_. You need
@@ -99,10 +98,17 @@ you can do:
$ git clone https://github.com/sphinx-gallery/sphinx-gallery
$ cd sphinx-gallery
- $ pip install -r dev-requirements.txt
+ $ pip install -r requirements.txt -r dev-requirements.txt
+ $ conda install graphviz # if using conda, you can get graphviz this way
$ pip install -e .
+Check that you are all set by running:
+
+.. code-block:: console
+
+ $ pytest sphinx_gallery
+
How to cite
===========
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index 01015e6..7085218 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -265,7 +265,7 @@ THUMBNAIL_TEMPLATE = """
.. only:: html
.. image:: /{thumbnail}
- :alt: {title}
+ :alt:
:ref:`sphx_glr_{ref_name}`
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 24a5153..e0aea51 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -210,6 +210,17 @@ def _sanitize_rst(string):
string = re.sub(p + r'`([^`]+)`' + e, r'\1\2\3', string)
# `whatever thing` --> whatever thing
string = re.sub(p + r'([^`]+)' + e, r'\1\2\3', string)
+
+ # **string** --> string
+ string = re.sub(r'\*\*([^\*]*)\*\*', r'\1', string)
+ # *string* --> string
+ string = re.sub(r'\*([^\*]*)\*', r'\1', string)
+ # `link text <url>`_ --> link text
+ string = re.sub(r'`([^`<>]+) <[^`<>]+>`\_\_?', r'\1', string)
+
+ # :anchor:`the term` --> the term
+ string = re.sub(r':[a-z]+:`([^`<>]+)( <[^`<>]+>)?`', r'\1', string)
+
return string
@@ -244,6 +255,9 @@ def extract_intro_and_title(filename, docstring):
intro = _sanitize_rst(intro)
if len(intro) > 95:
intro = intro[:95] + '...'
+
+ title = _sanitize_rst(title)
+
return intro, title
|
sphinx-gallery/sphinx-gallery
|
28f744d234fc6bee8a3593f0c06d8613e9916afb
|
diff --git a/sphinx_gallery/tests/test_backreferences.py b/sphinx_gallery/tests/test_backreferences.py
index 4aa8e44..ce5fe07 100644
--- a/sphinx_gallery/tests/test_backreferences.py
+++ b/sphinx_gallery/tests/test_backreferences.py
@@ -21,7 +21,7 @@ REFERENCE = r"""
.. only:: html
.. image:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
- :alt: test title
+ :alt:
:ref:`sphx_glr_fake_dir_test_file.py`
diff --git a/sphinx_gallery/tests/test_full.py b/sphinx_gallery/tests/test_full.py
index 7c4f9fa..a90defc 100644
--- a/sphinx_gallery/tests/test_full.py
+++ b/sphinx_gallery/tests/test_full.py
@@ -866,19 +866,19 @@ def test_alt_text_thumbnail(sphinx_app):
generated_examples_index = op.join(out_dir, 'auto_examples', 'index.html')
with codecs.open(generated_examples_index, 'r', 'utf-8') as fid:
html = fid.read()
- assert 'alt=""SVG":-`graphics_`"' in html
+ assert 'alt=""' in html
# check backreferences thumbnail, html
backref_html = op.join(out_dir, 'gen_modules',
'sphinx_gallery.backreferences.html')
with codecs.open(backref_html, 'r', 'utf-8') as fid:
html = fid.read()
- assert 'alt="Link to other packages"' in html
+ assert 'alt=""' in html
# check gallery index thumbnail, rst
generated_examples_index = op.join(src_dir, 'auto_examples',
'index.rst')
with codecs.open(generated_examples_index, 'r', 'utf-8') as fid:
rst = fid.read()
- assert ':alt: Trivial module to provide a value for plot_numpy_matplotlib.py' in rst # noqa: E501
+ assert ':alt:' in rst
def test_backreference_labels(sphinx_app):
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 46622e4..158cb14 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -295,7 +295,7 @@ def test_extract_intro_and_title():
# Title with punctuation (gh-517)
intro, title = sg.extract_intro_and_title('<string>',
' ------------\n"-`Header"-with:; `punct` mark\'s\n----------------') # noqa: E501
- assert title == '"-`Header"-with:; `punct` mark\'s'
+ assert title == '"-`Header"-with:; punct mark\'s'
# Long intro paragraph gets shortened
intro_paragraph = '\n'.join(['this is one line' for _ in range(10)])
|
Thumbnail title regression since 0.11.0
#906 changed the way thumbnail views of galleries are created. It now exposes the rst formatting in the caption:
[Current](https://matplotlib.org/devdocs/tutorials/index.html#intermediate):

[Previous:](https://matplotlib.org/2.2.5/tutorials/index.html)

See also https://github.com/sphinx-gallery/sphinx-gallery/issues/998#issuecomment-1245912973
|
0.0
|
28f744d234fc6bee8a3593f0c06d8613e9916afb
|
[
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[<\"test\">-<"test">-False]",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[test",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[1",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[use",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[`this`",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title"
] |
[
"sphinx_gallery/tests/test_backreferences.py::test_identify_names",
"sphinx_gallery/tests/test_backreferences.py::test_identify_names2",
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_final_rst_last_word",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_empty_code_block",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums[b-a546be453c8f436e744838a4801bd3a0]",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums[t-ea8a570e9f3afc0a7c3f2a17a48b8047]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[#sphinx_gallery_thumbnail_path",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_gen_rst.py::test_output_no_ansi",
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box",
"sphinx_gallery/tests/test_gen_rst.py::test_reset_module_order_3_param_invalid_when",
"sphinx_gallery/tests/test_gen_rst.py::test_full_line",
"sphinx_gallery/tests/test_gen_rst.py::test_incomplete_line_with_flush",
"sphinx_gallery/tests/test_gen_rst.py::test_incomplete_line_with_more_output",
"sphinx_gallery/tests/test_gen_rst.py::test_multi_line",
"sphinx_gallery/tests/test_gen_rst.py::test_isatty"
] |
{
"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
}
|
2022-09-19 14:00:00+00:00
|
bsd-3-clause
| 5,650 |
|
sphinx-gallery__sphinx-gallery-1177
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 4d95321..efa5edd 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,12 +1,12 @@
repos:
- repo: https://github.com/psf/black
- rev: 23.7.0
+ rev: 23.9.1
hooks:
- id: black
args: [--quiet]
exclude: plot_syntaxerror
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.0.285
+ rev: v0.0.290
hooks:
- id: ruff
- repo: https://github.com/codespell-project/codespell
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index 55c185b..3b1ce53 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -12,7 +12,7 @@ from html import escape
import inspect
import os
import re
-import warnings
+import sys
from sphinx.errors import ExtensionError
import sphinx.util
@@ -178,42 +178,34 @@ class NameFinder(ast.NodeVisitor):
return options
-def _from_import(a, b):
- imp_line = f"from {a} import {b}"
- scope = dict()
- with warnings.catch_warnings(record=True): # swallow warnings
- warnings.simplefilter("ignore")
- exec(imp_line, scope, scope)
- return scope
-
-
def _get_short_module_name(module_name, obj_name):
"""Get the shortest possible module name."""
if "." in obj_name:
obj_name, attr = obj_name.split(".")
else:
attr = None
- scope = {}
+
try:
- # Find out what the real object is supposed to be.
- scope = _from_import(module_name, obj_name)
- except Exception: # wrong object
+ # look only in sys.modules to avoid importing the module, which may
+ # otherwise have side effects
+ real_obj = getattr(sys.modules[module_name], obj_name)
+ if attr is not None:
+ getattr(real_obj, attr)
+ except (AttributeError, KeyError):
+ # AttributeError: wrong class
+ # KeyError: wrong object or module not previously imported
return None
- else:
- real_obj = scope[obj_name]
- if attr is not None and not hasattr(real_obj, attr): # wrong class
- return None # wrong object
parts = module_name.split(".")
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = ".".join(parts[:i])
- scope = {}
try:
- scope = _from_import(short_name, obj_name)
- # Ensure shortened object is the same as what we expect.
- assert real_obj is scope[obj_name]
- except Exception: # libraries can throw all sorts of exceptions...
+ assert real_obj is getattr(sys.modules[short_name], obj_name)
+ except (AssertionError, AttributeError, KeyError):
+ # AssertionError: shortened object is not what we expect
+ # KeyError: short module name not previously imported
+ # AttributeError: wrong class or object
# get the last working module name
short_name = ".".join(parts[: (i + 1)])
break
diff --git a/sphinx_gallery/py_source_parser.py b/sphinx_gallery/py_source_parser.py
index a7b401d..59fd8d7 100644
--- a/sphinx_gallery/py_source_parser.py
+++ b/sphinx_gallery/py_source_parser.py
@@ -212,7 +212,7 @@ def remove_ignore_blocks(code_block):
"""
Return the content of *code_block* with ignored areas removed.
- An ignore block starts with # sphinx_gallery_begin_ignore, and ends with
+ An ignore block starts with # sphinx_gallery_start_ignore, and ends with
# sphinx_gallery_end_ignore. These lines and anything in between them will
be removed, but surrounding empty lines are preserved.
@@ -221,8 +221,8 @@ def remove_ignore_blocks(code_block):
code_block : str
A code segment.
"""
- num_start_flags = len(re.findall(START_IGNORE_FLAG, code_block))
- num_end_flags = len(re.findall(END_IGNORE_FLAG, code_block))
+ num_start_flags = len(re.findall(START_IGNORE_FLAG, code_block, re.MULTILINE))
+ num_end_flags = len(re.findall(END_IGNORE_FLAG, code_block, re.MULTILINE))
if num_start_flags != num_end_flags:
raise ExtensionError(
|
sphinx-gallery/sphinx-gallery
|
74a8f1d5b3dd364fb4f2180b57f4fa9af9db858a
|
diff --git a/sphinx_gallery/tests/test_py_source_parser.py b/sphinx_gallery/tests/test_py_source_parser.py
index afc37e3..15a8280 100644
--- a/sphinx_gallery/tests/test_py_source_parser.py
+++ b/sphinx_gallery/tests/test_py_source_parser.py
@@ -76,7 +76,7 @@ def test_remove_ignore_comments():
normal_code = "# Regular code\n# should\n# be untouched!"
assert sg.remove_ignore_blocks(normal_code) == normal_code
- mismatched_code = "# sphinx_gallery_start_ignore"
+ mismatched_code = "x=5\n# sphinx_gallery_start_ignore\ny=4"
with pytest.raises(ExtensionError) as error:
sg.remove_ignore_blocks(mismatched_code)
assert "must have a matching" in str(error)
|
Searching for short module names in backreferences has side effects
This came up via a weird problem we were having building [napari docs](https://github.com/napari/docs) on certain platforms. I think this is a pretty niche problem, and in our case was caused partly by [setuptools allowing case-insensitive imports from editable installations](https://github.com/pypa/setuptools/issues/3994) on certain platforms (in our case macOS). I think that will eventually be fixed, but regardless it suggests a possible improvement in sphinx-gallery.
The basic problem is that sphinx-gallery does some importing when searching for short(er) module names in backreferences:
https://github.com/sphinx-gallery/sphinx-gallery/blob/2e1e2a8a23ed8becb737dac15a733f8b93318cda/sphinx_gallery/backreferences.py#L165
This has potential side effects that may affect examples, scrapers, and reset functions.
Unfortunately I don't really know a good way to clean up after such imports or perform them in isolation (subprocesses would be way too slow). You can remove things from `sys.modules`, but imports also get inserted into the namespace of the parent module. There are also ways to use `importlib` to execute the module without importing it, but none of this prevents the module itself from importing others.
All this said, my current best idea is to _only import modules that are already imported_ when looking at backreferences. That is, something like this:
```diff
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index 2d070f5..dfc2d9d 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -14,6 +14,7 @@ from html import escape
import inspect
import os
import re
+import sys
import warnings
from sphinx.errors import ExtensionError
@@ -163,6 +164,7 @@ class NameFinder(ast.NodeVisitor):
def _from_import(a, b):
+ assert a in sys.modules, f'{a} not in sys.modules, not importing it'
imp_line = f'from {a} import {b}'
scope = dict()
with warnings.catch_warnings(record=True): # swallow warnings
```
This should be safer as it leaves all initial importing up to the user/example code. I think the cost is that it may be a little less aggressive at finding shorter names. I don't think this will generally make a big (or any) difference, but I am also not that familiar with the feature. I did a build with and without this change on the napari docs and couldn't find a meaningful difference in the backrefs. If needed it could be added as a configuration, or maybe an existing configuration already covers this behavior?
I'm happy to hear other ideas here or thoughts on whether this is a real problem at all 😅.
See https://github.com/napari/docs/issues/214 for more discussion - also thanks to @lucyleeow for listening to all my wild theories as I investigated this.
|
0.0
|
74a8f1d5b3dd364fb4f2180b57f4fa9af9db858a
|
[
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_ignore_comments"
] |
[
"sphinx_gallery/tests/test_py_source_parser.py::test_get_docstring_and_rest",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[No",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#sphinx_gallery_line_numbers=True-file_conf3]",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#sphinx_gallery_thumbnail_number\\n=\\n5-file_conf4]",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#sphinx_gallery_thumbnail_number=1foo-None]",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[No",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#sphinx_gallery_line_numbers=True-]",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#sphinx_gallery_thumbnail_number\\n=\\n5-]",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[a"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-17 20:05:54+00:00
|
bsd-3-clause
| 5,651 |
|
sphinx-gallery__sphinx-gallery-142
|
diff --git a/.gitignore b/.gitignore
index c9e4050..f28edf3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,6 +39,7 @@ htmlcov/
.cache
nosetests.xml
coverage.xml
+*.orig
# Translations
*.mo
@@ -50,6 +51,7 @@ coverage.xml
# Sphinx documentation
doc/_build/
doc/auto_examples
+doc/auto_mayavi_examples
doc/tutorials/
doc/modules/generated
diff --git a/sphinx_gallery/notebook.py b/sphinx_gallery/notebook.py
index b05b9ff..fc0fccf 100644
--- a/sphinx_gallery/notebook.py
+++ b/sphinx_gallery/notebook.py
@@ -11,11 +11,13 @@ Class that holds the Jupyter notebook information
# License: 3-clause BSD
from __future__ import division, absolute_import, print_function
+from functools import partial
import json
import os
import re
import sys
+
def ipy_notebook_skeleton():
"""Returns a dictionary with the elements of a Jupyter notebook"""
py_version = sys.version_info
@@ -46,6 +48,14 @@ def ipy_notebook_skeleton():
return notebook_skeleton
+def directive_fun(match, directive):
+ """Helper to fill in directives"""
+ directive_to_alert = dict(note="info", warning="danger")
+ return ('<div class="alert alert-{0}"><h4>{1}</h4><p>{2}</p></div>'
+ .format(directive_to_alert[directive], directive.capitalize(),
+ match.group(1).strip()))
+
+
def rst2md(text):
"""Converts the RST text from the examples docstrigs and comments
into markdown text for the Jupyter notebooks"""
@@ -61,6 +71,30 @@ def rst2md(text):
inline_math = re.compile(r':math:`(.+?)`', re.DOTALL)
text = re.sub(inline_math, r'$\1$', text)
+ directives = ('warning', 'note')
+ for directive in directives:
+ directive_re = re.compile(r'^\.\. %s::((?:.+)?(?:\n+^ .+)*)'
+ % directive, flags=re.M)
+ text = re.sub(directive_re,
+ partial(directive_fun, directive=directive), text)
+
+ links = re.compile(r'^ *\.\. _.*:.*$\n', flags=re.M)
+ text = re.sub(links, '', text)
+
+ refs = re.compile(r':ref:`')
+ text = re.sub(refs, '`', text)
+
+ contents = re.compile(r'^\s*\.\. contents::.*$(\n +:\S+: *$)*\n',
+ flags=re.M)
+ text = re.sub(contents, '', text)
+
+ images = re.compile(
+ r'^\.\. image::(.*$)(?:\n *:alt:(.*$)\n)?(?: +:\S+:.*$\n)*',
+ flags=re.M)
+ text = re.sub(
+ images, lambda match: '\n'.format(
+ match.group(1).strip(), (match.group(2) or '').strip()), text)
+
return text
diff --git a/tutorials/plot_notebook.py b/tutorials/plot_notebook.py
index 558f7d4..5809cd5 100644
--- a/tutorials/plot_notebook.py
+++ b/tutorials/plot_notebook.py
@@ -99,3 +99,16 @@ print('Some output from Python')
# code directly will see the plots; this is not necessary for creating the docs
plt.show()
+
+############################################################################
+# You can also include :math:`math` inline, or as separate equations:
+#
+# .. math::
+#
+# \exp(j\pi) = -1
+#
+# You can also insert images:
+#
+# .. image:: http://www.sphinx-doc.org/en/stable/_static/sphinxheader.png
+# :alt: Sphinx header
+#
|
sphinx-gallery/sphinx-gallery
|
4406558320e75543607dc51b2427e912c05a9c94
|
diff --git a/sphinx_gallery/tests/test_notebook.py b/sphinx_gallery/tests/test_notebook.py
index a76ec1f..93a240a 100644
--- a/sphinx_gallery/tests/test_notebook.py
+++ b/sphinx_gallery/tests/test_notebook.py
@@ -26,3 +26,43 @@ def test_latex_conversion():
\begin{align}\mathcal{H} &= 0 \\
\mathcal{G} &= D\end{align}"""
assert_equal(align_eq_jmd, rst2md(align_eq))
+
+
+def test_convert():
+ """Test ReST conversion"""
+ rst = """hello
+
+.. contents::
+ :local:
+
+This is :math:`some` math :math:`stuff`.
+
+.. note::
+ Interpolation is a linear operation that can be performed also on
+ Raw and Epochs objects.
+
+.. warning::
+ Go away
+
+For more details on interpolation see the page :ref:`channel_interpolation`.
+.. _foo: bar
+
+.. image:: foobar
+ :alt: me
+ :whatever: you
+"""
+
+ markdown = """hello
+
+This is $some$ math $stuff$.
+
+<div class="alert alert-info"><h4>Note</h4><p>Interpolation is a linear operation that can be performed also on
+ Raw and Epochs objects.</p></div>
+
+<div class="alert alert-danger"><h4>Warning</h4><p>Go away</p></div>
+
+For more details on interpolation see the page `channel_interpolation`.
+
+
+""" # noqa
+ assert_equal(rst2md(rst), markdown)
|
RST directives remain in ipynb
The IPython ipynb downloads don't strip all irrelevant stuff e.g. links:
http://martinos.org/mne/dev/_downloads/plot_background_filtering.ipynb
Looks like this:

Should we remove lines starting with `.. `?
|
0.0
|
4406558320e75543607dc51b2427e912c05a9c94
|
[
"sphinx_gallery/tests/test_notebook.py::test_convert"
] |
[
"sphinx_gallery/tests/test_notebook.py::test_latex_conversion"
] |
{
"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
}
|
2016-08-30 17:08:15+00:00
|
bsd-3-clause
| 5,652 |
|
sphinx-gallery__sphinx-gallery-173
|
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index 4fe579c..28cf10a 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -103,7 +103,13 @@ def identify_names(code):
for name, full_name in finder.get_mapping():
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
- module, attribute = full_name.rsplit('.', 1)
+ splitted = full_name.rsplit('.', 1)
+ if len(splitted) == 1:
+ # module without attribute. This is not useful for
+ # backreferences
+ continue
+
+ module, attribute = splitted
# get shortened module name
module_short = get_short_module_name(module, attribute)
cobj = {'name': attribute, 'module': module,
|
sphinx-gallery/sphinx-gallery
|
ec05b2299b1ccec6e649a5b9535ced235d62d129
|
diff --git a/sphinx_gallery/tests/test_backreferences.py b/sphinx_gallery/tests/test_backreferences.py
index d820378..1e9e6c9 100644
--- a/sphinx_gallery/tests/test_backreferences.py
+++ b/sphinx_gallery/tests/test_backreferences.py
@@ -60,3 +60,33 @@ def test_backref_thumbnail_div():
"""
assert_equal(html_div, reference)
+
+
+def test_identify_names():
+ code_str = """
+import os
+os
+
+os.path.join
+
+import sphinx_gallery.back_references as br
+br.identify_names
+
+from sphinx_gallery.back_references import identify_names
+identify_names
+"""
+ res = sg.identify_names(code_str)
+ expected = {
+ 'os.path.join':
+ {'name': 'join', 'module': 'os.path', 'module_short': 'os.path'},
+ 'br.identify_names':
+ {'name': 'identify_names',
+ 'module': 'sphinx_gallery.back_references',
+ 'module_short': 'sphinx_gallery.back_references'},
+ 'identify_names':
+ {'name': 'identify_names',
+ 'module': 'sphinx_gallery.back_references',
+ 'module_short': 'sphinx_gallery.back_references'}
+ }
+
+ assert_equal(expected, res)
|
backreferences processing breaks if module accessed without attribute
The scikit-learn docs fail to build at https://circleci.com/gh/scikit-learn/scikit-learn/7314?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link due to https://github.com/sphinx-gallery/sphinx-gallery/blob/master/sphinx_gallery/backreferences.py#L106 where it is assumed that a module being referenced is always referenced with an attribute. It should be possible to reference a module without its attribute and hence for no `.` to be present.
|
0.0
|
ec05b2299b1ccec6e649a5b9535ced235d62d129
|
[
"sphinx_gallery/tests/test_backreferences.py::test_identify_names"
] |
[
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div",
"sphinx_gallery/tests/test_backreferences.py::test_backref_thumbnail_div"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-11-23 10:20:54+00:00
|
bsd-3-clause
| 5,653 |
|
sphinx-gallery__sphinx-gallery-281
|
diff --git a/doc/advanced_configuration.rst b/doc/advanced_configuration.rst
index 963d95f..d8a6c5d 100644
--- a/doc/advanced_configuration.rst
+++ b/doc/advanced_configuration.rst
@@ -18,6 +18,7 @@ file:
- ``examples_dirs`` and ``gallery_dirs`` (:ref:`multiple_galleries_config`)
- ``filename_pattern`` (:ref:`build_pattern`)
- ``subsection_order`` (:ref:`sub_gallery_order`)
+- ``within_subsection_order`` (:ref:`within_gallery_order`)
- ``reference_url`` (:ref:`link_to_documentation`)
- ``backreferences_dir`` and ``doc_module`` (:ref:`references_to_examples`)
- ``default_thumb_file`` (:ref:`custom_default_thumb`)
@@ -149,6 +150,33 @@ If you so desire you can implement your own sorting key. It will be
provided the relative paths to `conf.py` of each sub gallery folder.
+.. _within_gallery_order:
+
+Sorting gallery examples
+========================
+
+Within a given gallery (sub)section, the example files are ordered by
+using the standard :func:`sorted` function with the ``key`` argument by default
+set to
+:class:`NumberOfCodeLinesSortKey(src_dir) <sphinx_gallery.sorting.NumberOfCodeLinesSortKey>`,
+which sorts the files based on the number of code lines::
+
+ from sphinx_gallery.sorting import NumberOfCodeLinesSortKey
+ sphinx_gallery_conf = {
+ ...
+ 'within_subsection_order': NumberOfCodeLinesSortKey,
+ }
+
+In addition, multiple convenience classes are provided for use with
+``within_subsection_order``:
+
+- :class:`sphinx_gallery.sorting.NumberOfCodeLinesSortKey` (default) to sort by
+ the number of code lines.
+- :class:`sphinx_gallery.sorting.FileSizeSortKey` to sort by file size.
+- :class:`sphinx_gallery.sorting.FileNameSortKey` to sort by file name.
+- :class:`sphinx_gallery.sorting.ExampleTitleSortKey` to sort by example title.
+
+
.. _link_to_documentation:
Linking to documentation
diff --git a/doc/conf.py b/doc/conf.py
index eaa5dff..63cae10 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -306,7 +306,7 @@ intersphinx_mapping = {
'mayavi': ('http://docs.enthought.com/mayavi/mayavi', None),
}
-from sphinx_gallery.sorting import ExplicitOrder
+from sphinx_gallery.sorting import ExplicitOrder, NumberOfCodeLinesSortKey
examples_dirs = ['../examples', '../tutorials']
gallery_dirs = ['auto_examples', 'tutorials']
@@ -336,6 +336,7 @@ sphinx_gallery_conf = {
'subsection_order': ExplicitOrder(['../examples/sin_func',
'../examples/no_output',
'../tutorials/seaborn']),
+ 'within_subsection_order': NumberOfCodeLinesSortKey,
'find_mayavi_figures': find_mayavi_figures,
'expected_failing_examples': ['../examples/no_output/plot_raise.py',
'../examples/no_output/plot_syntaxerror.py']
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index dff8170..38fb667 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -21,6 +21,7 @@ from . import sphinx_compatibility
from .gen_rst import generate_dir_rst, SPHX_GLR_SIG
from .docs_resolv import embed_code_links
from .downloads import generate_zipfiles
+from .sorting import NumberOfCodeLinesSortKey
try:
FileNotFoundError
@@ -32,6 +33,7 @@ DEFAULT_GALLERY_CONF = {
'filename_pattern': re.escape(os.sep) + 'plot',
'examples_dirs': os.path.join('..', 'examples'),
'subsection_order': None,
+ 'within_subsection_order': NumberOfCodeLinesSortKey,
'gallery_dirs': 'auto_examples',
'backreferences_dir': None,
'doc_module': (),
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 73c86a0..41fd465 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -153,22 +153,30 @@ def codestr2rst(codestr, lang='python', lineno=None):
return code_directive + indented_block
-def extract_intro(filename, docstring):
+def extract_intro_and_title(filename, docstring):
""" Extract the first paragraph of module-level docstring. max:95 char"""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
- if len(paragraphs) > 1:
- first_paragraph = re.sub('\n', ' ', paragraphs[1])
- first_paragraph = (first_paragraph[:95] + '...'
- if len(first_paragraph) > 95 else first_paragraph)
- else:
+ # remove comments and other syntax like `.. _link:`
+ paragraphs = [p for p in paragraphs if not p.startswith('.. ')]
+ if len(paragraphs) <= 1:
raise ValueError(
"Example docstring should have a header for the example title "
"and at least a paragraph explaining what the example is about. "
"Please check the example file:\n {}\n".format(filename))
+ # Title is the first paragraph with any ReSTructuredText title chars
+ # removed, i.e. lines that consist of (all the same) 7-bit non-ASCII chars.
+ # This conditional is not perfect but should hopefully be good enough.
+ title = paragraphs[0].strip().split('\n')
+ title = ' '.join(t for t in title if len(t) > 0 and
+ (ord(t[0]) >= 128 or t[0].isalnum()))
+ # Concatenate all lines of the first paragraph and truncate at 95 chars
+ first_paragraph = re.sub('\n', ' ', paragraphs[1])
+ first_paragraph = (first_paragraph[:95] + '...'
+ if len(first_paragraph) > 95 else first_paragraph)
- return first_paragraph
+ return first_paragraph, title
def get_md5sum(src_file):
@@ -377,8 +385,10 @@ def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
if not os.path.exists(target_dir):
os.makedirs(target_dir)
- sorted_listdir = [fname for fname in sorted(os.listdir(src_dir))
- if fname.endswith('.py')]
+ listdir = [fname for fname in os.listdir(src_dir)
+ if fname.endswith('.py')]
+ sorted_listdir = sorted(
+ listdir, key=gallery_conf['within_subsection_order'](src_dir))
entries_text = []
computation_times = []
build_target_dir = os.path.relpath(target_dir, gallery_conf['src_dir'])
@@ -387,29 +397,25 @@ def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
'Generating gallery for %s ' % build_target_dir,
length=len(sorted_listdir))
for fname in iterator:
- intro, amount_of_code, time_elapsed = generate_file_rst(
+ intro, time_elapsed = generate_file_rst(
fname,
target_dir,
src_dir,
gallery_conf)
computation_times.append((time_elapsed, fname))
- new_fname = os.path.join(src_dir, fname)
this_entry = _thumbnail_div(build_target_dir, fname, intro) + """
.. toctree::
:hidden:
/%s\n""" % os.path.join(build_target_dir, fname[:-3]).replace(os.sep, '/')
- entries_text.append((amount_of_code, this_entry))
+ entries_text.append(this_entry)
if gallery_conf['backreferences_dir']:
write_backreferences(seen_backrefs, gallery_conf,
target_dir, fname, intro)
- # sort to have the smallest entries in the beginning
- entries_text.sort()
-
- for _, entry_text in entries_text:
+ for entry_text in entries_text:
fhindex += entry_text
# clear at the end of the section
@@ -533,8 +539,6 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
-------
intro: str
The introduction of the example
- amount_of_code : int
- character count of the corresponding python script in file
time_elapsed : float
seconds required to run the script
"""
@@ -543,13 +547,10 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
example_file = os.path.join(target_dir, fname)
shutil.copyfile(src_file, example_file)
file_conf, script_blocks = split_code_and_text_blocks(src_file)
- amount_of_code = sum([len(bcontent)
- for blabel, bcontent, lineno in script_blocks
- if blabel == 'code'])
- intro = extract_intro(fname, script_blocks[0][1])
+ intro, title = extract_intro_and_title(fname, script_blocks[0][1])
if md5sum_is_current(example_file):
- return intro, amount_of_code, 0
+ return intro, 0
image_dir = os.path.join(target_dir, 'images')
if not os.path.exists(image_dir):
@@ -648,4 +649,4 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
if block_vars['execute_script']:
logger.debug("%s ran in : %.2g seconds", src_file, time_elapsed)
- return intro, amount_of_code, time_elapsed
+ return intro, time_elapsed
diff --git a/sphinx_gallery/sorting.py b/sphinx_gallery/sorting.py
index 98b7dbe..d889e1c 100644
--- a/sphinx_gallery/sorting.py
+++ b/sphinx_gallery/sorting.py
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
r"""
-Sorters for Sphinx-Gallery subsections
-======================================
+Sorters for Sphinx-Gallery (sub)sections
+========================================
-Sorting key functions for gallery subsection folders
+Sorting key functions for gallery subsection folders and section files.
"""
# Created: Sun May 21 20:38:59 2017
# Author: Óscar Nájera
@@ -13,21 +13,24 @@ from __future__ import division, absolute_import, print_function
import os
import types
+from .gen_rst import extract_intro_and_title
+from .py_source_parser import split_code_and_text_blocks
+
class ExplicitOrder(object):
- """Sorting key for all galleries subsections
+ """Sorting key for all gallery subsections.
- This requires all folders to be listed otherwise an exception is raised
+ This requires all folders to be listed otherwise an exception is raised.
Parameters
----------
ordered_list : list, tuple, types.GeneratorType
- Hold the paths of each galleries' subsections
+ Hold the paths of each galleries' subsections.
Raises
------
ValueError
- Wrong input type or Subgallery path missing
+ Wrong input type or Subgallery path missing.
"""
def __init__(self, ordered_list):
@@ -46,3 +49,71 @@ class ExplicitOrder(object):
raise ValueError('If you use an explicit folder ordering, you '
'must specify all folders. Explicit order not '
'found for {}'.format(item))
+
+
+class _SortKey(object):
+ """Base class for section order key classes."""
+
+ def __init__(self, src_dir):
+ self.src_dir = src_dir
+
+
+class NumberOfCodeLinesSortKey(_SortKey):
+ """Sort examples in src_dir by the number of code lines.
+
+ Parameters
+ ----------
+ src_dir : str
+ The source directory.
+ """
+
+ def __call__(self, filename):
+ src_file = os.path.normpath(os.path.join(self.src_dir, filename))
+ file_conf, script_blocks = split_code_and_text_blocks(src_file)
+ amount_of_code = sum([len(bcontent)
+ for blabel, bcontent, lineno in script_blocks
+ if blabel == 'code'])
+ return amount_of_code
+
+
+class FileSizeSortKey(_SortKey):
+ """Sort examples in src_dir by file size.
+
+ Parameters
+ ----------
+ src_dir : str
+ The source directory.
+ """
+
+ def __call__(self, filename):
+ src_file = os.path.normpath(os.path.join(self.src_dir, filename))
+ return os.stat(src_file).st_size
+
+
+class FileNameSortKey(_SortKey):
+ """Sort examples in src_dir by file size.
+
+ Parameters
+ ----------
+ src_dir : str
+ The source directory.
+ """
+
+ def __call__(self, filename):
+ return filename
+
+
+class ExampleTitleSortKey(_SortKey):
+ """Sort examples in src_dir by example title.
+
+ Parameters
+ ----------
+ src_dir : str
+ The source directory.
+ """
+
+ def __call__(self, filename):
+ src_file = os.path.normpath(os.path.join(self.src_dir, filename))
+ _, script_blocks = split_code_and_text_blocks(src_file)
+ _, title = extract_intro_and_title(src_file, script_blocks[0][1])
+ return title
|
sphinx-gallery/sphinx-gallery
|
b6e1b5ebdd1d2bf788fc597c340805ce4cca8f67
|
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 79e0b49..09c11e8 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -5,15 +5,17 @@ r"""
Test Sphinx-Gallery
"""
-from __future__ import division, absolute_import, print_function, unicode_literals
+from __future__ import (division, absolute_import, print_function,
+ unicode_literals)
+import codecs
import os
-import tempfile
+import re
import shutil
+import tempfile
import pytest
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError
from sphinx_gallery.gen_rst import MixedEncodingStringIO
-from sphinx_gallery.gen_gallery import DEFAULT_GALLERY_CONF
from sphinx_gallery import sphinx_compatibility
@@ -162,3 +164,69 @@ def test_config_backreferences(config_app):
'gen_modules', 'backreferences')
build_warn = config_app._warning.getvalue()
assert build_warn == ""
+
+
+def _check_order(config_app, key):
+ index_fname = os.path.join(config_app.outdir, '..', 'ex', 'index.rst')
+ order = list()
+ regex = '.*:%s=(.):.*' % key
+ with codecs.open(index_fname, 'r', 'utf-8') as fid:
+ for line in fid:
+ if 'sphx-glr-thumbcontainer' in line:
+ order.append(int(re.match(regex, line).group(1)))
+ assert len(order) == 3
+ assert order == [1, 2, 3]
+
+
[email protected]_file(content="""
+import sphinx_gallery
+extensions = ['sphinx_gallery.gen_gallery']
+sphinx_gallery_conf = {
+ 'examples_dirs': 'src',
+ 'gallery_dirs': 'ex',
+}""")
+def test_example_sorting_default(config_app):
+ """Test sorting of examples by default key (number of code lines)."""
+ _check_order(config_app, 'lines')
+
+
[email protected]_file(content="""
+import sphinx_gallery
+from sphinx_gallery.sorting import FileSizeSortKey
+extensions = ['sphinx_gallery.gen_gallery']
+sphinx_gallery_conf = {
+ 'examples_dirs': 'src',
+ 'gallery_dirs': 'ex',
+ 'within_subsection_order': FileSizeSortKey,
+}""")
+def test_example_sorting_filesize(config_app):
+ """Test sorting of examples by filesize."""
+ _check_order(config_app, 'filesize')
+
+
[email protected]_file(content="""
+import sphinx_gallery
+from sphinx_gallery.sorting import FileNameSortKey
+extensions = ['sphinx_gallery.gen_gallery']
+sphinx_gallery_conf = {
+ 'examples_dirs': 'src',
+ 'gallery_dirs': 'ex',
+ 'within_subsection_order': FileNameSortKey,
+}""")
+def test_example_sorting_filename(config_app):
+ """Test sorting of examples by filename."""
+ _check_order(config_app, 'filename')
+
+
[email protected]_file(content="""
+import sphinx_gallery
+from sphinx_gallery.sorting import ExampleTitleSortKey
+extensions = ['sphinx_gallery.gen_gallery']
+sphinx_gallery_conf = {
+ 'examples_dirs': 'src',
+ 'gallery_dirs': 'ex',
+ 'within_subsection_order': ExampleTitleSortKey,
+}""")
+def test_example_sorting_title(config_app):
+ """Test sorting of examples by title."""
+ _check_order(config_app, 'title')
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 1047f37..75d967d 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -25,7 +25,8 @@ from sphinx_gallery import sphinx_compatibility
import matplotlib.pyplot as plt
CONTENT = [
- '"""'
+ '"""',
+ '================',
'Docstring header',
'================',
'',
@@ -109,11 +110,13 @@ def test_codestr2rst():
assert reference == output
-def test_extract_intro():
- result = sg.extract_intro('<string>', '\n'.join(CONTENT[1:9]))
- assert 'Docstring' not in result
- assert result == 'This is the description of the example which goes on and on, Óscar' # noqa
- assert 'second paragraph' not in result
+def test_extract_intro_and_title():
+ intro, title = sg.extract_intro_and_title('<string>',
+ '\n'.join(CONTENT[1:10]))
+ assert title == 'Docstring header'
+ assert 'Docstring' not in intro
+ assert intro == 'This is the description of the example which goes on and on, Óscar' # noqa
+ assert 'second paragraph' not in intro
def test_md5sums():
diff --git a/sphinx_gallery/tests/test_sorting.py b/sphinx_gallery/tests/test_sorting.py
index 036e464..d6a866d 100644
--- a/sphinx_gallery/tests/test_sorting.py
+++ b/sphinx_gallery/tests/test_sorting.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
r"""
-Tests for sorting keys on gallery sections
-==========================================
+Tests for sorting keys on gallery (sub)sections
+===============================================
"""
# Author: Óscar Nájera
diff --git a/sphinx_gallery/tests/testconfs/src/plot_1.py b/sphinx_gallery/tests/testconfs/src/plot_1.py
new file mode 100644
index 0000000..721bfc1
--- /dev/null
+++ b/sphinx_gallery/tests/testconfs/src/plot_1.py
@@ -0,0 +1,11 @@
+"""
+======
+B test
+======
+
+:filename=1:title=2:lines=3:filesize=2:
+"""
+
+print('foo')
+print('bar')
+print('again')
diff --git a/sphinx_gallery/tests/testconfs/src/plot_2.py b/sphinx_gallery/tests/testconfs/src/plot_2.py
new file mode 100644
index 0000000..d468d79
--- /dev/null
+++ b/sphinx_gallery/tests/testconfs/src/plot_2.py
@@ -0,0 +1,9 @@
+"""
+======
+C test
+======
+
+:filename=2:title=3:lines=1:filesize=1:
+"""
+
+print('foo')
diff --git a/sphinx_gallery/tests/testconfs/src/plot_3.py b/sphinx_gallery/tests/testconfs/src/plot_3.py
new file mode 100644
index 0000000..ceea4c0
--- /dev/null
+++ b/sphinx_gallery/tests/testconfs/src/plot_3.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+"""
+.. _extra_ref:
+
+===========================================================
+A test with a really long title to make the filesize larger
+===========================================================
+
+:filename=3:title=1:lines=2:filesize=3:
+"""
+
+print('foo')
+print('bar')
|
ENH: Allow setting example order
I recently migrated PySurfer over to SG, and want to be able to set the example file order. There currently is no way to do that, correct? The workarounds would be to either build subdirectories, or re-title the examples e.g. "01. Basic visualization" etc. to get them in the correct order, which is not so satisfactory.
I propose adding an `example_order` dict to `conf.py` to complement the existing `subsection_order`. The design would be nested dicts:
```
'example_order': {'examples': ['plot_basic.py', 'plot_advanced.py']}
```
So the first-level dict would be key-value pair for `subsection: order`. If a subdirectory isn't listed, use default (title-alphabetical) sorting. If one is listed, it must list all SG-relevant files in the directory or an error is thrown. This seems the most conservative API-wise and should be fully backward compatible.
|
0.0
|
b6e1b5ebdd1d2bf788fc597c340805ce4cca8f67
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_figure_rst",
"sphinx_gallery/tests/test_sorting.py::test_ExplicitOrder_sorting_key"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-02 04:21:43+00:00
|
bsd-3-clause
| 5,654 |
|
sphinx-gallery__sphinx-gallery-345
|
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index e1f4c0e..8e45375 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -208,11 +208,11 @@ def extract_intro_and_title(filename, docstring):
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
- paragraphs = [p for p in paragraphs if not p.startswith('.. ')]
- if len(paragraphs) <= 1:
+ paragraphs = [p for p in paragraphs
+ if not p.startswith('.. ') and len(p) > 0]
+ if len(paragraphs) == 0:
raise ValueError(
- "Example docstring should have a header for the example title "
- "and at least a paragraph explaining what the example is about. "
+ "Example docstring should have a header for the example title. "
"Please check the example file:\n {}\n".format(filename))
# Title is the first paragraph with any ReSTructuredText title chars
# removed, i.e. lines that consist of (all the same) 7-bit non-ASCII chars.
@@ -220,8 +220,13 @@ def extract_intro_and_title(filename, docstring):
title = paragraphs[0].strip().split('\n')
title = ' '.join(t for t in title if len(t) > 0 and
(ord(t[0]) >= 128 or t[0].isalnum()))
+ if len(title) == 0:
+ raise ValueError('Empty title detected from first paragraph:\n%s'
+ % (paragraphs[0],))
+ # Use the title if no other paragraphs are provided
+ first_paragraph = title if len(paragraphs) < 2 else paragraphs[1]
# Concatenate all lines of the first paragraph and truncate at 95 chars
- first_paragraph = re.sub('\n', ' ', paragraphs[1])
+ first_paragraph = re.sub('\n', ' ', first_paragraph)
first_paragraph = (first_paragraph[:95] + '...'
if len(first_paragraph) > 95 else first_paragraph)
|
sphinx-gallery/sphinx-gallery
|
06adfe18772236b461d9922b7f25850deb858e1f
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index e8919bc..7269149 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -15,7 +15,6 @@ import re
import os
import shutil
import zipfile
-import sys
import pytest
@@ -121,6 +120,26 @@ def test_extract_intro_and_title():
assert intro == 'This is the description of the example which goes on and on, Óscar' # noqa
assert 'second paragraph' not in intro
+ # SG incorrectly grabbing description when a label is defined (gh-232)
+ intro_label, title_label = sg.extract_intro_and_title(
+ '<string>', '\n'.join(['.. my_label', ''] + CONTENT[1:10]))
+ assert intro_label == intro
+ assert title_label == title
+
+ intro_whitespace, title_whitespace = sg.extract_intro_and_title(
+ '<string>', '\n'.join(CONTENT[1:4] + [''] + CONTENT[5:10]))
+ assert intro_whitespace == intro
+ assert title_whitespace == title
+
+ # Make example title optional (gh-222)
+ intro, title = sg.extract_intro_and_title('<string', 'Title\n-----')
+ assert intro == title == 'Title'
+
+ with pytest.raises(ValueError, match='should have a header'):
+ sg.extract_intro_and_title('<string>', '') # no title
+ with pytest.raises(ValueError, match='Empty title'):
+ sg.extract_intro_and_title('<string>', '-') # no real title
+
def test_md5sums():
"""Test md5sum check functions work on know file content"""
|
SG incorrectly grabbing the description when a label is defined in docstring
I noticed that SG is incorrectly grabbing the description when you define a label in the docstring before the title. E.g.:
```
"""
.. my_label:
=======
Title
=======
etc etc.
"""
```
SG will correctly find title, but when it tries to pull the description it shows up as `=====Title=====` because it's splitting on the wrong line.
For example see my matplotlib (new) tutorials build here: http://predictablynoisy.com/matplotlib/tutorials/index.html
|
0.0
|
06adfe18772236b461d9922b7f25850deb858e1f
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_figure_rst"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-02-09 19:51:31+00:00
|
bsd-3-clause
| 5,655 |
|
sphinx-gallery__sphinx-gallery-371
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 6630556..3b90073 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -7,9 +7,10 @@ git master
New features
''''''''''''
-* Added experimental support to auto-generate Binder links for examples via ``binder``
- config. Note that this API may change in the future. `#244
- <https://github.com/sphinx-gallery/sphinx-gallery/pull/244>`_
+* Added experimental support to auto-generate Binder links for examples via
+ ``binder`` config. Note that this API may change in the future. `#244
+ <https://github.com/sphinx-gallery/sphinx-gallery/pull/244>`_ and `#371
+ <https://github.com/sphinx-gallery/sphinx-gallery/pull/371>`_.
* **CSS** Download and binder buttons are now on the right side for large
screens. This might change downstream CSS layouts.
"div.sphx-glr-footer-example" can be used to capture these specific
diff --git a/doc/advanced_configuration.rst b/doc/advanced_configuration.rst
index 7fbe48b..ae46915 100644
--- a/doc/advanced_configuration.rst
+++ b/doc/advanced_configuration.rst
@@ -24,7 +24,7 @@ file:
- ``default_thumb_file`` (:ref:`custom_default_thumb`)
- ``thumbnail_size`` (:ref:`setting_thumbnail_size`)
- ``line_numbers`` (:ref:`adding_line_numbers`)
-- ``download_section_examples`` (:ref:`disable_joint_download`)
+- ``download_all_examples`` (:ref:`disable_all_scripts_download`)
- ``plot_gallery`` (:ref:`without_execution`)
- ``find_mayavi_figures`` (:ref:`find_mayavi`)
- ``abort_on_example_error`` (:ref:`abort_on_first`)
@@ -381,19 +381,19 @@ Note that for Sphinx < 1.3, the line numbers will not be consistent with the
original file.
-.. _disable_joint_download:
+.. _disable_all_scripts_download:
-Disabling joint download of scripts
-===================================
+Disabling download button of all scripts
+========================================
-By default Sphinx-Gallery prepares zip files of all python scripts and
-all Jupyter notebooks for each gallery section and makes them
-available for download at the end of each section. To disable this
-behavior add to the configuration dictionary in your ``conf.py`` file::
+By default Sphinx-Gallery collects all python scripts and all Jupyter
+notebooks from each gallery into zip files which are made available for
+download at the bottom of each gallery. To disable this behavior add to the
+configuration dictionary in your ``conf.py`` file::
sphinx_gallery_conf = {
...
- 'download_section_examples': False,
+ 'download_all_examples': False,
}
@@ -442,19 +442,27 @@ dictionary following the pattern below::
sphinx_gallery_conf = {
...
'binder': {
+ # Required keys
'org': '<github_org>',
'repo': '<github_repo>',
'url': '<binder_url>', # Any URL of a binder server. Must be full URL (e.g. https://mybinder.org).
'branch': '<branch-for-documentation>', # Can be any branch, tag, or commit hash. Use a branch that hosts your docs.
'dependencies': '<list_of_paths_to_dependency_files>',
- 'filepath_prefix': '<prefix>' # Optional, a prefix to append to any filepaths in Binder links.
- use this if you move your built documentation to a sub-folder of your repository (e.g., "v2.1")
+ # Optional keys
+ 'filepath_prefix': '<prefix>' # A prefix to append to any filepaths in Binder links.
+ 'notebooks_dir': '<notebooks-directory-name>' # Jupyter notebooks for Binder will be copied to this directory (relative to site root).
+ 'use_jupyter_lab': <bool> # Whether Binder links should start Jupyter Lab instead of the Jupyter Notebook interface.
}
}
Note that ``branch:`` should be the branch on which your documentation is hosted.
If you host your documentation on GitHub, this is usually ``gh-pages`` or ``master``.
+Each generated Jupyter Notebook will be copied to the folder
+specified in ``notebooks_dir``. This will be a subfolder of the sphinx output
+directory and included with your site build.
+Binder links will point to these notebooks.
+
.. important::
``dependencies`` should be a list of paths to Binder configuration files that
diff --git a/doc/conf.py b/doc/conf.py
index ac53cf6..773afba 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -345,6 +345,8 @@ sphinx_gallery_conf = {
'repo': 'sphinx-gallery.github.io',
'url': 'https://mybinder.org',
'branch': 'master',
- 'dependencies': './binder/requirements.txt'
+ 'dependencies': './binder/requirements.txt',
+ 'notebooks_dir': 'notebooks',
+ 'use_jupyter_lab': True,
}
}
diff --git a/sphinx_gallery/binder.py b/sphinx_gallery/binder.py
index 961a2be..7dced88 100644
--- a/sphinx_gallery/binder.py
+++ b/sphinx_gallery/binder.py
@@ -15,7 +15,7 @@ change in the future.
"""
-import shutil as sh
+import shutil
import os
try:
@@ -25,9 +25,13 @@ except NameError:
unicode = str
from .utils import replace_py_ipynb
+from . import sphinx_compatibility
-def gen_binder_url(fname, binder_conf):
+logger = sphinx_compatibility.getLogger('sphinx-gallery')
+
+
+def gen_binder_url(fname, binder_conf, gallery_conf):
"""Generate a Binder URL according to the configuration in conf.py.
Parameters
@@ -45,20 +49,36 @@ def gen_binder_url(fname, binder_conf):
"""
# Build the URL
fpath_prefix = binder_conf.get('filepath_prefix')
- binder_fpath = '_downloads/{}'.format(replace_py_ipynb(fname))
+ link_base = binder_conf.get('notebooks_dir')
+
+ # We want to keep the relative path to sub-folders
+ relative_link = os.path.relpath(fname, gallery_conf['src_dir'])
+ path_link = os.path.join(
+ link_base, replace_py_ipynb(relative_link))
+
+ # In case our website is hosted in a sub-folder
if fpath_prefix is not None:
- binder_fpath = '/'.join([fpath_prefix.strip('/'), binder_fpath])
+ path_link = '/'.join([fpath_prefix.strip('/'), path_link])
+
+ # Make sure we have the right slashes (in case we're on Windows)
+ path_link = path_link.replace(os.path.sep, '/')
+
+ # Create the URL
binder_url = binder_conf['url']
binder_url = '/'.join([binder_conf['url'],
'v2', 'gh',
binder_conf['org'],
binder_conf['repo'],
binder_conf['branch']])
- binder_url += '?filepath={}'.format(binder_fpath)
+
+ if binder_conf.get('use_jupyter_lab', False) is True:
+ binder_url += '?urlpath=lab/tree/{}'.format(path_link)
+ else:
+ binder_url += '?filepath={}'.format(path_link)
return binder_url
-def gen_binder_rst(fname, binder_conf):
+def gen_binder_rst(fname, binder_conf, gallery_conf):
"""Generate the RST + link for the Binder badge.
Parameters
@@ -84,7 +104,8 @@ def gen_binder_rst(fname, binder_conf):
rst : str
The reStructuredText for the Binder badge that links to this file.
"""
- binder_url = gen_binder_url(fname, binder_conf)
+ binder_conf = check_binder_conf(binder_conf)
+ binder_url = gen_binder_url(fname, binder_conf, gallery_conf)
rst = (
"\n"
@@ -95,17 +116,75 @@ def gen_binder_rst(fname, binder_conf):
return rst
-def copy_binder_reqs(app):
+def copy_binder_files(app, exception):
+ """Copy all Binder requirements and notebooks files."""
+ if exception is not None:
+ return
+
+ if app.builder.name not in ['html', 'readthedocs']:
+ return
+
+ gallery_conf = app.config.sphinx_gallery_conf
+ binder_conf = check_binder_conf(gallery_conf.get('binder'))
+
+ if not len(binder_conf) > 0:
+ return
+
+ logger.info('copying binder requirements...', color='white')
+ _copy_binder_reqs(app, binder_conf)
+ _copy_binder_notebooks(app)
+
+
+def _copy_binder_reqs(app, binder_conf):
"""Copy Binder requirements files to a "binder" folder in the docs."""
- binder_conf = app.config.sphinx_gallery_conf['binder']
path_reqs = binder_conf.get('dependencies')
- binder_folder = os.path.join(app.builder.outdir, 'binder')
+ binder_folder = os.path.join(app.outdir, 'binder')
if not os.path.isdir(binder_folder):
os.makedirs(binder_folder)
for path in path_reqs:
- sh.copy(os.path.join(app.builder.srcdir, path),
- binder_folder)
+ shutil.copy(os.path.join(app.srcdir, path), binder_folder)
+
+
+def _remove_ipynb_files(path, contents):
+ """Given a list of files in `contents`, remove all files named `ipynb` or
+ directories named `images` and return the result.
+
+ Used with the `shutil` "ignore" keyword to filter out non-ipynb files."""
+ contents_return = []
+ for entry in contents:
+ if entry.endswith('.ipynb'):
+ # Don't include ipynb files
+ pass
+ elif (entry != "images") and os.path.isdir(os.path.join(path, entry)):
+ # Don't include folders not called "images"
+ pass
+ else:
+ # Keep everything else
+ contents_return.append(entry)
+ return contents_return
+
+
+def _copy_binder_notebooks(app):
+ """Copy Jupyter notebooks to the binder notebooks directory.
+
+ Copy each output gallery directory structure but only including the
+ Jupyter notebook files."""
+
+ gallery_conf = app.config.sphinx_gallery_conf
+ gallery_dirs = gallery_conf.get('gallery_dirs')
+ binder_conf = gallery_conf.get('binder')
+ notebooks_dir = os.path.join(app.outdir, binder_conf.get('notebooks_dir'))
+ shutil.rmtree(notebooks_dir, ignore_errors=True)
+ os.makedirs(notebooks_dir)
+
+ iterator = sphinx_compatibility.status_iterator(
+ gallery_dirs, 'copying binder notebooks...', length=len(gallery_dirs))
+
+ for i_folder in iterator:
+ shutil.copytree(os.path.join(app.srcdir, i_folder),
+ os.path.join(notebooks_dir, i_folder),
+ ignore=_remove_ipynb_files)
def check_binder_conf(binder_conf):
@@ -119,7 +198,7 @@ def check_binder_conf(binder_conf):
# Ensure all fields are populated
req_values = ['url', 'org', 'repo', 'branch', 'dependencies']
- optional_values = ['filepath_prefix']
+ optional_values = ['filepath_prefix', 'notebooks_dir', 'use_jupyter_lab']
missing_values = []
for val in req_values:
if binder_conf.get(val) is None:
@@ -150,6 +229,8 @@ def check_binder_conf(binder_conf):
raise ValueError("`dependencies` value should be a list of strings. "
"Got type {}.".format(type(path_reqs)))
+ binder_conf['notebooks_dir'] = binder_conf.get('notebooks_dir',
+ 'notebooks')
path_reqs_filenames = [os.path.basename(ii) for ii in path_reqs]
if not any(ii in path_reqs_filenames for ii in required_reqs_files):
raise ValueError(
diff --git a/sphinx_gallery/docs_resolv.py b/sphinx_gallery/docs_resolv.py
index 5fb2c8f..cdc726b 100644
--- a/sphinx_gallery/docs_resolv.py
+++ b/sphinx_gallery/docs_resolv.py
@@ -117,7 +117,14 @@ def parse_sphinx_docopts(index):
elif value == 'true':
value = True
else:
- value = int(value)
+ try:
+ value = int(value)
+ except ValueError:
+ # In Sphinx 1.7.5, URL_ROOT is a JavaScript fragment.
+ # Ignoring this entry since URL_ROOT is not used
+ # elsewhere.
+ # https://github.com/sphinx-gallery/sphinx-gallery/issues/382
+ continue
docopts[key] = value
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 0864dba..c857bce 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -21,7 +21,7 @@ from .gen_rst import generate_dir_rst, SPHX_GLR_SIG
from .docs_resolv import embed_code_links
from .downloads import generate_zipfiles
from .sorting import NumberOfCodeLinesSortKey
-from .binder import copy_binder_reqs, check_binder_conf
+from .binder import copy_binder_files, check_binder_conf
try:
FileNotFoundError
@@ -236,12 +236,6 @@ def generate_gallery_rst(app):
else:
logger.info("\t- %s: not run", fname)
- # Copy the requirements files for binder
- binder_conf = check_binder_conf(gallery_conf.get('binder'))
- if len(binder_conf) > 0:
- logger.info("copying binder requirements...")
- copy_binder_reqs(app)
-
def touch_empty_backreferences(app, what, name, obj, options, lines):
"""Generate empty back-reference example files
@@ -367,6 +361,7 @@ def setup(app):
app.connect('builder-inited', generate_gallery_rst)
+ app.connect('build-finished', copy_binder_files)
app.connect('build-finished', sumarize_failing_examples)
app.connect('build-finished', embed_code_links)
metadata = {'parallel_read_safe': True,
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 74893eb..11879a0 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -30,6 +30,7 @@ from distutils.version import LooseVersion
from .utils import replace_py_ipynb
+
# Try Python 2 first, otherwise load from Python 3
try:
# textwrap indent only exists in python 3
@@ -83,7 +84,7 @@ from .downloads import CODE_DOWNLOAD
from .py_source_parser import split_code_and_text_blocks
from .notebook import jupyter_notebook, save_notebook
-from .binder import check_binder_conf, copy_binder_reqs, gen_binder_rst
+from .binder import check_binder_conf, gen_binder_rst
try:
basestring
@@ -385,7 +386,7 @@ def scale_image(in_fname, out_fname, max_width, max_height):
# width_sc, height_sc = img.size # necessary if using thumbnail
# insert centered
- thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))
+ thumb = Image.new('RGBA', (max_width, max_height), (255, 255, 255, 255))
pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
thumb.paste(img, pos_insert)
@@ -710,6 +711,7 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
time_m, time_s = divmod(time_elapsed, 60)
example_nb = jupyter_notebook(script_blocks)
save_notebook(example_nb, replace_py_ipynb(example_file))
+
with codecs.open(os.path.join(target_dir, base_image_name + '.rst'),
mode='w', encoding='utf-8') as f:
if time_elapsed >= gallery_conf["min_reported_time"]:
@@ -719,7 +721,8 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
# Generate a binder URL if specified
binder_badge_rst = ''
if len(binder_conf) > 0:
- binder_badge_rst += gen_binder_rst(fname, binder_conf)
+ binder_badge_rst += gen_binder_rst(example_file, binder_conf,
+ gallery_conf)
example_rst += CODE_DOWNLOAD.format(fname,
replace_py_ipynb(fname),
|
sphinx-gallery/sphinx-gallery
|
0496ff3185535e276a8040d013ceb1aad7a4b417
|
diff --git a/sphinx_gallery/tests/test_binder.py b/sphinx_gallery/tests/test_binder.py
index da3b5ea..efca66b 100644
--- a/sphinx_gallery/tests/test_binder.py
+++ b/sphinx_gallery/tests/test_binder.py
@@ -12,25 +12,33 @@ from copy import deepcopy
import pytest
-from sphinx_gallery.binder import (gen_binder_rst, gen_binder_url,
- check_binder_conf)
-from sphinx_gallery.utils import _TempDir
+from sphinx_gallery.binder import gen_binder_url, check_binder_conf
def test_binder():
"""Testing binder URL generation and checks."""
- file_path = 'myfile.py'
- conf1 = {'url': 'http://test1.com', 'org': 'org',
- 'repo': 'repo', 'branch': 'branch',
- 'dependencies': '../requirements.txt'}
- url = gen_binder_url(file_path, conf1)
- assert url == 'http://test1.com/v2/gh/org/repo/branch?filepath=_downloads/myfile.ipynb'
+ file_path = 'blahblah/mydir/myfile.py'
+ conf_base = {'url': 'http://test1.com', 'org': 'org',
+ 'repo': 'repo', 'branch': 'branch',
+ 'dependencies': '../requirements.txt'}
+ conf_base = check_binder_conf(conf_base)
+ gallery_conf_base = {'gallery_dirs': ['mydir'], 'src_dir': 'blahblah'}
+
+ url = gen_binder_url(file_path, conf_base, gallery_conf_base)
+ expected = ('http://test1.com/v2/gh/org/repo/'
+ 'branch?filepath=notebooks/mydir/myfile.ipynb')
+ assert url == expected
# Assert filepath prefix is added
prefix = 'my_prefix/foo'
+ conf1 = deepcopy(conf_base)
conf1['filepath_prefix'] = prefix
- url = gen_binder_url(file_path, conf1)
- assert url == 'http://test1.com/v2/gh/org/repo/branch?filepath={}/_downloads/myfile.ipynb'.format(prefix)
+ url = gen_binder_url(file_path, conf1, gallery_conf_base)
+ expected = ('http://test1.com/v2/gh/org/repo/'
+ 'branch?filepath={}/notebooks/'
+ 'mydir/myfile.ipynb').format(prefix)
+
+ assert url == expected
conf1.pop('filepath_prefix')
# URL must have http
@@ -43,6 +51,8 @@ def test_binder():
# Assert missing params
for key in conf1.keys():
+ if key == 'notebooks_dir':
+ continue
conf3 = deepcopy(conf1)
conf3.pop(key)
with pytest.raises(ValueError) as excinfo:
@@ -56,7 +66,8 @@ def test_binder():
conf3 = deepcopy(conf1)
conf3['dependencies'] = ifile
url = check_binder_conf(conf3)
- excinfo.match(r"Did not find one of `requirements.txt` or `environment.yml`")
+ excinfo.match(r"Did not find one of `requirements.txt` "
+ "or `environment.yml`")
with pytest.raises(ValueError) as excinfo:
conf6 = deepcopy(conf1)
@@ -76,3 +87,20 @@ def test_binder():
conf7['foo'] = 'blah'
url = check_binder_conf(conf7)
excinfo.match(r"Unknown Binder config key")
+
+ # Assert using lab correctly changes URL
+ conf_lab = deepcopy(conf_base)
+ conf_lab['use_jupyter_lab'] = True
+ url = gen_binder_url(file_path, conf_lab, gallery_conf_base)
+ expected = ('http://test1.com/v2/gh/org/repo/'
+ 'branch?urlpath=lab/tree/notebooks/mydir/myfile.ipynb')
+ assert url == expected
+
+ # Assert using static folder correctly changes URL
+ conf_static = deepcopy(conf_base)
+ file_path = 'blahblah/mydir/myfolder/myfile.py'
+ conf_static['notebooks_dir'] = 'ntbk_folder'
+ url = gen_binder_url(file_path, conf_static, gallery_conf_base)
+ expected = ('http://test1.com/v2/gh/org/repo/'
+ 'branch?filepath=ntbk_folder/mydir/myfolder/myfile.ipynb')
+ assert url == expected
diff --git a/sphinx_gallery/tests/test_docs_resolv.py b/sphinx_gallery/tests/test_docs_resolv.py
index 94d4d80..6f57510 100644
--- a/sphinx_gallery/tests/test_docs_resolv.py
+++ b/sphinx_gallery/tests/test_docs_resolv.py
@@ -67,6 +67,27 @@ def test_parse_sphinx_docopts():
'SOURCELINK_SUFFIX': '.txt'
}
+ data_sphinx_175 = '''
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: document.getElementById("documentation_options")\
+ .getAttribute('data-url_root'),
+ VERSION: '2.0.2',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true,
+ SOURCELINK_SUFFIX: '.txt'
+ };
+ </script>
+ '''
+ assert sg.parse_sphinx_docopts(data_sphinx_175) == {
+ 'VERSION': '2.0.2',
+ 'COLLAPSE_INDEX': False,
+ 'FILE_SUFFIX': '.html',
+ 'HAS_SOURCE': True,
+ 'SOURCELINK_SUFFIX': '.txt'
+ }
+
with pytest.raises(ValueError):
sg.parse_sphinx_docopts('empty input')
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 61407fd..64276f5 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -102,7 +102,8 @@ def test_no_warning_simple_config(config_app):
cfg = config_app.config
assert cfg.project == "Sphinx-Gallery <Tests>"
build_warn = config_app._warning.getvalue()
- assert build_warn == ''
+ # ignore 1.8.0 dev bug
+ assert build_warn == '' or 'up extension sphinx.domains.math' in build_warn
@pytest.mark.conf_file(content="""
@@ -155,7 +156,8 @@ def test_config_backreferences(config_app):
assert cfg.sphinx_gallery_conf['backreferences_dir'] == os.path.join(
'gen_modules', 'backreferences')
build_warn = config_app._warning.getvalue()
- assert build_warn == ""
+ # ignore 1.8.0 dev bug
+ assert build_warn == '' or 'up extension sphinx.domains.math' in build_warn
def test_duplicate_files_warn(config_app):
@@ -167,13 +169,14 @@ def test_duplicate_files_warn(config_app):
# No warning because no overlapping names
check_duplicate_filenames(files[:-1])
- warnings = config_app._warning.getvalue()
- assert warnings == ''
+ build_warn = config_app._warning.getvalue()
+ # ignore 1.8.0 dev bug
+ assert build_warn == '' or 'up extension sphinx.domains.math' in build_warn
# Warning because last file is named the same
check_duplicate_filenames(files)
- warnings = config_app._warning.getvalue()
- assert msg.format(m) in warnings
+ build_warn = config_app._warning.getvalue()
+ assert msg.format(m) in build_warn
def _check_order(config_app, key):
@@ -273,3 +276,34 @@ def test_collect_gallery_files(config_app, tmpdir):
[ap.strpath for ap in abs_paths if re.search(r'.*\.py$', ap.strpath)])
assert collected_files == expected_files
+
+
[email protected]_file(content="""
+import os
+import sphinx_gallery
+extensions = ['sphinx_gallery.gen_gallery']
+# General information about the project.
+project = u'Sphinx-Gallery <Tests>'
+
+sphinx_gallery_conf = {
+ 'backreferences_dir' : os.path.join('modules', 'gen'),
+ 'examples_dirs': 'src',
+ 'gallery_dirs': ['ex'],
+ 'binder': {'url': 'http://test1.com', 'org': 'org',
+ 'repo': 'repo', 'branch': 'branch',
+ 'notebooks_dir': 'ntbk_folder',
+ 'dependencies': 'requirements.txt'}
+}""")
+def test_binder_copy_files(config_app, tmpdir):
+ """Test that notebooks are copied properly."""
+ from sphinx_gallery.binder import copy_binder_files, check_binder_conf
+ gallery_conf = config_app.config.sphinx_gallery_conf
+ # Create requirements file
+ with open(os.path.join(config_app.srcdir, 'requirements.txt'), 'w') as ff:
+ pass
+ copy_binder_files(config_app, None)
+
+ for i_file in ['plot_1', 'plot_2', 'plot_3']:
+ assert os.path.exists(os.path.join(
+ config_app.outdir, 'ntbk_folder', gallery_conf['gallery_dirs'][0],
+ i_file+'.ipynb'))
|
JupyterLab support on binder
I just heard about urlpath=lab. Maybe it would be nice to support at one point. I could not find a way to point to a given file with JupyterLab, i.e. using both urlpath=lab&filepath=myipnb. Is this correct @choldgraf?
Thinking about it out loud, in a multi-notebook context (at the moment we are just opening a single notebook in binder but you could imagine pointing to a folder e.g. in the main gallery or it seems like urlpath=lab works like this by default) it feels like the notebooks should be in auto_examples as well as in _downloads. This way the notebook folder structure mirrors the example folder (maybe that does get rid of the duplicated filename problem).
I am not sure why .ipynb can not be seen in https://github.com/sphinx-gallery/sphinx-gallery.github.io/tree/master/auto_examples but this can probably be fixed (at the cost of duplicating .ipynb in the repo, once in _downloads, once in auto_examples which is probably fine ...).
|
0.0
|
0496ff3185535e276a8040d013ceb1aad7a4b417
|
[
"sphinx_gallery/tests/test_binder.py::test_binder",
"sphinx_gallery/tests/test_docs_resolv.py::test_parse_sphinx_docopts"
] |
[
"sphinx_gallery/tests/test_docs_resolv.py::test_embed_code_links_get_data",
"sphinx_gallery/tests/test_docs_resolv.py::test_shelve"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-27 22:09:01+00:00
|
bsd-3-clause
| 5,656 |
|
sphinx-gallery__sphinx-gallery-401
|
diff --git a/doc/advanced_configuration.rst b/doc/advanced_configuration.rst
index 94809a5..775c0ce 100644
--- a/doc/advanced_configuration.rst
+++ b/doc/advanced_configuration.rst
@@ -33,6 +33,7 @@ file:
- ``expected_failing_examples`` (:ref:`dont_fail_exit`)
- ``min_reported_time`` (:ref:`min_reported_time`)
- ``binder`` (:ref:`binder_links`)
+- ``first_notebook_cell`` (:ref:`first_notebook_cell`)
Some options can also be set or overridden on a file-by-file basis:
@@ -392,6 +393,36 @@ Note that for Sphinx < 1.3, the line numbers will not be consistent with the
original file.
+.. _first_notebook_cell:
+
+Add your own first notebook cell
+================================
+
+Sphinx-Gallery adds an extra cell to the beginning of every generated notebook.
+This is often for adding code that is required to run properly in the notebook,
+but not in a ``.py`` file. By default, this text is
+
+.. code-block:: python
+
+ %matplotlib inline
+
+You can choose whatever text you like by modifying the ``first_notebook_cell``
+configuration parameter. For example, the gallery of this documentation
+displays a comment along-side each the code shown above.
+
+.. code-block:: python
+
+ # This cell is added by sphinx-gallery
+ # It can be customized to whatever you like
+ %matplotlib inline
+
+Which is achieved by the following configuration::
+
+ 'first_notebook_cell': ("# This cell is added by sphinx-gallery\n"
+ "# It can be customized to whatever you like\n"
+ "%matplotlib inline")
+
+
.. _disable_all_scripts_download:
Disabling download button of all scripts
diff --git a/doc/conf.py b/doc/conf.py
index 0ab0800..9b34dad 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -348,5 +348,5 @@ sphinx_gallery_conf = {
'dependencies': './binder/requirements.txt',
'notebooks_dir': 'notebooks',
'use_jupyter_lab': True,
- }
+ },
}
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 9e4910d..3a3fd6d 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -62,6 +62,7 @@ DEFAULT_GALLERY_CONF = {
'binder': {},
'image_scrapers': ('matplotlib',),
'reset_modules': ('matplotlib', 'seaborn'),
+ 'first_notebook_cell': '%matplotlib inline'
}
logger = sphinx_compatibility.getLogger('sphinx-gallery')
@@ -103,6 +104,7 @@ def parse_config(app):
gallery_conf = _complete_gallery_conf(
app.config.sphinx_gallery_conf, src_dir, plot_gallery,
abort_on_example_error)
+
# this assures I can call the config in other places
app.config.sphinx_gallery_conf = gallery_conf
app.config.html_static_path.append(glr_path_static())
@@ -170,6 +172,12 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
gallery_conf['reset_modules'] = tuple(resetters)
del resetters
+ # Ensure the first cell text is a string if we have it
+ first_cell = gallery_conf.get("first_notebook_cell")
+ if not isinstance(first_cell, basestring):
+ raise ValueError("The 'first_notebook_cell' parameter must be type str"
+ "found type %s" % type(first_cell))
+ gallery_conf['first_notebook_cell'] = first_cell
return gallery_conf
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index c7489ee..c4e187c 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -579,7 +579,7 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
save_thumbnail(image_path_template, src_file, file_conf, gallery_conf)
- example_nb = jupyter_notebook(script_blocks)
+ example_nb = jupyter_notebook(script_blocks, gallery_conf)
save_notebook(example_nb, replace_py_ipynb(target_file))
return intro, time_elapsed
diff --git a/sphinx_gallery/notebook.py b/sphinx_gallery/notebook.py
index 19d7250..79472b2 100644
--- a/sphinx_gallery/notebook.py
+++ b/sphinx_gallery/notebook.py
@@ -15,6 +15,7 @@ import argparse
import json
import re
import sys
+import copy
from .py_source_parser import split_code_and_text_blocks
from .utils import replace_py_ipynb
@@ -100,17 +101,19 @@ def rst2md(text):
return text
-def jupyter_notebook(script_blocks):
+def jupyter_notebook(script_blocks, gallery_conf):
"""Generate a Jupyter notebook file cell-by-cell
Parameters
----------
- script_blocks: list
- script execution cells
+ script_blocks : list
+ Script execution cells.
+ gallery_conf : dict
+ The sphinx-gallery configuration dictionary.
"""
-
+ first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
work_notebook = jupyter_notebook_skeleton()
- add_code_cell(work_notebook, "%matplotlib inline")
+ add_code_cell(work_notebook, first_cell)
fill_notebook(work_notebook, script_blocks)
return work_notebook
@@ -180,6 +183,7 @@ def python_to_jupyter_cli(args=None, namespace=None):
Takes the same arguments as ArgumentParser.parse_args
"""
+ from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(
description='Sphinx-Gallery Notebook converter')
parser.add_argument('python_src_file', nargs='+',
@@ -191,5 +195,6 @@ def python_to_jupyter_cli(args=None, namespace=None):
for src_file in args.python_src_file:
file_conf, blocks = split_code_and_text_blocks(src_file)
print('Converting {0}'.format(src_file))
- example_nb = jupyter_notebook(blocks)
+ gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)
+ example_nb = jupyter_notebook(blocks, gallery_conf)
save_notebook(example_nb, replace_py_ipynb(src_file))
|
sphinx-gallery/sphinx-gallery
|
573f974bb6fabffcddcf6efef3d7eed6f2ef37f8
|
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index d83259d..221d5dc 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -360,3 +360,14 @@ def test_examples_not_expected_to_pass(sphinx_app_wrapper):
with pytest.raises(ValueError) as excinfo:
sphinx_app_wrapper.build_sphinx_app()
assert "expected to fail, but not failing" in str(excinfo.value)
+
+
[email protected]_file(content="""
+sphinx_gallery_conf = {
+ 'first_notebook_cell': 2,
+}""")
+def test_first_notebook_cell_config(sphinx_app_wrapper):
+ from sphinx_gallery.gen_gallery import parse_config
+ # First cell must be str
+ with pytest.raises(ValueError):
+ parse_config(sphinx_app_wrapper.create_sphinx_app())
diff --git a/sphinx_gallery/tests/test_notebook.py b/sphinx_gallery/tests/test_notebook.py
index 5f7760e..bd7a95d 100644
--- a/sphinx_gallery/tests/test_notebook.py
+++ b/sphinx_gallery/tests/test_notebook.py
@@ -14,6 +14,8 @@ import pytest
import sphinx_gallery.gen_rst as sg
from sphinx_gallery.notebook import (rst2md, jupyter_notebook, save_notebook,
python_to_jupyter_cli)
+from sphinx_gallery.tests.test_gen_rst import gallery_conf
+
try:
FileNotFoundError
except NameError:
@@ -78,10 +80,10 @@ For more details on interpolation see the page `channel_interpolation`.
assert rst2md(rst) == markdown
-def test_jupyter_notebook():
+def test_jupyter_notebook(gallery_conf):
"""Test that written ipython notebook file corresponds to python object"""
file_conf, blocks = sg.split_code_and_text_blocks('tutorials/plot_parse.py')
- example_nb = jupyter_notebook(blocks)
+ example_nb = jupyter_notebook(blocks, gallery_conf)
with tempfile.NamedTemporaryFile('w', delete=False) as f:
save_notebook(example_nb, f.name)
@@ -90,6 +92,13 @@ def test_jupyter_notebook():
assert json.load(fname) == example_nb
finally:
os.remove(f.name)
+ assert example_nb.get('cells')[0]['source'][0] == "%matplotlib inline"
+
+ # Test custom first cell text
+ test_text = '# testing\n%matplotlib notebook'
+ gallery_conf['first_notebook_cell'] = test_text
+ example_nb = jupyter_notebook(blocks, gallery_conf)
+ assert example_nb.get('cells')[0]['source'][0] == test_text
###############################################################################
# Notebook shell utility
diff --git a/sphinx_gallery/tests/test_utils.py b/sphinx_gallery/tests/test_utils.py
index 2d4f6db..2db502e 100644
--- a/sphinx_gallery/tests/test_utils.py
+++ b/sphinx_gallery/tests/test_utils.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
r"""
-Test utility functions
+Test utility functions
==================
@@ -13,7 +13,6 @@ import sphinx_gallery.utils as utils
import pytest
def test_replace_py_ipynb():
-
# Test behavior of function with expected input:
for file_name in ['some/file/name', '/corner.pycase']:
assert utils.replace_py_ipynb(file_name+'.py') == file_name+'.ipynb'
|
matplotlib inline vs notebook
Currently sphinx-gallery puts ["% matplotlib inline"](https://github.com/sphinx-gallery/sphinx-gallery/blob/830a11c6ba5a80a4cbbaff7e2932dd37e81321a5/sphinx_gallery/notebook.py#L113) at the top of all notebooks. Would it be possible to add an option to use "% matplotlib notebook" instead? Interactive elements in figures seem to work better with notebook.
|
0.0
|
573f974bb6fabffcddcf6efef3d7eed6f2ef37f8
|
[
"sphinx_gallery/tests/test_notebook.py::test_jupyter_notebook"
] |
[
"sphinx_gallery/tests/test_notebook.py::test_latex_conversion",
"sphinx_gallery/tests/test_notebook.py::test_convert",
"sphinx_gallery/tests/test_notebook.py::test_with_empty_args",
"sphinx_gallery/tests/test_notebook.py::test_missing_file",
"sphinx_gallery/tests/test_notebook.py::test_file_is_generated",
"sphinx_gallery/tests/test_utils.py::test_replace_py_ipynb"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-13 01:48:36+00:00
|
bsd-3-clause
| 5,657 |
|
sphinx-gallery__sphinx-gallery-480
|
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 4ce518d..4eebf85 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -714,7 +714,8 @@ def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
example_rst += "\n\n|\n\n"
example_rst += code_rst
else:
- example_rst += bcontent + '\n'
+ block_separator = '\n\n' if not bcontent.endswith('\n') else '\n'
+ example_rst += bcontent + block_separator
return example_rst
|
sphinx-gallery/sphinx-gallery
|
50310ed9b86b690067d99f7a4bb98e107f16384e
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index c9d97e3..8ca992c 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -97,6 +97,41 @@ def test_direct_comment_after_docstring():
assert result == expected_result
+def test_rst_block_after_docstring(gallery_conf, tmpdir):
+ """Assert there is a blank line between the docstring and rst blocks."""
+ filename = str(tmpdir.join('temp.py'))
+ with open(filename, 'w') as f:
+ f.write('\n'.join(['"Docstring"',
+ '####################',
+ '# Paragraph 1',
+ '',
+ '####################',
+ '# Paragraph 2',
+ '']))
+ file_conf, blocks = sg.split_code_and_text_blocks(filename)
+
+ assert file_conf == {}
+ assert blocks[0][0] == 'text'
+ assert blocks[1][0] == 'text'
+ assert blocks[2][0] == 'text'
+
+ script_vars = {'execute_script': ''}
+
+ output_blocks, time_elapsed = sg.execute_script(blocks,
+ script_vars,
+ gallery_conf)
+
+ example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
+ assert example_rst == '\n'.join([
+ 'Docstring',
+ '',
+ 'Paragraph 1',
+ '',
+ 'Paragraph 2',
+ '',
+ ''])
+
+
def test_codestr2rst():
"""Test the correct translation of a code block into rst"""
output = sg.codestr2rst('print("hello world")')
|
Adding a ReST block immediately after the module docstring breaks the generated .rst file
## Bug
It appears that both module docstring and ReST blocks are stripped of blank lines at the beginning and end.
Thus the example from https://sphinx-gallery.github.io/syntax.html
~~~
"""
This is my example script
=========================
This example doesn't do much, it just makes a simple plot
"""
###############################################################################
# This is a section header
# ------------------------
~~~
would result in an .rst file with
~~~
This example doesn't do much, it just makes a simple plot
This is a section header
------------------------
~~~
resulting in incorrect rendering of the section due to a missing line before it. A similar effect happens if you have just plain text paragraphs: They will be joined.
This appears to be a common pitfall:
https://github.com/matplotlib/matplotlib/pull/13911
https://github.com/matplotlib/matplotlib/pull/13950
## Proposed fix
Probably the correct fix would be to always add a blank line after the module docstring text in the generated .rst file.
|
0.0
|
50310ed9b86b690067d99f7a4bb98e107f16384e
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-04-27 19:04:02+00:00
|
bsd-3-clause
| 5,658 |
|
sphinx-gallery__sphinx-gallery-487
|
diff --git a/doc/configuration.rst b/doc/configuration.rst
index 582dd66..b5cdb10 100644
--- a/doc/configuration.rst
+++ b/doc/configuration.rst
@@ -26,6 +26,7 @@ file:
- ``default_thumb_file`` (:ref:`custom_default_thumb`)
- ``thumbnail_size`` (:ref:`setting_thumbnail_size`)
- ``line_numbers`` (:ref:`adding_line_numbers`)
+- ``remove_config_comments`` (:ref:`removing_config_comments`)
- ``download_all_examples`` (:ref:`disable_all_scripts_download`)
- ``plot_gallery`` (:ref:`without_execution`)
- ``image_scrapers`` (and the deprecated ``find_mayavi_figures``)
@@ -45,6 +46,9 @@ Some options can also be set or overridden on a file-by-file basis:
- ``# sphinx_gallery_line_numbers`` (:ref:`adding_line_numbers`)
- ``# sphinx_gallery_thumbnail_number`` (:ref:`choosing_thumbnail`)
+See also :ref:`removing_config_comments` to hide these comments from the
+rendered examples.
+
Some options can be set during the build execution step, e.g. using a Makefile:
- ``make html-noplot`` (:ref:`without_execution`)
@@ -428,6 +432,22 @@ setting::
Note that for Sphinx < 1.3, the line numbers will not be consistent with the
original file.
+.. _removing_config_comments
+
+Removing config comments
+========================
+
+Some configurations can be done on a file-by-file basis by adding a special
+comment with the pattern :samp:`# sphinx_gallery_{config} = {value}` to the
+example source files. By default, the source files are parsed as is and thus
+the comment will appear in the example.
+
+To remove the comment from the rendered example set the option::
+
+ sphinx_gallery_conf = {
+ ...
+ 'remove_config_comments': True,
+ }
.. _first_notebook_cell:
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 62d3ed1..1a4ab02 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -70,6 +70,7 @@ DEFAULT_GALLERY_CONF = {
'image_scrapers': ('matplotlib',),
'reset_modules': ('matplotlib', 'seaborn'),
'first_notebook_cell': '%matplotlib inline',
+ 'remove_config_comments': False,
'show_memory': False,
'junit': '',
'log_level': {'backreference_missing': 'warning'},
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index db82ea3..80160dd 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -61,7 +61,7 @@ from . import sphinx_compatibility
from .backreferences import write_backreferences, _thumbnail_div
from .downloads import CODE_DOWNLOAD
from .py_source_parser import (split_code_and_text_blocks,
- get_docstring_and_rest)
+ get_docstring_and_rest, remove_config_comments)
from .notebook import jupyter_notebook, save_notebook
from .binder import check_binder_conf, gen_binder_rst
@@ -642,6 +642,14 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
'target_file': target_file}
file_conf, script_blocks = split_code_and_text_blocks(src_file)
+
+ if gallery_conf['remove_config_comments']:
+ script_blocks = [
+ (label, remove_config_comments(content), line_number)
+ for label, content, line_number in script_blocks
+ ]
+
+
output_blocks, time_elapsed = execute_script(script_blocks,
script_vars,
gallery_conf)
diff --git a/sphinx_gallery/py_source_parser.py b/sphinx_gallery/py_source_parser.py
index 66536f1..94fe085 100644
--- a/sphinx_gallery/py_source_parser.py
+++ b/sphinx_gallery/py_source_parser.py
@@ -26,6 +26,20 @@ SyntaxError
Example script with invalid Python syntax
"""
+# The pattern for in-file config comments is designed to not greedily match
+# newlines at the start and end, except for one newline at the end. This
+# ensures that the matched pattern can be removed from the code without
+# changing the block structure; i.e. empty newlines are preserved, e.g. in
+#
+# a = 1
+#
+# # sphinx_gallery_thumbnail_number = 2
+#
+# b = 2
+INFILE_CONFIG_PATTERN = re.compile(
+ r"^[\ \t]*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)[\ \t]*\n?",
+ re.MULTILINE)
+
def parse_source_file(filename):
"""Parse source file into AST node
@@ -125,12 +139,8 @@ def extract_file_config(content):
"""
Pull out the file-specific config specified in the docstring.
"""
-
- prop_pat = re.compile(
- r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$",
- re.MULTILINE)
file_conf = {}
- for match in re.finditer(prop_pat, content):
+ for match in re.finditer(INFILE_CONFIG_PATTERN, content):
name = match.group(1)
value = match.group(2)
try:
@@ -188,3 +198,19 @@ def split_code_and_text_blocks(source_file):
blocks.append(('code', remaining_content, lineno))
return file_conf, blocks
+
+
+def remove_config_comments(code_block):
+ """
+ Return the content of *code_block* with in-file config comments removed.
+
+ Comment lines of the pattern '# sphinx_gallery_[option] = [val]' are
+ removed, but surrounding empty lines are preserved.
+
+ Parameters
+ ----------
+ code_block : str
+ A code segment.
+ """
+ parsed_code, _ = re.subn(INFILE_CONFIG_PATTERN, '', code_block)
+ return parsed_code
|
sphinx-gallery/sphinx-gallery
|
40d7e652f4bd5be7b5823c2cb8ac881e79af6b50
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 048b613..899a72e 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -36,6 +36,7 @@ CONTENT = [
'And this is a second paragraph',
'"""',
'',
+ '# sphinx_gallery_thumbnail_number = 1'
'# and now comes the module code',
'import logging',
'import sys',
@@ -247,6 +248,53 @@ def test_fail_example(gallery_conf, log_collector):
raise ValueError('Did not stop executing script after error')
+def _generate_rst(gallery_conf, fname, content):
+ """
+ Helper function returning the rST text of a given example content.
+
+ This writes a file gallery_conf['examples_dir']/fname with *content*,
+ creates the corresponding rst file by running generate_file_rst() and
+ returns the generated rST code.
+
+ Parameters
+ ----------
+ gallery_conf
+ A gallery_conf as created by the gallery_conf fixture.
+ fname : str
+ A filename; e.g. 'test.py'. This is relative to
+ gallery_conf['examples_dir']
+ content : str
+ The content of fname.
+
+ Returns
+ -------
+ rst : str
+ The generated rST code.
+ """
+ with codecs.open(os.path.join(gallery_conf['examples_dir'], fname),
+ mode='w', encoding='utf-8') as f:
+ f.write('\n'.join(content))
+ # generate rst file
+ sg.generate_file_rst(fname, gallery_conf['gallery_dir'],
+ gallery_conf['examples_dir'], gallery_conf)
+ # read rst file and check if it contains code output
+ rst_fname = os.path.splitext(fname)[0] + '.rst'
+ with codecs.open(os.path.join(gallery_conf['gallery_dir'], rst_fname),
+ mode='r', encoding='utf-8') as f:
+ rst = f.read()
+ return rst
+
+
+def test_remove_config_comments(gallery_conf):
+ """Test the gallery_conf['remove_config_comments'] setting."""
+ rst = _generate_rst(gallery_conf, 'test.py', CONTENT)
+ assert '# sphinx_gallery_thumbnail_number = 1' in rst
+
+ gallery_conf['remove_config_comments'] = True
+ rst = _generate_rst(gallery_conf, 'test.py', CONTENT)
+ assert '# sphinx_gallery_thumbnail_number = 1' not in rst
+
+
def test_gen_dir_rst(gallery_conf, fakesphinxapp):
"""Test gen_dir_rst."""
print(os.listdir(gallery_conf['examples_dir']))
@@ -273,17 +321,8 @@ def test_pattern_matching(gallery_conf, log_collector):
# create three files in tempdir (only one matches the pattern)
fnames = ['plot_0.py', 'plot_1.py', 'plot_2.py']
for fname in fnames:
- with codecs.open(os.path.join(gallery_conf['examples_dir'], fname),
- mode='w', encoding='utf-8') as f:
- f.write('\n'.join(CONTENT))
- # generate rst file
- sg.generate_file_rst(fname, gallery_conf['gallery_dir'],
- gallery_conf['examples_dir'], gallery_conf)
- # read rst file and check if it contains code output
+ rst = _generate_rst(gallery_conf, fname, CONTENT)
rst_fname = os.path.splitext(fname)[0] + '.rst'
- with codecs.open(os.path.join(gallery_conf['gallery_dir'], rst_fname),
- mode='r', encoding='utf-8') as f:
- rst = f.read()
if re.search(gallery_conf['filename_pattern'],
os.path.join(gallery_conf['gallery_dir'], rst_fname)):
assert code_output in rst
diff --git a/sphinx_gallery/tests/test_py_source_parser.py b/sphinx_gallery/tests/test_py_source_parser.py
index b550bb9..93ac792 100644
--- a/sphinx_gallery/tests/test_py_source_parser.py
+++ b/sphinx_gallery/tests/test_py_source_parser.py
@@ -25,3 +25,41 @@ def test_get_docstring_and_rest(unicode_sample, tmpdir):
fid.write('print("hello")\n')
with pytest.raises(ValueError, match='Could not find docstring'):
sg.get_docstring_and_rest(fname)
+
+
[email protected]('content, file_conf', [
+ ("No config\nin here.",
+ {}),
+ ("# sphinx_gallery_line_numbers = True",
+ {'line_numbers': True}),
+ (" # sphinx_gallery_line_numbers = True ",
+ {'line_numbers': True}),
+ ("#sphinx_gallery_line_numbers=True",
+ {'line_numbers': True}),
+ ("#sphinx_gallery_thumbnail_number\n=\n5",
+ {'thumbnail_number': 5}),
+])
+def test_extract_file_config(content, file_conf):
+ assert sg.extract_file_config(content) == file_conf
+
+
[email protected]('contents, result', [
+ ("No config\nin here.",
+ "No config\nin here."),
+ ("# sphinx_gallery_line_numbers = True",
+ ""),
+ (" # sphinx_gallery_line_numbers = True ",
+ ""),
+ ("#sphinx_gallery_line_numbers=True",
+ ""),
+ ("#sphinx_gallery_thumbnail_number\n=\n5",
+ ""),
+ ("a = 1\n# sphinx_gallery_line_numbers = True\nb = 1",
+ "a = 1\nb = 1"),
+ ("a = 1\n\n# sphinx_gallery_line_numbers = True\n\nb = 1",
+ "a = 1\n\n\nb = 1"),
+ ("# comment\n# sphinx_gallery_line_numbers = True\n# commment 2",
+ "# comment\n# commment 2"),
+])
+def test_remove_config_comments(contents, result):
+ assert sg.remove_config_comments(contents) == result
|
Strip in-file sphinx_gallery directives from code
The in-file comment `# sphinx_gallery_line_numbers` and `# sphinx_gallery_thumbnail_number` are meant to control sphinx gallery behavior. They should not appear in the generated example code, as they do not have any meaning for the reader of the generated example.
I have some proof-of-concept code for this but before I poish it up for a PR, I would like to know if this is a desired feature.
|
0.0
|
40d7e652f4bd5be7b5823c2cb8ac881e79af6b50
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[No",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#sphinx_gallery_line_numbers=True-]",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[#sphinx_gallery_thumbnail_number\\n=\\n5-]",
"sphinx_gallery/tests/test_py_source_parser.py::test_remove_config_comments[a"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_py_source_parser.py::test_get_docstring_and_rest",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[No",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#sphinx_gallery_line_numbers=True-file_conf3]",
"sphinx_gallery/tests/test_py_source_parser.py::test_extract_file_config[#sphinx_gallery_thumbnail_number\\n=\\n5-file_conf4]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-11 22:02:07+00:00
|
bsd-3-clause
| 5,659 |
|
sphinx-gallery__sphinx-gallery-494
|
diff --git a/doc/advanced.rst b/doc/advanced.rst
index db6b69e..0e912be 100644
--- a/doc/advanced.rst
+++ b/doc/advanced.rst
@@ -7,6 +7,10 @@ Advanced usage
This page contains more advanced topics in case you want to understand how
to use Sphinx-Gallery more deeply.
+.. contents:: **Contents**
+ :local:
+ :depth: 2
+
Extend your Makefile for Sphinx-Gallery
=======================================
@@ -62,8 +66,8 @@ and its thumbnail is ``sphx_glr_plot_gallery_version_thumb.png``
.. _custom_scraper:
-Writing a custom image scraper
-==============================
+Write a custom image scraper
+============================
.. warning:: The API for custom scrapers is currently experimental.
@@ -210,19 +214,39 @@ output formats. To use SVG, you can do::
You can also use different formats on a per-image basis, but this requires
writing a customized scraper class or function.
-Contributing scrapers back to Sphinx-gallery
---------------------------------------------
+Integrate custom scrapers with Sphinx-gallery
+---------------------------------------------
+
+Sphinx-gallery plans to internally maintain only two scrapers: matplotlib and
+mayavi. If you have extended or fixed bugs with these scrapers, we welcome PRs
+to improve them!
+
+On the other hand, if you have developed a custom scraper for a different
+plotting library that would be useful to the broader community, we encourage
+you to get it working with Sphinx-gallery and then maintain it externally
+(probably in the package that it scrapes), and then integrate and advertise
+it with Sphinx-gallery. You can:
+
+1. Contribute it to the list of externally supported scrapers located in
+ :ref:`reset_modules`.
+2. Optional: add a custom hook to your module root to simplify scraper use.
+ Taking PyVista as an example, adding ``pyvista._get_sg_image_scraper()``
+ that returns the ``callable`` scraper to be used by Sphinx-gallery allows
+ PyVista users to just use strings as they already can for
+ ``'matplotlib'`` and ``'mayavi'``::
+
+ sphinx_gallery_conf = {
+ ...
+ 'image_scrapers': ('pyvista',)
+ }
-If you've developed a custom scraper for Sphinx-gallery that would be useful
-to the broader community, we encourage you to contribute it to the list of
-natively-supported scrapers located in
-`the scrapers module <https://github.com/sphinx-gallery/sphinx-gallery/blob/master/sphinx_gallery/scrapers.py>`_.
-We welcome PRs!
+ Sphinx-gallery will look for this custom function and call it to get the
+ PyVista image scraper to use before running any examples.
.. _custom_reset:
-Defining resetting behavior for custom visualization libraries
---------------------------------------------------------------
+Define resetting behavior (e.g., for custom libraries)
+======================================================
Sphinx-gallery natively supports resetting ``matplotlib`` and ``seaborn``.
However, if you'd like to support resetting for other libraries (or would like
diff --git a/doc/configuration.rst b/doc/configuration.rst
index fdae0a3..d024880 100644
--- a/doc/configuration.rst
+++ b/doc/configuration.rst
@@ -702,55 +702,38 @@ Image scrapers
Image scrapers are plugins that allow Sphinx-gallery to detect images produced
during execution of your examples, and then embed them into documentation.
Scrapers can be activated by appending scraper names to the ``image_scrapers``
-field of your Sphinx-gallery configuration (see below). There are currently
-two native image scrapers in Sphinx-gallery (Matplotlib and Mayavi).
+field of your Sphinx-gallery configuration:
-By default, Sphinx-gallery will only detect new :mod:`matplotlib.pyplot`
-figures. This behavior is equivalent to the default of::
+- By default, Sphinx-gallery will only detect new :mod:`matplotlib.pyplot`
+ figures. This behavior is equivalent to the default of::
sphinx_gallery_conf = {
...
'image_scrapers': ('matplotlib',),
}
-Built-in support is also provided for finding :mod:`Mayavi <mayavi.mlab>`
-figures. Enable this feature with the following configuration::
+- Built-in support is also provided for finding :mod:`Mayavi <mayavi.mlab>`
+ figures. Enable this feature with the following configuration::
sphinx_gallery_conf = {
...
'image_scrapers': ('matplotlib', 'mayavi'),
}
-.. note:: The parameter ``find_mayavi_figures`` which can also be used to
- extract Mayavi figures is **deprecated** in version 0.2+,
- and will be removed in a future release.
+- Some external packages maintain their own Sphinx-Gallery image
+ scrapers. If you are using these projects, then it is possible to
+ leverage their scrapers with Sphinx-Gallery. To do so, view their
+ documentation on how to integrate with Sphinx-gallery via the
+ ``'image_scrapers'`` configuration value:
+ * `PyVista <https://github.com/pyvista/pyvista>`_
+ * `PyGMT <https://github.com/GenericMappingTools/pygmt>`_
-External scrapers
-^^^^^^^^^^^^^^^^^
-
-Several external packages maintain their own Sphinx-Gallery image
-scrapers. If you are using these projects, then it is possible to
-leverage their scrapers with Sphinx-Gallery. These packages include:
-
-* `PyVista <https://github.com/pyvista/pyvista>`_
-* `PyGMT <https://github.com/GenericMappingTools/pygmt>`_
-
-
-Custom scrapers
-^^^^^^^^^^^^^^^
-
-It is possible to write custom scrapers for images generated by packages
-outside of those supported natively in Sphinx-gallery. This is accomplished
-by writing your own Python function to define how to detect and retrieve
-images produced by an arbitrary package. For instructions on how to accomplish
-this, see :ref:`custom_scraper`.
-
-.. note:: If you've developed a custom scraper for Sphinx-gallery that would
- be useful to the broader community, we encourage you to contribute
- it to the list of natively-supported scrapers located in
- `the scrapers module <https://github.com/sphinx-gallery/sphinx-gallery/blob/master/sphinx_gallery/scrapers.py>`_.
- We welcome PRs!
+- It is possible to write custom scrapers for images generated by packages
+ outside of those supported natively in Sphinx-gallery. This is accomplished
+ by writing your own Python function to define how to detect and retrieve
+ images produced by an arbitrary package. For instructions, see
+ :ref:`custom_scraper`.
.. _reset_modules:
diff --git a/examples/plot_unicode_everywhere.py b/examples/plot_unicode_everywhere.py
index 26158c5..a739c6c 100644
--- a/examples/plot_unicode_everywhere.py
+++ b/examples/plot_unicode_everywhere.py
@@ -25,6 +25,7 @@ s = np.random.rand(*x.shape) * 800 + 500
plt.scatter(x, y, s, marker=r'$\oint$')
x = np.random.randn(60) * 7 - 4
y = np.random.randn(60) * 3 - 2
+s = s[:x.size]
plt.scatter(x, y, s, alpha=0.5, c='g', marker=r'$\clubsuit$')
plt.xlabel('⇒')
plt.ylabel('⇒')
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 1a4ab02..42cc3d3 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -14,6 +14,7 @@ from __future__ import division, print_function, absolute_import
import codecs
import copy
from datetime import timedelta, datetime
+from importlib import import_module
import re
import os
from xml.sax.saxutils import quoteattr, escape
@@ -145,10 +146,19 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
scrapers = list(scrapers)
for si, scraper in enumerate(scrapers):
if isinstance(scraper, basestring):
- if scraper not in _scraper_dict:
- raise ValueError('Unknown image scraper named %r' % (scraper,))
- scrapers[si] = _scraper_dict[scraper]
- elif not callable(scraper):
+ if scraper in _scraper_dict:
+ scraper = _scraper_dict[scraper]
+ else:
+ orig_scraper = scraper
+ try:
+ scraper = import_module(scraper)
+ scraper = getattr(scraper, '_get_sg_image_scraper')
+ scraper = scraper()
+ except Exception as exp:
+ raise ValueError('Unknown image scraper %r, got:\n%s'
+ % (orig_scraper, exp))
+ scrapers[si] = scraper
+ if not callable(scraper):
raise ValueError('Scraper %r was not callable' % (scraper,))
gallery_conf['image_scrapers'] = tuple(scrapers)
del scrapers
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 80160dd..1493b21 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -396,7 +396,10 @@ def _memory_usage(func, gallery_conf):
assert callable(func)
mem, out = memory_usage(func, max_usage=True, retval=True,
multiprocess=True)
- mem = mem[0]
+ try:
+ mem = mem[0] # old MP always returned a list
+ except TypeError: # 'float' object is not subscriptable
+ pass
else:
out = func()
mem = 0
diff --git a/sphinx_gallery/scrapers.py b/sphinx_gallery/scrapers.py
index b0840b3..d43147b 100644
--- a/sphinx_gallery/scrapers.py
+++ b/sphinx_gallery/scrapers.py
@@ -6,6 +6,9 @@ Scrapers for embedding images
=============================
Collect images that have been produced by code blocks.
+
+The only scrapers we support are Matplotlib and Mayavi, others should
+live in modules that will support them (e.g., PyVista, Plotly).
"""
import os
|
sphinx-gallery/sphinx-gallery
|
8c630d0bbf6b858847162ef5b43376a4dc1796ce
|
diff --git a/sphinx_gallery/tests/test_scrapers.py b/sphinx_gallery/tests/test_scrapers.py
index 1d2f212..5028c4d 100644
--- a/sphinx_gallery/tests/test_scrapers.py
+++ b/sphinx_gallery/tests/test_scrapers.py
@@ -4,6 +4,7 @@ import pytest
import numpy as np
from PIL import Image
+import sphinx_gallery
from sphinx_gallery.gen_gallery import _complete_gallery_conf
from sphinx_gallery.scrapers import (figure_rst, mayavi_scraper, SINGLE_IMAGE,
matplotlib_scraper, ImagePathIterator,
@@ -30,7 +31,7 @@ class matplotlib_svg_scraper():
@pytest.mark.parametrize('ext', ('png', 'svg'))
def test_save_matplotlib_figures(gallery_conf, ext):
- """Test matplotlib figure save"""
+ """Test matplotlib figure save."""
if ext == 'svg':
gallery_conf['image_scrapers'] = (matplotlib_svg_scraper(),)
import matplotlib.pyplot as plt # nest these so that Agg can be set
@@ -115,16 +116,30 @@ def test_save_mayavi_figures(gallery_conf):
pixels = np.asarray(img.convert("RGB"))
assert (pixels == [255, 245, 240]).all()
+
+def _custom_func(x, y, z):
+ return ''
+
+
+def test_custom_scraper(gallery_conf, monkeypatch):
+ """Test custom scrapers."""
# custom finders
- gallery_conf.update(image_scrapers=[lambda x, y, z: ''])
- image_rst = save_figures(block, block_vars, gallery_conf)
- assert len(image_path_iterator) == 3
+ with monkeypatch.context() as m:
+ m.setattr(sphinx_gallery, '_get_sg_image_scraper',
+ lambda: _custom_func, raising=False)
+ for cust in (_custom_func, 'sphinx_gallery'):
+ gallery_conf.update(image_scrapers=[cust])
+ fname_template = os.path.join(gallery_conf['gallery_dir'],
+ 'image{0}.png')
+ image_path_iterator = ImagePathIterator(fname_template)
+ block = ('',) * 3
+ block_vars = dict(image_path_iterator=image_path_iterator)
# degenerate
gallery_conf.update(image_scrapers=['foo'])
+ complete_args = (gallery_conf, gallery_conf['gallery_dir'], True, False)
with pytest.raises(ValueError, match='Unknown image scraper'):
- _complete_gallery_conf(
- gallery_conf, gallery_conf['gallery_dir'], True, False)
+ _complete_gallery_conf(*complete_args)
gallery_conf.update(
image_scrapers=[lambda x, y, z: y['image_path_iterator'].next()])
with pytest.raises(RuntimeError, match='did not produce expected image'):
@@ -132,6 +147,18 @@ def test_save_mayavi_figures(gallery_conf):
gallery_conf.update(image_scrapers=[lambda x, y, z: 1.])
with pytest.raises(TypeError, match='was not a string'):
save_figures(block, block_vars, gallery_conf)
+ # degenerate string interface
+ gallery_conf.update(image_scrapers=['sphinx_gallery'])
+ with monkeypatch.context() as m:
+ m.setattr(sphinx_gallery, '_get_sg_image_scraper', 'foo',
+ raising=False)
+ with pytest.raises(ValueError, match='^Unknown image.*\n.*callable'):
+ _complete_gallery_conf(*complete_args)
+ with monkeypatch.context() as m:
+ m.setattr(sphinx_gallery, '_get_sg_image_scraper', lambda: 'foo',
+ raising=False)
+ with pytest.raises(ValueError, match='^Scraper.*was not callable'):
+ _complete_gallery_conf(*complete_args)
@pytest.mark.parametrize('ext', _KNOWN_IMG_EXTS)
|
Support for Plotly
Nothing is much clear about the support of sphinx gallery for plotly. It is clear that it just supports matplotlib, seaborn and mayavi. Perhaps more clearity on is it possible to use sphinx gallery for showing plots on plotly?
|
0.0
|
8c630d0bbf6b858847162ef5b43376a4dc1796ce
|
[
"sphinx_gallery/tests/test_scrapers.py::test_custom_scraper"
] |
[
"sphinx_gallery/tests/test_scrapers.py::test_save_matplotlib_figures[png]",
"sphinx_gallery/tests/test_scrapers.py::test_save_matplotlib_figures[svg]",
"sphinx_gallery/tests/test_scrapers.py::test_figure_rst[png]",
"sphinx_gallery/tests/test_scrapers.py::test_figure_rst[svg]",
"sphinx_gallery/tests/test_scrapers.py::test_iterator"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-20 15:03:55+00:00
|
bsd-3-clause
| 5,660 |
|
sphinx-gallery__sphinx-gallery-510
|
diff --git a/doc/getting_started.rst b/doc/getting_started.rst
index 4404d6e..bdb0e3c 100644
--- a/doc/getting_started.rst
+++ b/doc/getting_started.rst
@@ -39,7 +39,7 @@ Let's say your Python project looks like this:
└── examples
├── plot_example.py
├── example.py
- └── README.txt
+ └── README.txt (or .rst)
Your Python module is in ``my_python_module``, examples for how to use it are
in ``examples`` and the ``doc`` folder holds the base documentation
@@ -59,7 +59,8 @@ Structure the examples folder
In order for Sphinx-Gallery to build a gallery from your ``examples`` folder,
this folder must have the following things:
-* **The Gallery Header** (``README.txt``). A file called ``README.txt`` that
+* **The Gallery Header** (``README.txt``). A file called ``README.txt``
+ or ``README.rst`` that
contains rST that will be used as a header for the gallery generated from
this folder. It must have at least a title. For example::
diff --git a/mayavi_examples/README.txt b/mayavi_examples/README.rst
similarity index 100%
rename from mayavi_examples/README.txt
rename to mayavi_examples/README.rst
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 36c35fa..26a53b7 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -14,29 +14,26 @@ from __future__ import division, print_function, absolute_import
import codecs
import copy
from datetime import timedelta, datetime
+from distutils.version import LooseVersion
from importlib import import_module
import re
import os
from xml.sax.saxutils import quoteattr, escape
+import sphinx
from sphinx.util.console import red
from . import sphinx_compatibility, glr_path_static, __version__ as _sg_version
-from .utils import _replace_md5
+from .utils import _replace_md5, Bunch
from .backreferences import finalize_backreferences
from .gen_rst import (generate_dir_rst, SPHX_GLR_SIG, _get_memory_base,
- extract_intro_and_title, get_docstring_and_rest)
+ extract_intro_and_title, get_docstring_and_rest,
+ _get_readme)
from .scrapers import _scraper_dict, _reset_dict
from .docs_resolv import embed_code_links
from .downloads import generate_zipfiles
from .sorting import NumberOfCodeLinesSortKey
from .binder import copy_binder_files
-try:
- FileNotFoundError
-except NameError:
- # Python2
- FileNotFoundError = IOError
-
try:
basestring
except NameError:
@@ -91,7 +88,7 @@ def parse_config(app):
lang = app.builder.config.highlight_language
gallery_conf = _complete_gallery_conf(
app.config.sphinx_gallery_conf, src_dir, plot_gallery,
- abort_on_example_error, lang, app.builder.name)
+ abort_on_example_error, lang, app.builder.name, app)
# this assures I can call the config in other places
app.config.sphinx_gallery_conf = gallery_conf
@@ -101,7 +98,7 @@ def parse_config(app):
def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
abort_on_example_error, lang='python',
- builder_name='html'):
+ builder_name='html', app=None):
gallery_conf = copy.deepcopy(DEFAULT_GALLERY_CONF)
gallery_conf.update(sphinx_gallery_conf)
if sphinx_gallery_conf.get('find_mayavi_figures', False):
@@ -114,6 +111,11 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
gallery_conf.update(plot_gallery=plot_gallery)
gallery_conf.update(abort_on_example_error=abort_on_example_error)
gallery_conf['src_dir'] = src_dir
+ # Old Sphinx can't handle pickling app, so let's just expose the one
+ # thing we need internally
+ if LooseVersion(sphinx.__version__) < LooseVersion('1.8'):
+ app = Bunch(config=app.config) if app is not None else app
+ gallery_conf['app'] = app
if gallery_conf.get("mod_example_dir", False):
backreferences_warning = """\n========
@@ -194,8 +196,8 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
return gallery_conf
-def get_subsections(srcdir, examples_dir, sortkey):
- """Return the list of subsections of a gallery
+def get_subsections(srcdir, examples_dir, gallery_conf):
+ """Return the list of subsections of a gallery.
Parameters
----------
@@ -203,18 +205,18 @@ def get_subsections(srcdir, examples_dir, sortkey):
absolute path to directory containing conf.py
examples_dir : str
path to the examples directory relative to conf.py
- sortkey : :func:`python:callable`
- The sort key to use.
+ gallery_conf : dict
+ The gallery configuration.
Returns
-------
out : list
sorted list of gallery subsection folder names
-
"""
+ sortkey = gallery_conf['subsection_order']
subfolders = [subfolder for subfolder in os.listdir(examples_dir)
- if os.path.exists(os.path.join(
- examples_dir, subfolder, 'README.txt'))]
+ if _get_readme(os.path.join(examples_dir, subfolder),
+ gallery_conf, raise_error=False) is not None]
base_examples_dir_path = os.path.relpath(examples_dir, srcdir)
subfolders_with_path = [os.path.join(base_examples_dir_path, item)
for item in subfolders]
@@ -269,15 +271,8 @@ def generate_gallery_rst(app):
examples_dir = os.path.join(app.builder.srcdir, examples_dir)
gallery_dir = os.path.join(app.builder.srcdir, gallery_dir)
- if not os.path.exists(os.path.join(examples_dir, 'README.txt')):
- raise FileNotFoundError("Main example directory {0} does not "
- "have a README.txt file. Please write "
- "one to introduce your gallery."
- .format(examples_dir))
-
# Here we don't use an os.walk, but we recurse only twice: flat is
# better than nested.
-
this_fhindex, this_computation_times = generate_dir_rst(
examples_dir, gallery_dir, gallery_conf, seen_backrefs)
@@ -292,8 +287,7 @@ def generate_gallery_rst(app):
fhindex.write(":orphan:\n\n" + this_fhindex)
for subsection in get_subsections(
- app.builder.srcdir, examples_dir,
- gallery_conf['subsection_order']):
+ app.builder.srcdir, examples_dir, gallery_conf):
src_dir = os.path.join(examples_dir, subsection)
target_dir = os.path.join(gallery_dir, subsection)
this_fhindex, this_computation_times = \
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index e303c66..0bf420a 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -40,7 +40,7 @@ try:
from textwrap import indent
except ImportError:
def indent(text, prefix, predicate=None):
- """Adds 'prefix' to the beginning of selected lines in 'text'.
+ """Add 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
@@ -56,6 +56,9 @@ except ImportError:
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
+ FileNotFoundError = IOError
+
+
import sphinx
from . import glr_path_static
@@ -286,15 +289,28 @@ def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf):
scale_image(img, thumb_file, *gallery_conf["thumbnail_size"])
-def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
- """Generate the gallery reStructuredText for an example directory"""
+def _get_readme(dir_, gallery_conf, raise_error=True):
+ extensions = ['.txt'] + sorted(gallery_conf['app'].config['source_suffix'])
+ for ext in extensions:
+ fname = os.path.join(dir_, 'README' + ext)
+ if os.path.isfile(fname):
+ return fname
+ if raise_error:
+ raise FileNotFoundError(
+ "Example directory {0} does not have a README file with one "
+ "of the expected file extensions {1}. Please write one to "
+ "introduce your gallery.".format(dir_, extensions))
+ return None
+
+def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
+ """Generate the gallery reStructuredText for an example directory."""
head_ref = os.path.relpath(target_dir, gallery_conf['src_dir'])
fhindex = """\n\n.. _sphx_glr_{0}:\n\n""".format(
head_ref.replace(os.path.sep, '_'))
- with codecs.open(os.path.join(src_dir, 'README.txt'), 'r',
- encoding='utf-8') as fid:
+ fname = _get_readme(src_dir, gallery_conf)
+ with codecs.open(fname, 'r', encoding='utf-8') as fid:
fhindex += fid.read()
# Add empty lines to avoid bug in issue #165
fhindex += "\n\n"
diff --git a/sphinx_gallery/utils.py b/sphinx_gallery/utils.py
index 60f0ccf..afee07f 100644
--- a/sphinx_gallery/utils.py
+++ b/sphinx_gallery/utils.py
@@ -115,3 +115,11 @@ def _replace_md5(fname_new, fname_old=None, method='move'):
else:
copyfile(fname_new, fname_old)
assert os.path.isfile(fname_old)
+
+
+class Bunch(dict):
+ """Dictionary-like object that exposes its keys as attributes."""
+
+ def __init__(self, **kwargs): # noqa: D102
+ dict.__init__(self, kwargs)
+ self.__dict__ = self
|
sphinx-gallery/sphinx-gallery
|
b62bd3d64ea83ceec0394ee5582347f21d75070c
|
diff --git a/sphinx_gallery/tests/conftest.py b/sphinx_gallery/tests/conftest.py
index 77d7e04..ff49c55 100644
--- a/sphinx_gallery/tests/conftest.py
+++ b/sphinx_gallery/tests/conftest.py
@@ -5,14 +5,18 @@ Pytest fixtures
from __future__ import division, absolute_import, print_function
import collections
-import logging
import pytest
+import sphinx
import sphinx_gallery.docs_resolv
import sphinx_gallery.gen_gallery
import sphinx_gallery.gen_rst
-from sphinx_gallery import sphinx_compatibility
+
+
+def pytest_report_header(config, startdir):
+ """Add information to the pytest run header."""
+ return 'Sphinx: %s (%s)' % (sphinx.__version__, sphinx.__file__)
Params = collections.namedtuple('Params', 'args kwargs')
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 20da966..c8a2877 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -273,7 +273,7 @@ def test_example_sorting_title(sphinx_app_wrapper):
_check_order(sphinx_app, 'title')
-def test_collect_gallery_files(sphinx_app_wrapper, tmpdir):
+def test_collect_gallery_files(tmpdir):
"""Test that example files are collected properly."""
rel_filepaths = ['examples/file1.py',
'examples/test.rst',
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index b7ef18f..61afc12 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -12,6 +12,7 @@ import io
import tempfile
import re
import os
+import shutil
import zipfile
import codeop
@@ -20,9 +21,15 @@ import pytest
import sphinx_gallery.gen_rst as sg
from sphinx_gallery import downloads
from sphinx_gallery.gen_gallery import generate_dir_rst, _complete_gallery_conf
-from sphinx_gallery.utils import _TempDir
+from sphinx_gallery.utils import _TempDir, Bunch
from sphinx_gallery.scrapers import ImagePathIterator
+try:
+ FileNotFoundError
+except NameError:
+ # Python2
+ FileNotFoundError = IOError
+
CONTENT = [
'"""',
'================',
@@ -223,8 +230,7 @@ def test_extract_intro_and_title():
def test_md5sums():
- """Test md5sum check functions work on know file content"""
-
+ """Test md5sum check functions work on know file content."""
with tempfile.NamedTemporaryFile('wb', delete=False) as f:
f.write(b'Local test\n')
try:
@@ -246,15 +252,17 @@ def test_md5sums():
@pytest.fixture
def gallery_conf(tmpdir):
- """Sets up a test sphinx-gallery configuration"""
- gallery_conf = _complete_gallery_conf({}, str(tmpdir), True, False)
+ """Set up a test sphinx-gallery configuration."""
+ app = Bunch()
+ app.config = dict(source_suffix={'.rst': None})
+ gallery_conf = _complete_gallery_conf({}, str(tmpdir), True, False,
+ app=app)
gallery_conf.update(examples_dir=_TempDir(), gallery_dir=str(tmpdir))
return gallery_conf
def test_fail_example(gallery_conf, log_collector):
- """Test that failing examples are only executed until failing block"""
-
+ """Test that failing examples are only executed until failing block."""
gallery_conf.update(filename_pattern='raise.py')
failing_code = CONTENT + ['#' * 79,
@@ -281,8 +289,7 @@ def test_fail_example(gallery_conf, log_collector):
def _generate_rst(gallery_conf, fname, content):
- """
- Helper function returning the rST text of a given example content.
+ """Return the rST text of a given example content.
This writes a file gallery_conf['examples_dir']/fname with *content*,
creates the corresponding rst file by running generate_file_rst() and
@@ -327,21 +334,28 @@ def test_remove_config_comments(gallery_conf):
assert '# sphinx_gallery_thumbnail_number = 1' not in rst
-def test_gen_dir_rst(gallery_conf, fakesphinxapp):
[email protected]('ext', ('.txt', '.rst', '.bad'))
+def test_gen_dir_rst(gallery_conf, fakesphinxapp, ext):
"""Test gen_dir_rst."""
print(os.listdir(gallery_conf['examples_dir']))
fname_readme = os.path.join(gallery_conf['src_dir'], 'README.txt')
with open(fname_readme, 'wb') as fid:
fid.write(u"Testing\n=======\n\nÓscar here.".encode('utf-8'))
+ fname_out = os.path.splitext(fname_readme)[0] + ext
+ if fname_readme != fname_out:
+ shutil.move(fname_readme, fname_out)
args = (gallery_conf['src_dir'], gallery_conf['gallery_dir'],
gallery_conf, [])
- out = generate_dir_rst(*args)
- assert u"Óscar here" in out[0]
+ if ext == '.bad': # not found with correct ext
+ with pytest.raises(FileNotFoundError, match='does not have a README'):
+ generate_dir_rst(*args)
+ else:
+ out = generate_dir_rst(*args)
+ assert u"Óscar here" in out[0]
def test_pattern_matching(gallery_conf, log_collector):
- """Test if only examples matching pattern are executed"""
-
+ """Test if only examples matching pattern are executed."""
gallery_conf.update(filename_pattern=re.escape(os.sep) + 'plot_0')
code_output = ('\n Out:\n\n .. code-block:: none\n'
@@ -383,7 +397,7 @@ def test_thumbnail_number(test_str):
def test_zip_notebooks(gallery_conf):
- """Test generated zipfiles are not corrupt"""
+ """Test generated zipfiles are not corrupt."""
gallery_conf.update(examples_dir='examples')
examples = downloads.list_downloadable_sources(
gallery_conf['examples_dir'])
@@ -395,8 +409,7 @@ def test_zip_notebooks(gallery_conf):
def test_rst_example(gallery_conf):
- """Test generated rst file includes the correct paths for binder"""
-
+ """Test generated rst file includes the correct paths for binder."""
gallery_conf.update(binder={'org': 'sphinx-gallery',
'repo': 'sphinx-gallery.github.io',
'binderhub_url': 'https://mybinder.org',
@@ -448,7 +461,6 @@ def test_output_indentation(gallery_conf):
assert output_test_string == test_string.replace(r"\n", "\n")
-
class TestLoggingTee:
def setup(self):
self.output_file = io.StringIO()
@@ -510,6 +522,5 @@ class TestLoggingTee:
# TODO: test that broken thumbnail does appear when needed
-# TODO: test that examples are not executed twice
# TODO: test that examples are executed after a no-plot and produce
# the correct image in the thumbnail
diff --git a/sphinx_gallery/tests/test_notebook.py b/sphinx_gallery/tests/test_notebook.py
index 0d5b9f0..e3180c3 100644
--- a/sphinx_gallery/tests/test_notebook.py
+++ b/sphinx_gallery/tests/test_notebook.py
@@ -14,7 +14,7 @@ import pytest
import sphinx_gallery.gen_rst as sg
from sphinx_gallery.notebook import (rst2md, jupyter_notebook, save_notebook,
python_to_jupyter_cli)
-from sphinx_gallery.tests.test_gen_rst import gallery_conf
+from sphinx_gallery.tests.test_gen_rst import gallery_conf # noqa
try:
FileNotFoundError
|
Allow .rst extension for README files
https://github.com/sphinx-gallery/sphinx-gallery/blob/cd6eaed237b00ed505b3faa095694c2d66afe49d/sphinx_gallery/gen_gallery.py#L272
Currently, SG forces the required README files to have the `.txt` extension. I imagine almost every project using SG is formatting these README files in RST so allowing an `.rst` extension makes sense.
Why does this matter? It makes viewing the example directory on GitHub a bit more user-friendly as GitHub will render RST properly when the file has an `.rst` extension. See this page for example: https://github.com/pyvista/pyvista/tree/master/examples
A newcomer to the project might explore the example directory in the repo before heading to the gallery on the docs and I'd much rather have a rendered page there than unwelcoming, raw RST
|
0.0
|
b62bd3d64ea83ceec0394ee5582347f21d75070c
|
[
"sphinx_gallery/tests/test_gen_gallery.py::test_default_config",
"sphinx_gallery/tests/test_gen_gallery.py::test_no_warning_simple_config",
"sphinx_gallery/tests/test_gen_gallery.py::test_config_old_backreferences_conf",
"sphinx_gallery/tests/test_gen_gallery.py::test_config_backreferences",
"sphinx_gallery/tests/test_gen_gallery.py::test_duplicate_files_warn",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_default",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_filesize",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_filename",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_title",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_binder_copy_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_expected_failing_examples_were_executed",
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_notebook.py::test_latex_conversion",
"sphinx_gallery/tests/test_notebook.py::test_convert",
"sphinx_gallery/tests/test_notebook.py::test_jupyter_notebook",
"sphinx_gallery/tests/test_notebook.py::test_with_empty_args",
"sphinx_gallery/tests/test_notebook.py::test_missing_file",
"sphinx_gallery/tests/test_notebook.py::test_file_is_generated"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-06-21 15:29:04+00:00
|
bsd-3-clause
| 5,661 |
|
sphinx-gallery__sphinx-gallery-511
|
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index ab1b204..4c44d49 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -196,7 +196,7 @@ BACKREF_THUMBNAIL_TEMPLATE = THUMBNAIL_TEMPLATE + """
def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,
check=True):
- """Generates RST to place a thumbnail in a gallery"""
+ """Generate RST to place a thumbnail in a gallery."""
thumb, _ = _find_image_ext(
os.path.join(target_dir, 'images', 'thumb',
'sphx_glr_%s_thumb.png' % fname[:-3]))
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 0bf420a..45991d4 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -196,9 +196,31 @@ def codestr2rst(codestr, lang='python', lineno=None):
return code_directive + indented_block
-def extract_intro_and_title(filename, docstring):
- """ Extract the first paragraph of module-level docstring. max:95 char"""
+def _regroup(x):
+ x = x.groups()
+ return x[0] + x[1].split('.')[-1] + x[2]
+
+
+def _sanitize_rst(string):
+ """Use regex to remove at least some sphinx directives."""
+ # :class:`a.b.c <thing here>`, :ref:`abc <thing here>` --> thing here
+ p, e = r'(\s|^):[^:\s]+:`', r'`(\W|$)'
+ string = re.sub(p + r'\S+\s*<([^>`]+)>' + e, r'\1\2\3', string)
+ # :class:`~a.b.c` --> c
+ string = re.sub(p + r'~([^`]+)' + e, _regroup, string)
+ # :class:`a.b.c` --> a.b.c
+ string = re.sub(p + r'([^`]+)' + e, r'\1\2\3', string)
+
+ # ``whatever thing`` --> whatever thing
+ p = r'(\s|^)`'
+ string = re.sub(p + r'`([^`]+)`' + e, r'\1\2\3', string)
+ # `whatever thing` --> whatever thing
+ string = re.sub(p + r'([^`]+)' + e, r'\1\2\3', string)
+ return string
+
+def extract_intro_and_title(filename, docstring):
+ """Extract and clean the first paragraph of module-level docstring."""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
@@ -223,9 +245,9 @@ def extract_intro_and_title(filename, docstring):
intro_paragraph = title if len(paragraphs) < 2 else paragraphs[1]
# Concatenate all lines of the first paragraph and truncate at 95 chars
intro = re.sub('\n', ' ', intro_paragraph)
+ intro = _sanitize_rst(intro)
if len(intro) > 95:
intro = intro[:95] + '...'
-
return intro, title
@@ -709,7 +731,6 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
for label, content, line_number in script_blocks
]
-
output_blocks, time_elapsed = execute_script(script_blocks,
script_vars,
gallery_conf)
|
sphinx-gallery/sphinx-gallery
|
2fbf59555dc109b22b0e8533e681652a03b99985
|
diff --git a/sphinx_gallery/tests/test_backreferences.py b/sphinx_gallery/tests/test_backreferences.py
index 1b15dfe..f150fb2 100644
--- a/sphinx_gallery/tests/test_backreferences.py
+++ b/sphinx_gallery/tests/test_backreferences.py
@@ -8,21 +8,13 @@ from __future__ import division, absolute_import, print_function
import pytest
import sphinx_gallery.backreferences as sg
+from sphinx_gallery.gen_rst import _sanitize_rst
-def test_thumbnail_div():
- """Test if the thumbnail div generates the correct string"""
-
- with pytest.raises(RuntimeError, match='internal sphinx-gallery thumb'):
- html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
- '<"test">')
- html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
- '<"test">', check=False)
-
- reference = r"""
+REFERENCE = r"""
.. raw:: html
- <div class="sphx-glr-thumbcontainer" tooltip="<"test">">
+ <div class="sphx-glr-thumbcontainer" tooltip="{0}">
.. only:: html
@@ -32,44 +24,45 @@ def test_thumbnail_div():
.. raw:: html
- </div>
+ </div>{1}
"""
- assert html_div == reference
-
-
-def test_backref_thumbnail_div():
- """Test if the thumbnail div generates the correct string"""
-
- html_div = sg._thumbnail_div('fake_dir', '',
- 'test_file.py', 'test formating',
- is_backref=True, check=False)
-
- reference = """
-.. raw:: html
-
- <div class="sphx-glr-thumbcontainer" tooltip="test formating">
-
-.. only:: html
-
- .. figure:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
-
- :ref:`sphx_glr_fake_dir_test_file.py`
-
-.. raw:: html
- </div>
[email protected]('content, tooltip, is_backref', [
+ # HTML sanitizing
+ ('<"test">', '<"test">', False),
+ # backref support
+ ('test formating', 'test formating', True),
+ # RST sanitizing
+ ('1 :class:`~a.b`. 2 :class:`a.b` 3 :ref:`whatever <better name>`',
+ '1 b. 2 a.b 3 better name', False),
+ ('use :meth:`mne.io.Raw.plot_psd` to',
+ 'use mne.io.Raw.plot_psd to', False),
+ ('`this` and ``that``; and `these things` and ``those things``',
+ 'this and that; and these things and those things', False),
+])
+def test_thumbnail_div(content, tooltip, is_backref):
+ """Test if the thumbnail div generates the correct string."""
+ with pytest.raises(RuntimeError, match='internal sphinx-gallery thumb'):
+ html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
+ '<"test">')
+ content = _sanitize_rst(content)
+ html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
+ content, is_backref=is_backref, check=False)
+ if is_backref:
+ extra = """
.. only:: not html
- * :ref:`sphx_glr_fake_dir_test_file.py`
-"""
-
+ * :ref:`sphx_glr_fake_dir_test_file.py`"""
+ else:
+ extra = ''
+ reference = REFERENCE.format(tooltip, extra)
assert html_div == reference
def test_identify_names(unicode_sample):
-
+ """Test name identification."""
expected = {
'os.path.join':
{'name': 'join', 'module': 'os.path', 'module_short': 'os.path'},
@@ -88,6 +81,7 @@ def test_identify_names(unicode_sample):
def test_identify_names2(tmpdir):
+ """Test more name identification."""
code_str = b"""
'''
Title
@@ -103,7 +97,8 @@ print(c)
e.HelloWorld().f.g
"""
expected = {'c': {'name': 'c', 'module': 'a.b', 'module_short': 'a.b'},
- 'e.HelloWorld': {'name': 'HelloWorld', 'module': 'd', 'module_short': 'd'}}
+ 'e.HelloWorld': {'name': 'HelloWorld', 'module': 'd',
+ 'module_short': 'd'}}
fname = tmpdir.join("indentify_names.py")
fname.write(code_str, 'wb')
|
ENH: remove API crossrefs from hover text
Currently if the first sentence of an example/tutorial/whatever contains an API cross-ref, the hover text can end up looking like this:

Enhancement would be to add a regex to the hover text generator that would strip out the cross-reference-generating text and leave just the class/function/method/attribute name. Ideally would be smart enough to behave the same way the cross-refs do w/r/t the presence of the leading `~`.
|
0.0
|
2fbf59555dc109b22b0e8533e681652a03b99985
|
[
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[<\"test\">-<"test">-False]",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[test",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[1",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[use",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[`this`",
"sphinx_gallery/tests/test_backreferences.py::test_identify_names",
"sphinx_gallery/tests/test_backreferences.py::test_identify_names2"
] |
[] |
{
"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
}
|
2019-06-21 18:09:50+00:00
|
bsd-3-clause
| 5,662 |
|
sphinx-gallery__sphinx-gallery-518
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 191ecef..932b79c 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,7 +1,7 @@
Change Log
==========
-v0.4.0
+v0.5.0
------
Developer changes
@@ -15,6 +15,10 @@ Incompatible changes
- Dropped support for Sphinx < 1.8.3.
- Dropped support for Python < 3.5.
+**Implemented enhancements:**
+
+- ENH: Support ``#%%`` cell separator `#370 <https://github.com/sphinx-gallery/sphinx-gallery/pull/518>`__ (`lucyleeow <https://github.com/lucyleeow>`_)
+
v0.4.0
------
diff --git a/doc/syntax.rst b/doc/syntax.rst
index cc37c2e..b0e7ae7 100644
--- a/doc/syntax.rst
+++ b/doc/syntax.rst
@@ -39,8 +39,9 @@ Jupyter Notebooks are structured (in fact, Sphinx-Gallery also **creates** a
Jupyter Notebook for each example that is built).
You can embed rST in your Python examples by including a line of ``#`` symbols
-that spans >= 20 columns. We recommend using 79 columns, like
-this::
+that spans >= 20 columns or ``#%%``. For compatibility reasons,
+``# %%`` (with a space) can also be used but ``#%%`` is recommended for
+consistency. If using ``#``'s, we recommend using 79 columns, like this::
###############################################################################
@@ -62,7 +63,20 @@ gallery examples. For example::
# commented rST block. Instead, they'll resolve as regular Python comments.
print('my variable plus 2 is {}'.format(myvariable + 2))
-Here are the contents of an example Python file from the snippets above.::
+The ``#%%`` syntax is consistent with the 'code block' (or 'code cell')
+syntax in `Jupyter VSCode plugin
+<https://code.visualstudio.com/docs/python/jupyter-support>`_, `Jupytext
+<https://jupytext.readthedocs.io/en/latest/introduction.html>`_, `Pycharm
+<https://www.jetbrains.com/help/pycharm/running-jupyter-notebook-cells.html>`_,
+`Hydrogen plugin (for Atom)
+<https://nteract.gitbooks.io/hydrogen/>`_ and `Spyder
+<https://docs.spyder-ide.org/editor.html>`_. In these IDEs/with these IDE
+plugins, ``#%%`` at the start of a line signifies the start of a code block.
+The code within a code block can be easily executed all at once. This
+functionality can be helpful when writing a Sphinx-Gallery ``.py`` script.
+
+Here are the contents of an example Python file using the 'code block'
+functionality::
"""
This is my example script
@@ -71,21 +85,26 @@ Here are the contents of an example Python file from the snippets above.::
This example doesn't do much, it just makes a simple plot
"""
- ###############################################################################
+ #%%
# This is a section header
# ------------------------
- #
- # .. note:: This is the first section!
+ # This is the first section!
+ # The `#%%` signifies to Sphinx-Gallery that this text should be rendered as
+ # rST and if using one of the above IDE/plugin's, also signifies the start of a
+ # 'code block'.
# This line won't be rendered as rST because there's a space after the last block.
myvariable = 2
print("my variable is {}".format(myvariable))
+ # This is the end of the 'code block' (if using an above IDE). All code within
+ # this block can be easily executed all at once.
- ###############################################################################
+ #%%
# This is another section header
# ------------------------------
#
# In the built documentation, it will be rendered as rST after the code above!
+ # This is also another code block.
print('my variable plus 2 is {}'.format(myvariable + 2))
diff --git a/sphinx_gallery/py_source_parser.py b/sphinx_gallery/py_source_parser.py
index dd80f56..166552f 100644
--- a/sphinx_gallery/py_source_parser.py
+++ b/sphinx_gallery/py_source_parser.py
@@ -161,7 +161,7 @@ def split_code_and_text_blocks(source_file):
file_conf = extract_file_config(rest_of_content)
pattern = re.compile(
- r'(?P<header_line>^#{20,}.*)\s(?P<text_content>(?:^#.*\s)*)',
+ r'(?P<header_line>^#{20,}.*|^# ?%%.*)\s(?P<text_content>(?:^#.*\s)*)',
flags=re.M)
sub_pat = re.compile('^#', flags=re.M)
diff --git a/tutorials/plot_parse.py b/tutorials/plot_parse.py
index 8f75828..47bb4f4 100644
--- a/tutorials/plot_parse.py
+++ b/tutorials/plot_parse.py
@@ -27,10 +27,12 @@ import matplotlib.pyplot as plt
# Now there is free repetition of both
#############################################
-# And a single line of hashes can split your blocks
+# A block an be split by either a single line of ``#``'s (>=20 columns) or
+# ``#%%``. For compatibility reasons ``# %%`` (with a space) can also be used
+# but we recommend only using ``#%%`` for consistency. All future
+# 'block splitters' used in the source ``.py`` document will be ``#%%``.
-
-###############################################################################
+#%%
# Latex in the comments does not need to be escaped
#
# .. math::
@@ -45,30 +47,32 @@ def dummy():
# this should not be part of a 'text' block
-######################################################################
+#%%
#
# ####################################################################
#
# Making a line cut in sphinx
-###############################################################################
+#%%
# .. warning::
-# The next kind of comments are not supported and become to hard to escape
+# The next kind of comments are not supported and become too hard to escape
# so just don't code like this::
#
# def dummy2():
# """Function docstring"""
# ####################################
-# # This comment inside python indentation
+# # This comment
+# #%%
+# # and this comment inside python indentation
# # breaks the block structure and is not
# # supported
# dummy2
#
-"""Free strings are not supported they remain part of the code"""
+"""Free strings are not supported. They remain part of the code"""
-##############################################################################
-# New lines can be included in you block comments and the parser
+#%%
+# New lines can be included in your block comments and the parser
# is capable of retaining this significant whitespace to work with sphinx
#
# So the reStructuredText headers survive
@@ -77,20 +81,21 @@ def dummy():
print('one')
-###############################################################################
+#%%
# Code block separators
-###############################################################################
-# Surrounding a comment line with lines of # like a block spliter also
-# works and creates a new header for that comment block
-# too. Nevertheless to get rich text formatting we advise to use
-# RestructuredText syntax in the comment blocks.
+####################################################################
+# Surrounding a comment line with a line of ``#``'s (like a block splitter)
+# above and below (or ``#%%`` on top and a line of ``#``'s below, as we have
+# done here in the source ``.py`` doc) also works and creates a new header for
+# that comment block too. Nevertheless to get rich text formatting we advise to
+# use RestructuredText syntax in the comment blocks.
print('two')
-##################################################
+#%%
#
B = 1
-##############################################################################
+#%%
# End comments
#
# That's all folks !
|
sphinx-gallery/sphinx-gallery
|
f2e6cc984aa88f6a2f026d63eb4ab55692ce2e59
|
diff --git a/sphinx_gallery/tests/reference_parse.txt b/sphinx_gallery/tests/reference_parse.txt
index 376bbee..8eda9f9 100644
--- a/sphinx_gallery/tests/reference_parse.txt
+++ b/sphinx_gallery/tests/reference_parse.txt
@@ -7,27 +7,29 @@
('text',
'There is no need to always alternate between code and comment blocks\nNow there is free repetition of both\n',
26),
- ('text', 'And a single line of hashes can split your blocks\n', 30),
- ('text', 'Latex in the comments does not need to be escaped\n\n.. math::\n \\sin\n', 34),
+ ('text',
+ "A block an be split by either a single line of ``#``'s (>=20 columns) or \n``#%%``. For compatibility reasons ``# %%`` (with a space) can also be used\nbut we recommend only using ``#%%`` for consistency. All future \n'block splitters' used in the source ``.py`` document will be ``#%%``.\n",
+ 30),
+ ('text', 'Latex in the comments does not need to be escaped\n\n.. math::\n \\sin\n', 36),
('code',
'\ndef dummy():\n """This should not be part of a \'text\' block\'"""\n\n ######################################\n # Comment inside code to remain here\n pass\n\n# this should not be part of a \'text\' block\n\n',
- 38),
+ 40),
('text',
'####################################################################\n\nMaking a line cut in sphinx\n',
- 49),
+ 51),
('text',
- '.. warning::\n The next kind of comments are not supported and become to hard to escape\n so just don\'t code like this::\n\n def dummy2():\n """Function docstring"""\n ####################################\n # This comment inside python indentation\n # breaks the block structure and is not\n # supported\n dummy2\n\n',
- 55),
- ('code', '\n"""Free strings are not supported they remain part of the code"""\n\n', 67),
+ '.. warning::\n The next kind of comments are not supported and become too hard to escape\n so just don\'t code like this::\n\n def dummy2():\n """Function docstring"""\n ####################################\n # This comment \n #%%\n # and this comment inside python indentation\n # breaks the block structure and is not\n # supported\n dummy2\n\n',
+ 57),
+ ('code', '\n"""Free strings are not supported. They remain part of the code"""\n\n', 71),
('text',
- 'New lines can be included in you block comments and the parser\nis capable of retaining this significant whitespace to work with sphinx\n\nSo the reStructuredText headers survive\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
- 71),
- ('code', "\n\nprint('one')\n\n", 76),
+ 'New lines can be included in your block comments and the parser\nis capable of retaining this significant whitespace to work with sphinx\n\nSo the reStructuredText headers survive\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',
+ 75),
+ ('code', "\n\nprint('one')\n\n", 80),
('text',
- 'Code block separators\n##############################################################################\n Surrounding a comment line with lines of # like a block spliter also\n works and creates a new header for that comment block\n too. Nevertheless to get rich text formatting we advise to use\n RestructuredText syntax in the comment blocks.\n',
- 81),
- ('code', "\nprint('two')\n", 87),
- ('code', 'B = 1\n\n', 91),
+ "Code block separators\n###################################################################\n Surrounding a comment line with a line of ``#``'s (like a block splitter)\n above and below (or ``#%%`` on top and a line of ``#``'s below, as we have \n done here in the source ``.py`` doc) also works and creates a new header for\n that comment block too. Nevertheless to get rich text formatting we advise to\n use RestructuredText syntax in the comment blocks.\n",
+ 85),
+ ('code', "\nprint('two')\n", 92),
+ ('code', 'B = 1\n\n', 96),
('text',
"End comments\n\nThat's all folks !\n\n.. literalinclude:: plot_parse.py\n\n\n",
- 94)]
+ 99)]
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index b3d0081..82644ad 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -67,7 +67,8 @@ def test_split_code_and_text_blocks():
def test_bug_cases_of_notebook_syntax():
"""Test over the known requirements of supported syntax in the
- notebook styled comments"""
+ notebook styled comments. Use both '#'s' and '# %%' as cell
+ separators"""
with open('sphinx_gallery/tests/reference_parse.txt') as reference:
ref_blocks = ast.literal_eval(reference.read())
@@ -110,8 +111,11 @@ def test_rst_block_after_docstring(gallery_conf, tmpdir):
'####################',
'# Paragraph 1',
'',
- '####################',
+ '#%%',
'# Paragraph 2',
+ '',
+ '# %%',
+ '# Paragraph 3',
'']))
file_conf, blocks = sg.split_code_and_text_blocks(filename)
@@ -119,6 +123,7 @@ def test_rst_block_after_docstring(gallery_conf, tmpdir):
assert blocks[0][0] == 'text'
assert blocks[1][0] == 'text'
assert blocks[2][0] == 'text'
+ assert blocks[3][0] == 'text'
script_vars = {'execute_script': ''}
@@ -133,6 +138,8 @@ def test_rst_block_after_docstring(gallery_conf, tmpdir):
'',
'Paragraph 2',
'',
+ 'Paragraph 3',
+ '',
''])
|
Feature request: Add an option for different cell separations
We should add an option so that to give equivalent to what currently is "########################", used as a cell separated.
Candidates:
* "\n\n" to have lighter source files
* "# %%" to be compatible with other softwares such as atom hydrogen, as mentioned below by @lesteve
Thanks to @ogrisel for having suggested this a while ago.
|
0.0
|
f2e6cc984aa88f6a2f026d63eb4ab55692ce2e59
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-11 09:31:42+00:00
|
bsd-3-clause
| 5,663 |
|
sphinx-gallery__sphinx-gallery-529
|
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 64c2047..ed04ba2 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -508,7 +508,7 @@ def execute_code_block(compiler, block, example_globals,
os.chdir(cwd)
captured_std = captured_std.getvalue().expandtabs()
- if captured_std:
+ if captured_std and not captured_std.isspace():
captured_std = CODE_OUTPUT.format(indent(captured_std, u' ' * 4))
else:
captured_std = ''
|
sphinx-gallery/sphinx-gallery
|
c15b18033960e45724bb55940714c0acb4a1c969
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 82644ad..2442540 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -448,6 +448,27 @@ def test_output_indentation(gallery_conf):
assert output_test_string == test_string.replace(r"\n", "\n")
+def test_empty_output_box(gallery_conf):
+ """Tests that `print(__doc__)` doesn't produce an empty output box."""
+ compiler = codeop.Compile()
+
+ code_block = ("code", "print(__doc__)", 1)
+
+ script_vars = {
+ "execute_script": True,
+ "image_path_iterator": ImagePathIterator("temp.png"),
+ "src_file": __file__,
+ "memory_delta": [],
+ }
+
+ example_globals = {'__doc__': ''}
+
+ output = sg.execute_code_block(
+ compiler, code_block, example_globals, script_vars, gallery_conf
+ )
+ assert output.isspace() == True
+
+
class TestLoggingTee:
def setup(self):
self.output_file = io.StringIO()
|
Small regression in 0.4.1: print(__doc__) creates empty output block
Seen in https://github.com/scikit-learn/scikit-learn/pull/14507#issuecomment-516466110, `print(__doc__)` creates empty output box (yellowish box in the output below).

This was introduced by https://github.com/sphinx-gallery/sphinx-gallery/pull/475. A simple fix would be to not have an output box if `my_stdout.isspace()` and add a test similar to the one introduced in #475 to check that `print(__doc__)` does not create an output box.
Small reminder: many scikit-learn examples have `print(__doc__)` at the beginning, so inside sphinx-gallery we set `__doc__ = ''` (`__doc__` is already rendered at the top of the example HTML so you don't want it captured in stdout as well).
ping @lucyleeow who is interested to work on this.
|
0.0
|
c15b18033960e45724bb55940714c0acb4a1c969
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-08-09 10:21:15+00:00
|
bsd-3-clause
| 5,664 |
|
sphinx-gallery__sphinx-gallery-537
|
diff --git a/doc/advanced.rst b/doc/advanced.rst
index 0e912be..c3bc542 100644
--- a/doc/advanced.rst
+++ b/doc/advanced.rst
@@ -83,11 +83,39 @@ Image scrapers are functions (or callable class instances) that do two things:
extensions, respectively)
3. Return rST that embeds these figures in the built documentation.
-The function should take the following inputs (in this order): ``block``,
-``block_vars``, and ``gallery_conf``. It should return a string containing the
-rST for embedding this figure in the documentation.
-See :func:`~sphinx_gallery.scrapers.matplotlib_scraper` for
-a description of the inputs/outputs.
+The function should take the following inputs (in this order):
+
+1. ``block`` - a Sphinx-Gallery ``.py`` file is separated into consecutive
+ lines of 'code' and rST 'text', called 'blocks'. For each
+ block, a tuple containing the (label, content, line_number)
+ (e.g. ``('code', 'print("Hello world")', 5)``) of the block is created.
+
+ * 'label' is a string that can either be ``'text'`` or ``'code'``. In this
+ context, it should only be ``'code'`` as this function is only called for
+ code blocks.
+ * 'content' is a string containing the actual content of the code block.
+ * 'line_number' is an integer, indicating the line number that the block
+ starts at.
+
+2. ``block_vars`` - dictionary of configuration and runtime variables. Of
+ interest for image scrapers is the element ``'image_path_iterator'`` which
+ is an iterable object which returns an absolute path to an image file name
+ adhering to Sphinx-Gallery naming convention. The path directs to the
+ ``gallery_dirs/images`` directory (:ref:`configure_and_use_sphinx_gallery`)
+ and the image file name is ``'sphx_glr_'`` followed by the name of the
+ source ``.py`` file then a number, which starts at 1 and increases by 1 at
+ each iteration. The default file format is ``.'png'``. For example:
+ ``'home/user/Documents/module/auto_examples/images/sphx_glr_plot_mymodule_001.png'``
+
+3. ``gallery_conf`` - dictionary containing the configuration of Sphinx-Gallery,
+ set under ``sphinx_gallery_conf`` in ``doc/conf.py`` (:ref:`configuration`).
+
+It should return a string containing the rST for embedding this figure in the
+documentation. See :func:`~sphinx_gallery.scrapers.matplotlib_scraper` for an
+example of a scraper function (click on 'source' below the function name to see
+the source code). The :func:`~sphinx_gallery.scrapers.matplotlib_scraper` uses
+the helper function :func:`sphinx_gallery.scrapers.figure_rst` to help generate
+rST (see below).
This function will be called once for each code block of your examples.
Sphinx-gallery will take care of scaling images for the gallery
diff --git a/doc/getting_started.rst b/doc/getting_started.rst
index 43356a7..e613497 100644
--- a/doc/getting_started.rst
+++ b/doc/getting_started.rst
@@ -94,6 +94,8 @@ this folder must have the following things:
included as sub-sections of your gallery. They **must** contain their own
``README.txt`` or ``README.rst`` file as well.
+.. _configure_and_use_sphinx_gallery:
+
Configure and use sphinx-gallery
--------------------------------
diff --git a/doc/syntax.rst b/doc/syntax.rst
index b0e7ae7..a4962d8 100644
--- a/doc/syntax.rst
+++ b/doc/syntax.rst
@@ -13,11 +13,13 @@ A simple example
Sphinx-Gallery expects each Python file to have two things:
1. **A docstring**, written in rST, that defines the
- header for the example. It must begin by defining an rST title. For example::
+ header for the example. It must begin by defining a rST title. The title
+ may contain any punctuation mark but cannot start with the same punctuation
+ mark repeated more than 3 times. For example::
"""
- This is my example script
- =========================
+ "This" is my example-script
+ ===========================
This example doesn't do much, it just makes a simple plot
"""
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index f74bf18..3e635b8 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -186,16 +186,18 @@ def extract_intro_and_title(filename, docstring):
"Example docstring should have a header for the example title. "
"Please check the example file:\n {}\n".format(filename))
# Title is the first paragraph with any ReSTructuredText title chars
- # removed, i.e. lines that consist of (all the same) 7-bit non-ASCII chars.
+ # removed, i.e. lines that consist of (3 or more of the same) 7-bit
+ # non-ASCII chars.
# This conditional is not perfect but should hopefully be good enough.
title_paragraph = paragraphs[0]
- match = re.search(r'([\w ]+)', title_paragraph)
+ match = re.search(r'^(?!([\W _])\1{3,})(.+)', title_paragraph,
+ re.MULTILINE)
if match is None:
raise ValueError(
'Could not find a title in first paragraph:\n{}'.format(
title_paragraph))
- title = match.group(1).strip()
+ title = match.group(0).strip()
# Use the title if no other paragraphs are provided
intro_paragraph = title if len(paragraphs) < 2 else paragraphs[1]
# Concatenate all lines of the first paragraph and truncate at 95 chars
|
sphinx-gallery/sphinx-gallery
|
e871d656c749014f269f1ce92ca08d2c074ed934
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 11c6553..b5cda51 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -210,6 +210,11 @@ def test_extract_intro_and_title():
'^^^^^\n Title two \n^^^^^')
assert intro == title == 'Title two'
+ # Title with punctuation (gh-517)
+ intro, title = sg.extract_intro_and_title('<string>',
+ ' ------------\n"-`Header"-with:; `punct` mark\'s\n----------------')
+ assert title == '"-`Header"-with:; `punct` mark\'s'
+
# Long intro paragraph gets shortened
intro_paragraph = '\n'.join(['this is one line' for _ in range(10)])
intro, _ = sg.extract_intro_and_title(
@@ -224,7 +229,7 @@ def test_extract_intro_and_title():
with pytest.raises(ValueError, match='should have a header'):
sg.extract_intro_and_title('<string>', '') # no title
with pytest.raises(ValueError, match='Could not find a title'):
- sg.extract_intro_and_title('<string>', '-') # no real title
+ sg.extract_intro_and_title('<string>', '=====') # no real title
def test_md5sums():
|
Intro text gets truncated on '-' character
Hello,
We have a sample that we'd like to document, which has a sentence: "This is a Mach-Zehnder Interferometer used for [...]".
However, in gen_rst.py, extract_intro_and_title, the regex defined is this:
`match = re.search(r'([\w ]+)', title_paragraph)`
This will truncate on the '-' sign because of this specific regex. Would it be safe/ok to add the '-' symbol here, too? I can imagine there will be other sentences where a hyphen will be present.
Thanks for this nice project, btw!
|
0.0
|
e871d656c749014f269f1ce92ca08d2c074ed934
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-12 12:50:41+00:00
|
bsd-3-clause
| 5,665 |
|
sphinx-gallery__sphinx-gallery-573
|
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 5d632a5..4100482 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -857,12 +857,13 @@ def save_rst_example(example_rst, example_file, time_elapsed,
binder_text = (" or to run this example in your browser via Binder"
if len(binder_conf) else "")
- example_rst = (".. note::\n"
- " :class: sphx-glr-download-link-note\n\n"
- " Click :ref:`here <sphx_glr_download_{0}>` "
- "to download the full example code{1}\n"
- ".. rst-class:: sphx-glr-example-title\n\n"
- ".. _sphx_glr_{0}:\n\n"
+ example_rst = (".. only:: html\n\n"
+ " .. note::\n"
+ " :class: sphx-glr-download-link-note\n\n"
+ " Click :ref:`here <sphx_glr_download_{0}>` "
+ " to download the full example code{1}\n"
+ " .. rst-class:: sphx-glr-example-title\n\n"
+ " .. _sphx_glr_{0}:\n\n"
).format(ref_fname, binder_text) + example_rst
if time_elapsed >= gallery_conf["min_reported_time"]:
|
sphinx-gallery/sphinx-gallery
|
9a79bd95de0e0496c04a50cf47c3677f6ce1977e
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 911fc6c..d0d0602 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -417,6 +417,16 @@ def test_remove_config_comments(gallery_conf):
assert '# sphinx_gallery_thumbnail_number = 1' not in rst
+def test_download_link_note_only_html(gallery_conf):
+ """Test html only directive for download_link."""
+ rst = _generate_rst(gallery_conf, 'test.py', CONTENT)
+ download_link_note = (".. only:: html\n\n"
+ " .. note::\n"
+ " :class: sphx-glr-download-link-note\n\n"
+ )
+ assert download_link_note in rst
+
+
@pytest.mark.parametrize('ext', ('.txt', '.rst', '.bad'))
def test_gen_dir_rst(gallery_conf, fakesphinxapp, ext):
"""Test gen_dir_rst."""
|
Remove the note linking to the download section at the beginning of the example from latex/pdf output
For latex/pdf output, this note at the beginning of the example linking to the download section does not link to anything (since there are no download buttons). Would it be possible to disable it in that case? The straightforward way would be wrap it into a `.. only:: html` directive.
|
0.0
|
9a79bd95de0e0496c04a50cf47c3677f6ce1977e
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_download_link_note_only_html"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_final_rst_last_word",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_empty_code_block",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_custom_scraper_thumbnail_alpha",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[assign,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[var,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print(var),()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print+var,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[assign,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[var,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print(var),(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print+var,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_only,(html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(html,repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(repr,html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_only,(html,repr)]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-12-02 19:50:00+00:00
|
bsd-3-clause
| 5,666 |
|
sphinx-gallery__sphinx-gallery-574
|
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 9d8aadd..1a93db0 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -258,7 +258,7 @@ def generate_gallery_rst(app):
# Check for duplicate filenames to make sure linking works as expected
examples_dirs = [ex_dir for ex_dir, _ in workdirs]
- files = collect_gallery_files(examples_dirs)
+ files = collect_gallery_files(examples_dirs, gallery_conf)
check_duplicate_filenames(files)
for examples_dir, gallery_dir in workdirs:
@@ -549,14 +549,16 @@ def summarize_failing_examples(app, exception):
"\n" + "-" * 79)
-def collect_gallery_files(examples_dirs):
+def collect_gallery_files(examples_dirs, gallery_conf):
"""Collect python files from the gallery example directories."""
files = []
for example_dir in examples_dirs:
for root, dirnames, filenames in os.walk(example_dir):
for filename in filenames:
if filename.endswith('.py'):
- files.append(os.path.join(root, filename))
+ if re.search(gallery_conf['ignore_pattern'],
+ filename) is None:
+ files.append(os.path.join(root, filename))
return files
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 5d632a5..4100482 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -857,12 +857,13 @@ def save_rst_example(example_rst, example_file, time_elapsed,
binder_text = (" or to run this example in your browser via Binder"
if len(binder_conf) else "")
- example_rst = (".. note::\n"
- " :class: sphx-glr-download-link-note\n\n"
- " Click :ref:`here <sphx_glr_download_{0}>` "
- "to download the full example code{1}\n"
- ".. rst-class:: sphx-glr-example-title\n\n"
- ".. _sphx_glr_{0}:\n\n"
+ example_rst = (".. only:: html\n\n"
+ " .. note::\n"
+ " :class: sphx-glr-download-link-note\n\n"
+ " Click :ref:`here <sphx_glr_download_{0}>` "
+ " to download the full example code{1}\n"
+ " .. rst-class:: sphx-glr-example-title\n\n"
+ " .. _sphx_glr_{0}:\n\n"
).format(ref_fname, binder_text) + example_rst
if time_elapsed >= gallery_conf["min_reported_time"]:
|
sphinx-gallery/sphinx-gallery
|
9a79bd95de0e0496c04a50cf47c3677f6ce1977e
|
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 872bb83..9f5269d 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -281,7 +281,7 @@ def test_example_sorting_title(sphinx_app_wrapper):
_check_order(sphinx_app, 'title')
-def test_collect_gallery_files(tmpdir):
+def test_collect_gallery_files(tmpdir, gallery_conf):
"""Test that example files are collected properly."""
rel_filepaths = ['examples/file1.py',
'examples/test.rst',
@@ -298,7 +298,7 @@ def test_collect_gallery_files(tmpdir):
examples_path = tmpdir.join('examples')
dirs = [examples_path.strpath]
- collected_files = set(collect_gallery_files(dirs))
+ collected_files = set(collect_gallery_files(dirs, gallery_conf))
expected_files = set(
[ap.strpath for ap in abs_paths
if re.search(r'examples.*\.py$', ap.strpath)])
@@ -307,13 +307,35 @@ def test_collect_gallery_files(tmpdir):
tutorials_path = tmpdir.join('tutorials')
dirs = [examples_path.strpath, tutorials_path.strpath]
- collected_files = set(collect_gallery_files(dirs))
+ collected_files = set(collect_gallery_files(dirs, gallery_conf))
expected_files = set(
[ap.strpath for ap in abs_paths if re.search(r'.*\.py$', ap.strpath)])
assert collected_files == expected_files
+def test_collect_gallery_files_ignore_pattern(tmpdir, gallery_conf):
+ """Test that ignore pattern example files are not collected."""
+ rel_filepaths = ['examples/file1.py',
+ 'examples/folder1/fileone.py',
+ 'examples/folder1/file2.py',
+ 'examples/folder2/fileone.py']
+
+ abs_paths = [tmpdir.join(rp) for rp in rel_filepaths]
+ for ap in abs_paths:
+ ap.ensure()
+
+ gallery_conf['ignore_pattern'] = r'one'
+ examples_path = tmpdir.join('examples')
+ dirs = [examples_path.strpath]
+ collected_files = set(collect_gallery_files(dirs, gallery_conf))
+ expected_files = set(
+ [ap.strpath for ap in abs_paths
+ if re.search(r'one', ap.strpath) is None])
+
+ assert collected_files == expected_files
+
+
@pytest.mark.conf_file(content="""
sphinx_gallery_conf = {
'backreferences_dir' : os.path.join('modules', 'gen'),
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 911fc6c..d0d0602 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -417,6 +417,16 @@ def test_remove_config_comments(gallery_conf):
assert '# sphinx_gallery_thumbnail_number = 1' not in rst
+def test_download_link_note_only_html(gallery_conf):
+ """Test html only directive for download_link."""
+ rst = _generate_rst(gallery_conf, 'test.py', CONTENT)
+ download_link_note = (".. only:: html\n\n"
+ " .. note::\n"
+ " :class: sphx-glr-download-link-note\n\n"
+ )
+ assert download_link_note in rst
+
+
@pytest.mark.parametrize('ext', ('.txt', '.rst', '.bad'))
def test_gen_dir_rst(gallery_conf, fakesphinxapp, ext):
"""Test gen_dir_rst."""
|
check_duplicated does not respect the ignore_pattern
It seems that check_duplicate_filenames does not respect the ignore_pattern.
The proper fix would probably be to have collect_gallery_files respect the ignore_pattern.
|
0.0
|
9a79bd95de0e0496c04a50cf47c3677f6ce1977e
|
[
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files_ignore_pattern",
"sphinx_gallery/tests/test_gen_rst.py::test_download_link_note_only_html"
] |
[
"sphinx_gallery/tests/test_gen_gallery.py::test_default_config",
"sphinx_gallery/tests/test_gen_gallery.py::test_no_warning_simple_config",
"sphinx_gallery/tests/test_gen_gallery.py::test_config_old_backreferences_conf",
"sphinx_gallery/tests/test_gen_gallery.py::test_config_backreferences",
"sphinx_gallery/tests/test_gen_gallery.py::test_duplicate_files_warn",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_default",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_filesize",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_filename",
"sphinx_gallery/tests/test_gen_gallery.py::test_example_sorting_title",
"sphinx_gallery/tests/test_gen_gallery.py::test_binder_copy_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_expected_failing_examples_were_executed",
"sphinx_gallery/tests/test_gen_gallery.py::test_write_computation_times_noop",
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_final_rst_last_word",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_empty_code_block",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums",
"sphinx_gallery/tests/test_gen_rst.py::test_fail_example",
"sphinx_gallery/tests/test_gen_rst.py::test_custom_scraper_thumbnail_alpha",
"sphinx_gallery/tests/test_gen_rst.py::test_remove_config_comments",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_pattern_matching",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[assign,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[var,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print(var),()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print+var,()]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[assign,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[var,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print(var),(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print+var,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[print",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_only,(html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(html,repr)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_and_html,(repr,html)]",
"sphinx_gallery/tests/test_gen_rst.py::test_capture_repr[repr_only,(html,repr)]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-03 09:48:35+00:00
|
bsd-3-clause
| 5,667 |
|
sphinx-gallery__sphinx-gallery-625
|
diff --git a/doc/configuration.rst b/doc/configuration.rst
index 584e854..e7568c8 100644
--- a/doc/configuration.rst
+++ b/doc/configuration.rst
@@ -37,10 +37,10 @@ file:
- ``min_reported_time`` (:ref:`min_reported_time`)
- ``show_memory`` (:ref:`show_memory`)
- ``binder`` (:ref:`binder_links`)
-- ``first_notebook_cell`` (:ref:`first_notebook_cell`)
+- ``first_notebook_cell`` and ``last_notebook_cell`` (:ref:`own_notebook_cell`)
- ``junit`` (:ref:`junit_xml`)
- ``log_level`` (:ref:`log_level`)
-- ``capture_repr``, ``ignore_repr_types`` (:ref:`capture_repr`)
+- ``capture_repr`` and ``ignore_repr_types`` (:ref:`capture_repr`)
Some options can also be set or overridden on a file-by-file basis:
@@ -545,22 +545,26 @@ To remove the comment from the rendered example set the option::
'remove_config_comments': True,
}
-.. _first_notebook_cell:
+.. _own_notebook_cell:
-Add your own first notebook cell
-================================
+Add your own first and last notebook cell
+=========================================
-Sphinx-Gallery adds an extra cell to the beginning of every generated notebook.
-This is often for adding code that is required to run properly in the notebook,
-but not in a ``.py`` file. By default, this text is
+Sphinx-Gallery allows you to add your own first and/or last cell to *every*
+generated notebook. Adding a first cell can be useful for including code that
+is required to run properly in the notebook, but not in a ``.py`` file. By
+default, the following first cell is added to each notebook::
.. code-block:: ipython
%matplotlib inline
+Adding a last cell can be useful for performing a desired action such as
+reporting on the user's evironment. By default no last cell is added.
+
You can choose whatever text you like by modifying the ``first_notebook_cell``
-configuration parameter. For example, the gallery of this documentation
-displays a comment along-side each the code shown above.
+and ``last_notebook_cell`` configuration parameters. For example, the gallery
+of this documentation adds the following first cell::
.. code-block:: ipython
@@ -577,8 +581,19 @@ Which is achieved by the following configuration::
"%matplotlib inline")
}
-If the value of ``first_notebook_cell`` is set to ``None``, then no extra first
-cell will be added to the notebook.
+A last cell may be added similarly by setting the ``last_notebook_cell``
+parameter::
+
+ sphinx_gallery_conf = {
+ ...
+ 'first_notebook_cell': ("# This cell is added by sphinx-gallery\n"
+ "# It can be customized to whatever you like\n"
+ "%matplotlib inline"),
+ 'last_notebook_cell': "# This is the last cell",
+ }
+
+If the value of ``first_notebook_cell`` or ``last_notebook_cell`` is set to
+``None``, then no extra first or last cell will be added to the notebook.
.. _junit_xml:
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index a47be82..758c9ab 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -63,6 +63,7 @@ DEFAULT_GALLERY_CONF = {
'image_scrapers': ('matplotlib',),
'reset_modules': ('matplotlib', 'seaborn'),
'first_notebook_cell': '%matplotlib inline',
+ 'last_notebook_cell': None,
'remove_config_comments': False,
'show_memory': False,
'junit': '',
@@ -198,6 +199,12 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
raise ValueError("The 'first_notebook_cell' parameter must be type str"
"or None, found type %s" % type(first_cell))
gallery_conf['first_notebook_cell'] = first_cell
+ # Ensure the last cell text is a string if we have it
+ last_cell = gallery_conf.get("last_notebook_cell")
+ if (not isinstance(last_cell, str)) and (last_cell is not None):
+ raise ValueError("The 'last_notebook_cell' parameter must be type str"
+ "or None, found type %s" % type(last_cell))
+ gallery_conf['last_notebook_cell'] = last_cell
# Make it easy to know which builder we're in
gallery_conf['builder_name'] = builder_name
gallery_conf['titles'] = {}
diff --git a/sphinx_gallery/notebook.py b/sphinx_gallery/notebook.py
index 036da5a..7cfad6e 100644
--- a/sphinx_gallery/notebook.py
+++ b/sphinx_gallery/notebook.py
@@ -112,10 +112,13 @@ def jupyter_notebook(script_blocks, gallery_conf):
The sphinx-gallery configuration dictionary.
"""
first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
+ last_cell = gallery_conf.get("last_notebook_cell", None)
work_notebook = jupyter_notebook_skeleton()
if first_cell is not None:
add_code_cell(work_notebook, first_cell)
fill_notebook(work_notebook, script_blocks)
+ if last_cell is not None:
+ add_code_cell(work_notebook, last_cell)
return work_notebook
|
sphinx-gallery/sphinx-gallery
|
29c3246b5a54020b8b1f63ae8e59a3ac2aaa2198
|
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index c50d752..2e636c5 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -336,6 +336,17 @@ def test_first_notebook_cell_config(sphinx_app_wrapper):
parse_config(sphinx_app_wrapper.create_sphinx_app())
[email protected]_file(content="""
+sphinx_gallery_conf = {
+ 'last_notebook_cell': 2,
+}""")
+def test_last_notebook_cell_config(sphinx_app_wrapper):
+ from sphinx_gallery.gen_gallery import parse_config
+ # First cell must be str
+ with pytest.raises(ValueError):
+ parse_config(sphinx_app_wrapper.create_sphinx_app())
+
+
@pytest.mark.conf_file(content="""
sphinx_gallery_conf = {
'backreferences_dir': False,
diff --git a/sphinx_gallery/tests/test_notebook.py b/sphinx_gallery/tests/test_notebook.py
index e8c364d..73b8a14 100644
--- a/sphinx_gallery/tests/test_notebook.py
+++ b/sphinx_gallery/tests/test_notebook.py
@@ -101,6 +101,19 @@ def test_jupyter_notebook(gallery_conf):
cell_src = example_nb.get('cells')[0]['source'][0]
assert cell_src.startswith('\nAlternating text and code')
+ # Test custom last cell text
+ test_text = '# testing last cell'
+ gallery_conf['last_notebook_cell'] = test_text
+ example_nb = jupyter_notebook(blocks, gallery_conf)
+ assert example_nb.get('cells')[-1]['source'][0] == test_text
+
+ # Test empty first cell text
+ test_text = None
+ gallery_conf['last_notebook_cell'] = test_text
+ example_nb = jupyter_notebook(blocks, gallery_conf)
+ cell_src = example_nb.get('cells')[-1]['source'][0]
+ assert cell_src.startswith("Last text block.\n\nThat's all folks !")
+
###############################################################################
# Notebook shell utility
|
last_notebook_cell
Could a `last_notebook_cell` option be added much like the `first_notebook_cell` option for adding snippets that we want executed at the end of the downloaded notebook? This would be used to perhaps report on the user's environment with a tool like [`scooby`](https://github.com/banesullivan/scooby):
```py
sphinx_gallery_conf = {
...
'last_notebook_cell': ("# Report on the environment specs\n"
"import scooby\n",
"scooby.Report()",)
}
```
With something like this, a user could download the example, run it, and encounter an error then immediately share the environment report... I imagine this will be useful for PyVista (`pv.Report`) and `mne-python` (`mne.sys_info()`)
|
0.0
|
29c3246b5a54020b8b1f63ae8e59a3ac2aaa2198
|
[
"sphinx_gallery/tests/test_notebook.py::test_jupyter_notebook"
] |
[
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files_ignore_pattern",
"sphinx_gallery/tests/test_gen_gallery.py::test_write_computation_times_noop",
"sphinx_gallery/tests/test_notebook.py::test_latex_conversion",
"sphinx_gallery/tests/test_notebook.py::test_convert",
"sphinx_gallery/tests/test_notebook.py::test_with_empty_args",
"sphinx_gallery/tests/test_notebook.py::test_missing_file",
"sphinx_gallery/tests/test_notebook.py::test_file_is_generated"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-19 11:14:40+00:00
|
bsd-3-clause
| 5,668 |
|
sphinx-gallery__sphinx-gallery-636
|
diff --git a/sphinx_gallery/gen_gallery.py b/sphinx_gallery/gen_gallery.py
index 4d143ba..8ad3d20 100644
--- a/sphinx_gallery/gen_gallery.py
+++ b/sphinx_gallery/gen_gallery.py
@@ -196,17 +196,17 @@ def _complete_gallery_conf(sphinx_gallery_conf, src_dir, plot_gallery,
# Ensure the first cell text is a string if we have it
first_cell = gallery_conf.get("first_notebook_cell")
if (not isinstance(first_cell, str)) and (first_cell is not None):
- raise ValueError("The 'first_notebook_cell' parameter must be type str"
+ raise ValueError("The 'first_notebook_cell' parameter must be type str "
"or None, found type %s" % type(first_cell))
# Ensure the last cell text is a string if we have it
last_cell = gallery_conf.get("last_notebook_cell")
if (not isinstance(last_cell, str)) and (last_cell is not None):
- raise ValueError("The 'last_notebook_cell' parameter must be type str"
+ raise ValueError("The 'last_notebook_cell' parameter must be type str "
"or None, found type %s" % type(last_cell))
# Make it easy to know which builder we're in
gallery_conf['builder_name'] = builder_name
gallery_conf['titles'] = {}
- # Ensure 'backreferences_dir' is str or Noe
+ # Ensure 'backreferences_dir' is str or None
backref = gallery_conf['backreferences_dir']
if (not isinstance(backref, str)) and (backref is not None):
raise ValueError("The 'backreferences_dir' parameter must be of type "
@@ -294,6 +294,7 @@ def generate_gallery_rst(app):
examples_dirs = [ex_dir for ex_dir, _ in workdirs]
files = collect_gallery_files(examples_dirs, gallery_conf)
check_duplicate_filenames(files)
+ check_spaces_in_filenames(files)
for examples_dir, gallery_dir in workdirs:
@@ -611,8 +612,20 @@ def check_duplicate_filenames(files):
if len(dup_names) > 0:
logger.warning(
- 'Duplicate file name(s) found. Having duplicate file names will '
- 'break some links. List of files: {}'.format(sorted(dup_names),))
+ 'Duplicate example file name(s) found. Having duplicate file '
+ 'names will break some links. '
+ 'List of files: {}'.format(sorted(dup_names),))
+
+
+def check_spaces_in_filenames(files):
+ """Check for spaces in filenames across example directories."""
+ regex = re.compile(r'[\s]')
+ files_with_space = list(filter(regex.search, files))
+ if files_with_space:
+ logger.warning(
+ 'Example file name(s) with space(s) found. Having space(s) in '
+ 'file names will break some links. '
+ 'List of files: {}'.format(sorted(files_with_space),))
def get_default_config_value(key):
|
sphinx-gallery/sphinx-gallery
|
23f44fdcd6530b8ee7d8b3e153d15448b407b3a6
|
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 2e636c5..1b1de2e 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -16,6 +16,7 @@ import pytest
from sphinx.errors import ExtensionError
from sphinx_gallery.gen_gallery import (check_duplicate_filenames,
+ check_spaces_in_filenames,
collect_gallery_files,
write_computation_times)
@@ -125,7 +126,7 @@ def test_duplicate_files_warn(sphinx_app_wrapper):
sphinx_app = sphinx_app_wrapper.create_sphinx_app()
files = ['./a/file1.py', './a/file2.py', 'a/file3.py', './b/file1.py']
- msg = ("Duplicate file name(s) found. Having duplicate file names "
+ msg = ("Duplicate example file name(s) found. Having duplicate file names "
"will break some links. List of files: {}")
m = "['./b/file1.py']" if sys.version_info[0] >= 3 else "[u'./b/file1.py']"
@@ -140,6 +141,27 @@ def test_duplicate_files_warn(sphinx_app_wrapper):
assert msg.format(m) in build_warn
+def test_spaces_in_files_warn(sphinx_app_wrapper):
+ """Test for a exception when an example filename has a space in it."""
+ sphinx_app = sphinx_app_wrapper.create_sphinx_app()
+
+ files = ['./a/file1.py', './a/file2.py', './a/file 3.py']
+ msg = ("Example file name(s) with space(s) found. Having space(s) in "
+ "file names will break some links. "
+ "List of files: {}")
+ m = "['./a/file 3.py']" if sys.version_info[0] >= 3 else "[u'./a/file 3.py']"
+
+ # No warning because no filename with space
+ check_spaces_in_filenames(files[:-1])
+ build_warn = sphinx_app._warning.getvalue()
+ assert build_warn == ''
+
+ # Warning because last file has space
+ check_spaces_in_filenames(files)
+ build_warn = sphinx_app._warning.getvalue()
+ assert msg.format(m) in build_warn
+
+
def _check_order(sphinx_app, key):
index_fname = os.path.join(sphinx_app.outdir, '..', 'ex', 'index.rst')
order = list()
|
BUG: Spaces in example filenames break image linking
I get to see this in place of the plots. Please guide me where I am wrong.

Thanks! :)
|
0.0
|
23f44fdcd6530b8ee7d8b3e153d15448b407b3a6
|
[
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files_ignore_pattern",
"sphinx_gallery/tests/test_gen_gallery.py::test_write_computation_times_noop"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-31 18:31:41+00:00
|
bsd-3-clause
| 5,669 |
|
sphinx-gallery__sphinx-gallery-750
|
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 2e95ca1..dd27222 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -10,8 +10,7 @@ example files.
Files that generate images should start with 'plot'.
"""
-# Don't use unicode_literals here (be explicit with u"..." instead) otherwise
-# tricky errors come up with exec(code_blocks, ...) calls
+
from __future__ import division, print_function, absolute_import
from time import time
import copy
@@ -25,6 +24,7 @@ import importlib
from io import StringIO
import os
import re
+import stat
from textwrap import indent
import warnings
from shutil import copyfile
@@ -138,8 +138,7 @@ SINGLE_IMAGE = """
:class: sphx-glr-single-img
"""
-# This one could contain unicode
-CODE_OUTPUT = u""".. rst-class:: sphx-glr-script-out
+CODE_OUTPUT = """.. rst-class:: sphx-glr-script-out
Out:
@@ -176,7 +175,7 @@ def codestr2rst(codestr, lang='python', lineno=None):
lineno = ' :lineno-start: {0}\n'.format(lineno + blank_lines)
else:
lineno = ''
- code_directive = "\n.. code-block:: {0}\n{1}\n".format(lang, lineno)
+ code_directive = ".. code-block:: {0}\n{1}\n".format(lang, lineno)
indented_block = indent(codestr, ' ' * 4)
return code_directive + indented_block
@@ -875,8 +874,34 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf,
return intro, title, (time_elapsed, memory_used)
+EXAMPLE_HEADER = """
+.. DO NOT EDIT.
+.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
+.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
+.. "{0}"
+.. LINE NUMBERS ARE GIVEN BELOW.
+
+.. only:: html
+
+ .. note::
+ :class: sphx-glr-download-link-note
+
+ Click :ref:`here <sphx_glr_download_{1}>`
+ to download the full example code{2}
+
+.. rst-class:: sphx-glr-example-title
+
+.. _sphx_glr_{1}:
+
+"""
+RST_BLOCK_HEADER = """\
+.. GENERATED FROM PYTHON SOURCE LINES {0}-{1}
+
+"""
+
+
def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
- """Generates the rst string containing the script prose, code and output
+ """Generate the rst string containing the script prose, code and output.
Parameters
----------
@@ -902,9 +927,14 @@ def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
# A simple example has two blocks: one for the
# example introduction/explanation and one for the code
is_example_notebook_like = len(script_blocks) > 2
- example_rst = u"" # there can be unicode content
- for (blabel, bcontent, lineno), code_output in \
- zip(script_blocks, output_blocks):
+ example_rst = ""
+ for bi, ((blabel, bcontent, lineno), code_output) in \
+ enumerate(zip(script_blocks, output_blocks)):
+ # do not add comment to the title block, otherwise the linking does
+ # not work properly
+ if bi > 0:
+ example_rst += RST_BLOCK_HEADER.format(
+ lineno, lineno + bcontent.count('\n'))
if blabel == 'code':
if not file_conf.get('line_numbers',
@@ -946,21 +976,15 @@ def save_rst_example(example_rst, example_file, time_elapsed,
Sphinx-Gallery configuration dictionary
"""
- ref_fname = os.path.relpath(example_file, gallery_conf['src_dir'])
- ref_fname = ref_fname.replace(os.path.sep, "_")
+ example_fname = os.path.relpath(example_file, gallery_conf['src_dir'])
+ ref_fname = example_fname.replace(os.path.sep, "_")
binder_conf = check_binder_conf(gallery_conf.get('binder'))
binder_text = (" or to run this example in your browser via Binder"
if len(binder_conf) else "")
- example_rst = (".. only:: html\n\n"
- " .. note::\n"
- " :class: sphx-glr-download-link-note\n\n"
- " Click :ref:`here <sphx_glr_download_{0}>` "
- " to download the full example code{1}\n"
- " .. rst-class:: sphx-glr-example-title\n\n"
- " .. _sphx_glr_{0}:\n\n"
- ).format(ref_fname, binder_text) + example_rst
+ example_rst = EXAMPLE_HEADER.format(
+ example_fname, ref_fname, binder_text) + example_rst
if time_elapsed >= gallery_conf["min_reported_time"]:
time_m, time_s = divmod(time_elapsed, 60)
@@ -985,6 +1009,10 @@ def save_rst_example(example_rst, example_file, time_elapsed,
write_file_new = re.sub(r'\.py$', '.rst.new', example_file)
with codecs.open(write_file_new, 'w', encoding="utf-8") as f:
f.write(example_rst)
+ # make it read-only so that people don't try to edit it
+ mode = os.stat(write_file_new).st_mode
+ ro_mask = 0x777 ^ (stat.S_IWRITE | stat.S_IWGRP | stat.S_IWOTH)
+ os.chmod(write_file_new, mode & ro_mask)
# in case it wasn't in our pattern, only replace the file if it's
# still stale.
_replace_md5(write_file_new, mode='t')
|
sphinx-gallery/sphinx-gallery
|
ecd399e2e60557875d9312a6f5f8dbe4d0dd7a0e
|
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index 447b068..c037a8e 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -130,6 +130,7 @@ def test_rst_block_after_docstring(gallery_conf, tmpdir):
f.write('\n'.join(['"Docstring"',
'####################',
'# Paragraph 1',
+ '# is long.',
'',
'#%%',
'# Paragraph 2',
@@ -152,16 +153,24 @@ def test_rst_block_after_docstring(gallery_conf, tmpdir):
blocks, script_vars, gallery_conf)
example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
- assert example_rst == '\n'.join([
- 'Docstring',
- '',
- 'Paragraph 1',
- '',
- 'Paragraph 2',
- '',
- 'Paragraph 3',
- '',
- ''])
+ want_rst = """\
+Docstring
+
+.. GENERATED FROM PYTHON SOURCE LINES 3-5
+
+Paragraph 1
+is long.
+
+.. GENERATED FROM PYTHON SOURCE LINES 7-8
+
+Paragraph 2
+
+.. GENERATED FROM PYTHON SOURCE LINES 10-11
+
+Paragraph 3
+
+"""
+ assert example_rst == want_rst
def test_rst_empty_code_block(gallery_conf, tmpdir):
@@ -191,15 +200,20 @@ def test_rst_empty_code_block(gallery_conf, tmpdir):
blocks, script_vars, gallery_conf)
example_rst = sg.rst_blocks(blocks, output_blocks, file_conf, gallery_conf)
- assert example_rst.rstrip('\n') == """Docstring
+ want_rst = """\
+Docstring
+
+.. GENERATED FROM PYTHON SOURCE LINES 3-4
Paragraph 1
+.. GENERATED FROM PYTHON SOURCE LINES 4-5
.. code-block:: python
# just a comment"""
+ assert example_rst.rstrip('\n') == want_rst
def test_script_vars_globals(gallery_conf, tmpdir):
@@ -235,7 +249,7 @@ b = 'foo'
def test_codestr2rst():
"""Test the correct translation of a code block into rst."""
output = sg.codestr2rst('print("hello world")')
- reference = """
+ reference = """\
.. code-block:: python
print("hello world")"""
|
Relate warnings and errors on generated rst file back to source Python file / prevent accidental writing of generated files
When there is a problem in the generated RST file from a Gallery Python file, Sphinx reports the line error in the generated rst file. There's a few problems with this:
1. If you're not paying close attention, you might try editing the RST file to fix the error. But this is the wrong thing to do: you should have edited the source Python file. Some ways to make it harder to make this mistake include (1) removing the write bit from generated files, and (2) inserting a "@generated" comment which is respected by many editors and will warn people when editing
2. It would have been much better to report the error in the source Python file in the first place.
Compilers with the C preprocessor have solved this problem by generating comment lines that let you correspond lines in the generated source back to the original source, and then having the eventual frontend report errors by first translating them back to the original source. sphinx-gallery should do this too. It might be difficult to fix this without also getting Sphinx to play ball (e.g., a logical separation would be for Sphinx to add support for file/line number comments, and then teaching sphinx-gallery to respect them).
Is a feature like this something that would be accepted by sphinx-gallery?
|
0.0
|
ecd399e2e60557875d9312a6f5f8dbe4d0dd7a0e
|
[
"sphinx_gallery/tests/test_gen_rst.py::test_rst_block_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_empty_code_block",
"sphinx_gallery/tests/test_gen_rst.py::test_codestr2rst"
] |
[
"sphinx_gallery/tests/test_gen_rst.py::test_split_code_and_text_blocks",
"sphinx_gallery/tests/test_gen_rst.py::test_bug_cases_of_notebook_syntax",
"sphinx_gallery/tests/test_gen_rst.py::test_direct_comment_after_docstring",
"sphinx_gallery/tests/test_gen_rst.py::test_final_rst_last_word",
"sphinx_gallery/tests/test_gen_rst.py::test_script_vars_globals",
"sphinx_gallery/tests/test_gen_rst.py::test_extract_intro_and_title",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums[b-a546be453c8f436e744838a4801bd3a0]",
"sphinx_gallery/tests/test_gen_rst.py::test_md5sums[t-ea8a570e9f3afc0a7c3f2a17a48b8047]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.txt]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.rst]",
"sphinx_gallery/tests/test_gen_rst.py::test_gen_dir_rst[.bad]",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[#sphinx_gallery_thumbnail_number",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_number[",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[#",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[#sphinx_gallery_thumbnail_path",
"sphinx_gallery/tests/test_gen_rst.py::test_thumbnail_path[",
"sphinx_gallery/tests/test_gen_rst.py::test_zip_notebooks",
"sphinx_gallery/tests/test_gen_rst.py::test_rst_example",
"sphinx_gallery/tests/test_gen_rst.py::test_output_indentation",
"sphinx_gallery/tests/test_gen_rst.py::test_empty_output_box"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-28 15:12:36+00:00
|
bsd-3-clause
| 5,670 |
|
sphinx-gallery__sphinx-gallery-906
|
diff --git a/CHANGES.rst b/CHANGES.rst
index e65ffb5..7329034 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -8,6 +8,19 @@ In this version, the "Out:" prefix applied to code outputs is now created from
CSS pseudo-elements instead of additional real text. For more details, see
`#896 <https://github.com/sphinx-gallery/sphinx-gallery/pull/896>`.
+**Implemented enhancements:**
+
+
+**Fixed bugs:**
+
+- Display gallery items using CSS grid instead of floating `#906 <https://github.com/sphinx-gallery/sphinx-gallery/pull/906>`__, see `migration guide <https://github.com/sphinx-gallery/sphinx-gallery/pull/906#issuecomment-1019542067>`__ to adapt custom css for thumbnails (`alexisthual <https://github.com/alexisthual>`__)
+
+**Closed issues:**
+
+
+**Merged pull requests:**
+
+
v0.10.1
-------
diff --git a/doc/faq.rst b/doc/faq.rst
index 8e97824..bab0741 100644
--- a/doc/faq.rst
+++ b/doc/faq.rst
@@ -46,3 +46,16 @@ Alternatively, you can set ``capture_repr`` to be an empty tuple
(``'capture_repr': ()``), which will imitate the behavior of Sphinx-Gallery
prior to v0.5.0. This will also prevent you from getting any other unwanted
output that did not occur prior to v0.5.0.
+
+Why has my thumbnail appearance changed?
+----------------------------------------
+
+The DOM structure of thumbnails was refactored in order to make them responsive
+and aligned on a css grid. These changes might make your existing custom css
+obsolete. You can read our
+`custom css migration guide for thumbnails <https://github.com/sphinx-gallery/sphinx-gallery/pull/906#issuecomment-1019542067>`_
+for pointers on how to update your css.
+
+
+.. seealso::
+ `Github PR #906 <https://github.com/sphinx-gallery/sphinx-gallery/pull/906>`_
diff --git a/sphinx_gallery/_static/sg_gallery.css b/sphinx_gallery/_static/sg_gallery.css
index 62947b7..cf0be73 100644
--- a/sphinx_gallery/_static/sg_gallery.css
+++ b/sphinx_gallery/_static/sg_gallery.css
@@ -3,27 +3,72 @@ Sphinx-Gallery has compatible CSS to fix default sphinx themes
Tested for Sphinx 1.3.1 for all themes: default, alabaster, sphinxdoc,
scrolls, agogo, traditional, nature, haiku, pyramid
Tested for Read the Docs theme 0.1.7 */
+.sphx-glr-thumbnails {
+ width: 100%;
+
+ /* align thumbnails on a grid */
+ justify-content: space-between;
+ display: grid;
+ /* each grid column should be at least 160px (this will determine
+ the actual number of columns) and then take as much of the
+ remaining width as possible */
+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
+ gap: 15px;
+}
+.sphx-glr-thumbnails .toctree-wrapper {
+ /* hide empty toctree divs added to the DOM
+ by sphinx even though the toctree is hidden
+ (they would fill grid places with empty divs) */
+ display: none;
+}
.sphx-glr-thumbcontainer {
- background: #fff;
- border: solid #fff 1px;
+ background: transparent;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
- box-shadow: none;
- float: left;
- margin: 5px;
- min-height: 230px;
- padding-top: 5px;
+ box-shadow: 0 0 10px #6c757d40;
+
+ /* useful to absolutely position link in div */
position: relative;
+
+ /* thumbnail width should include padding and borders
+ and take all available space */
+ box-sizing: border-box;
+ width: 100%;
+ padding: 10px;
+ border: 1px solid transparent;
+
+ /* align content in thumbnail */
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 7px;
+}
+.sphx-glr-thumbcontainer p {
+ position: absolute;
+ top: 0;
+ left: 0;
+}
+.sphx-glr-thumbcontainer p,
+.sphx-glr-thumbcontainer p a {
+ /* link should cover the whole thumbnail div */
+ width: 100%;
+ height: 100%;
+}
+.sphx-glr-thumbcontainer p a span {
+ /* text within link should be masked
+ (we are just interested in the href) */
+ display: none;
}
.sphx-glr-thumbcontainer:hover {
- border: solid #b4ddfc 1px;
- box-shadow: 0 0 15px rgba(142, 176, 202, 0.5);
+ border: 1px solid #0069d9;
+ cursor: pointer;
}
.sphx-glr-thumbcontainer a.internal {
bottom: 0;
display: block;
left: 0;
+ box-sizing: border-box;
padding: 150px 10px 0;
position: absolute;
right: 0;
@@ -36,7 +81,7 @@ thumbnail with its default link Background color */
}
.sphx-glr-thumbcontainer p {
- margin: 0 0 .1em 0;
+ margin: 0 0 0.1em 0;
}
.sphx-glr-thumbcontainer .figure {
margin: 10px;
@@ -66,7 +111,7 @@ thumbnail with its default link Background color */
border-color: #333 transparent;
border-width: 18px 0 0 20px;
bottom: 58%;
- content: '';
+ content: "";
left: 85%;
position: absolute;
z-index: 99;
@@ -121,7 +166,7 @@ blockquote.sphx-glr-script-out {
}
div.sphx-glr-footer {
- text-align: center;
+ text-align: center;
}
div.sphx-glr-download {
@@ -131,7 +176,7 @@ div.sphx-glr-download {
div.sphx-glr-download a {
background-color: #ffc;
- background-image: linear-gradient(to bottom, #FFC, #d5d57e);
+ background-image: linear-gradient(to bottom, #ffc, #d5d57e);
border-radius: 4px;
border: 1px solid #c2c22d;
color: #000;
@@ -152,7 +197,8 @@ div.sphx-glr-download code.download {
}
div.sphx-glr-download a:hover {
- box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1),
+ 0 1px 5px rgba(0, 0, 0, 0.25);
text-decoration: none;
background-image: none;
background-color: #d5d57e;
@@ -193,7 +239,7 @@ div.sphx-glr-animation {
display: block;
max-width: 100%;
}
-div.sphx-glr-animation .animation{
+div.sphx-glr-animation .animation {
display: block;
}
@@ -208,7 +254,7 @@ p.sphx-glr-signature a.reference.external {
display: table;
}
-.sphx-glr-clear{
+.sphx-glr-clear {
clear: both;
}
diff --git a/sphinx_gallery/backreferences.py b/sphinx_gallery/backreferences.py
index 3cc40ba..884e611 100644
--- a/sphinx_gallery/backreferences.py
+++ b/sphinx_gallery/backreferences.py
@@ -242,14 +242,16 @@ THUMBNAIL_TEMPLATE = """
.. only:: html
- .. figure:: /{thumbnail}
- :alt: {title}
+ .. image:: /{thumbnail}
+ :alt: {title}
- :ref:`sphx_glr_{ref_name}`
+ :ref:`sphx_glr_{ref_name}`
.. raw:: html
+ <div class="sphx-glr-thumbnail-title">{title}</div>
</div>
+
"""
BACKREF_THUMBNAIL_TEMPLATE = THUMBNAIL_TEMPLATE + """
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 85f05e0..cc79b9a 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -343,6 +343,21 @@ def _get_readme(dir_, gallery_conf, raise_error=True):
return None
+THUMBNAIL_PARENT_DIV = """
+.. raw:: html
+
+ <div class="sphx-glr-thumbnails">
+
+"""
+
+THUMBNAIL_PARENT_DIV_CLOSE = """
+.. raw:: html
+
+ </div>
+
+"""
+
+
def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
"""Generate the gallery reStructuredText for an example directory."""
head_ref = os.path.relpath(target_dir, gallery_conf['src_dir'])
@@ -368,6 +383,11 @@ def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
# sort them
sorted_listdir = sorted(
listdir, key=gallery_conf['within_subsection_order'](src_dir))
+
+ # Add div containing all thumbnails;
+ # this is helpful for controlling grid or flexbox behaviours
+ fhindex += THUMBNAIL_PARENT_DIV
+
entries_text = []
costs = []
build_target_dir = os.path.relpath(target_dir, gallery_conf['src_dir'])
@@ -392,9 +412,8 @@ def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):
for entry_text in entries_text:
fhindex += entry_text
- # clear at the end of the section
- fhindex += """.. raw:: html\n
- <div class="sphx-glr-clear"></div>\n\n"""
+ # Close thumbnail parent div
+ fhindex += THUMBNAIL_PARENT_DIV_CLOSE
return fhindex, costs
@@ -1144,7 +1163,8 @@ def save_rst_example(example_rst, example_file, time_elapsed,
replace_py_ipynb(fname),
binder_badge_rst,
ref_fname)
- example_rst += SPHX_GLR_SIG
+ if gallery_conf['show_signature']:
+ example_rst += SPHX_GLR_SIG
write_file_new = re.sub(r'\.py$', '.rst.new', example_file)
with codecs.open(write_file_new, 'w', encoding="utf-8") as f:
|
sphinx-gallery/sphinx-gallery
|
cf860972ef019e4815b912fdd14ae6182386811a
|
diff --git a/sphinx_gallery/tests/test_backreferences.py b/sphinx_gallery/tests/test_backreferences.py
index 5afb819..3274516 100644
--- a/sphinx_gallery/tests/test_backreferences.py
+++ b/sphinx_gallery/tests/test_backreferences.py
@@ -20,15 +20,17 @@ REFERENCE = r"""
.. only:: html
- .. figure:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
- :alt: test title
+ .. image:: /fake_dir/images/thumb/sphx_glr_test_file_thumb.png
+ :alt: test title
- :ref:`sphx_glr_fake_dir_test_file.py`
+ :ref:`sphx_glr_fake_dir_test_file.py`
.. raw:: html
- </div>{1}
-"""
+ <div class="sphx-glr-thumbnail-title">test title</div>
+ </div>
+
+{1}"""
@pytest.mark.parametrize('content, tooltip, is_backref', [
@@ -56,10 +58,10 @@ def test_thumbnail_div(content, tooltip, is_backref):
check=False)
if is_backref:
extra = """
-
.. only:: not html
- * :ref:`sphx_glr_fake_dir_test_file.py`"""
+ * :ref:`sphx_glr_fake_dir_test_file.py`
+"""
else:
extra = ''
reference = REFERENCE.format(tooltip, extra)
diff --git a/sphinx_gallery/tests/test_full.py b/sphinx_gallery/tests/test_full.py
index 3ba93c7..4e18d44 100644
--- a/sphinx_gallery/tests/test_full.py
+++ b/sphinx_gallery/tests/test_full.py
@@ -772,19 +772,19 @@ def test_backreference_labels(sphinx_app):
@pytest.mark.parametrize(
'test, nlines, filenamesortkey', [
# first example, no heading
- ('Test 1-N', 6, False),
+ ('Test 1-N', 5, False),
# first example, default heading, default level
- ('Test 1-D-D', 8, False),
+ ('Test 1-D-D', 7, False),
# first example, default heading, custom level
- ('Test 1-D-C', 8, False),
+ ('Test 1-D-C', 7, False),
# first example, custom heading, default level
- ('Test 1-C-D', 9, False),
+ ('Test 1-C-D', 8, False),
# both examples, no heading
- ('Test 2-N', 11, True),
+ ('Test 2-N', 10, True),
# both examples, default heading, default level
- ('Test 2-D-D', 14, True),
+ ('Test 2-D-D', 13, True),
# both examples, custom heading, custom level
- ('Test 2-C-C', 15, True),
+ ('Test 2-C-C', 14, True),
]
)
def test_minigallery_directive(sphinx_app, test, nlines, filenamesortkey):
diff --git a/sphinx_gallery/tests/test_gen_gallery.py b/sphinx_gallery/tests/test_gen_gallery.py
index 705f1c5..75e061c 100644
--- a/sphinx_gallery/tests/test_gen_gallery.py
+++ b/sphinx_gallery/tests/test_gen_gallery.py
@@ -164,6 +164,12 @@ def test_spaces_in_files_warn(sphinx_app_wrapper):
def _check_order(sphinx_app, key):
+ """
+ Iterates through sphx-glr-thumbcontainer divs from index.rst lines
+ and reads given key from the tooltip.
+ Test that these keys appear in a specific order.
+ """
+
index_fname = os.path.join(sphinx_app.outdir, '..', 'ex', 'index.rst')
order = list()
regex = '.*:%s=(.):.*' % key
|
Make thumbnails grid- and flexbox-compatible
At the moment, sphinx-gallery generates a div for each gallery item.
These divs are `float: left` and have a pre-determined width, which does not render very nicely on most screen sizes or for long titles.
I suggest that for each subsection of the gallery, we add a parent div to these item divs.
This would allow users to either use css `grid` or `flex` (which we could also implement here directly).
It boils down to adding a new div before iterating through each gallery item and closing this div after:
https://github.com/sphinx-gallery/sphinx-gallery/blob/a68a48686138741ac38dcc15930293caeebcf484/sphinx_gallery/gen_rst.py#L371-L382
Also, maybe we could use [`sphinx-design`](https://github.com/executablebooks/sphinx-design) to handle the grid for us, but this would add a new dependency.
Happy to here what you think about this!
|
0.0
|
cf860972ef019e4815b912fdd14ae6182386811a
|
[
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[<\"test\">-<"test">-False]",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[test",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[1",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[use",
"sphinx_gallery/tests/test_backreferences.py::test_thumbnail_div[`this`"
] |
[
"sphinx_gallery/tests/test_backreferences.py::test_identify_names",
"sphinx_gallery/tests/test_backreferences.py::test_identify_names2",
"sphinx_gallery/tests/test_gen_gallery.py::test_bad_config",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files",
"sphinx_gallery/tests/test_gen_gallery.py::test_collect_gallery_files_ignore_pattern",
"sphinx_gallery/tests/test_gen_gallery.py::test_write_computation_times_noop"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-12 17:21:45+00:00
|
bsd-3-clause
| 5,671 |
|
spiral-project__ihatemoney-1039
|
diff --git a/ihatemoney/currency_convertor.py b/ihatemoney/currency_convertor.py
index 881d542..1139a44 100644
--- a/ihatemoney/currency_convertor.py
+++ b/ihatemoney/currency_convertor.py
@@ -1,3 +1,6 @@
+import traceback
+import warnings
+
from cachetools import TTLCache, cached
import requests
@@ -21,7 +24,14 @@ class CurrencyConverter(object, metaclass=Singleton):
@cached(cache=TTLCache(maxsize=1, ttl=86400))
def get_rates(self):
- rates = requests.get(self.api_url).json()["rates"]
+ try:
+ rates = requests.get(self.api_url).json()["rates"]
+ except Exception:
+ warnings.warn(
+ f"Call to {self.api_url} failed: {traceback.format_exc(limit=0).strip()}"
+ )
+ # In case of any exception, let's have an empty value
+ rates = {}
rates[self.no_currency] = 1.0
return rates
|
spiral-project/ihatemoney
|
b32abadd05114aad93cdf52eb616ae7a5c63d979
|
diff --git a/ihatemoney/tests/main_test.py b/ihatemoney/tests/main_test.py
index 5d69130..97ab82a 100644
--- a/ihatemoney/tests/main_test.py
+++ b/ihatemoney/tests/main_test.py
@@ -382,6 +382,16 @@ class TestCurrencyConverter(unittest.TestCase):
result = self.converter.exchange_currency(100, "USD", "EUR")
self.assertEqual(result, 80.0)
+ def test_failing_remote(self):
+ rates = {}
+ with patch("requests.Response.json", new=lambda _: {}), self.assertWarns(
+ UserWarning
+ ):
+ # we need a non-patched converter, but it seems that MagickMock
+ # is mocking EVERY instance of the class method. Too bad.
+ rates = CurrencyConverter.get_rates(self.converter)
+ self.assertDictEqual(rates, {CurrencyConverter.no_currency: 1})
+
if __name__ == "__main__":
unittest.main()
|
500 error because of exchangerate.host failing
Hi,
My own instance of ihm running 5.2.0 fails with
~~~
$ curl -i https://ihm.chown.me/
HTTP/2 500
server: nginx
date: Sun, 10 Jul 2022 01:14:46 GMT
content-type: text/html; charset=utf-8
content-length: 265
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
content-security-policy: default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'
strict-transport-security: max-age=31556926; includeSubDomains
referrer-policy: strict-origin-when-cross-origin
vary: Cookie
set-cookie: session=bleh; Secure; HttpOnly; Path=/; SameSite=Lax
<!doctype html>
<html lang=en>
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
~~~
Log says
~~~
ERROR [ihatemoney.run] Exception on / [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.10/site-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/src/ihatemoney/web.py", line 276, in home
project_form = get_project_form()
File "/src/ihatemoney/web.py", line 271, in get_project_form
return ProjectForm()
File "/usr/local/lib/python3.10/site-packages/wtforms/form.py", line 208, in __call__
return type.__call__(cls, *args, **kwargs)
File "/src/ihatemoney/forms.py", line 153, in __init__
for currency_name in self.currency_helper.get_currencies()
File "/src/ihatemoney/currency_convertor.py", line 31, in get_currencies
for rate in self.get_rates()
File "/usr/local/lib/python3.10/site-packages/cachetools/__init__.py", line 520, in wrapper
v = func(*args, **kwargs)
File "/src/ihatemoney/currency_convertor.py", line 24, in get_rates
rates = requests.get(self.api_url).json()["rates"]
KeyError: 'rates'
~~~
Code is
~~~
14 class CurrencyConverter(object, metaclass=Singleton):
15 # Get exchange rates
16 no_currency = "XXX"
17 api_url = "https://api.exchangerate.host/latest?base=USD"
18
19 def __init__(self):
20 pass
21
22 @cached(cache=TTLCache(maxsize=1, ttl=86400))
23 def get_rates(self):
24 rates = requests.get(self.api_url).json()["rates"]
25 rates[self.no_currency] = 1.0
26 return rates
~~~
Indeed the api doesn't work anymore here:
~~~
$ curl -4i "https://api.exchangerate.host/latest?base=USD"
HTTP/2 404
date: Sun, 10 Jul 2022 01:11:54 GMT
content-type: application/json; charset=utf-8
content-length: 17
x-dns-prefetch-control: off
x-frame-options: SAMEORIGIN
strict-transport-security: max-age=15552000; includeSubDomains
x-download-options: noopen
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
x-ratelimit-limit: 2000
x-ratelimit-remaining: 1998
access-control-allow-origin: *
access-control-allow-methods: GET
access-control-allow-credentials: false
access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept, Methods
x-forwarded-for: api.exchangerate.host
cache-control: max-age=31536000
etag: W/"11-UIVUdQWNarX1D9mk06okyEMbpS8"
vary: Accept-Encoding
cf-cache-status: HIT
age: 4306
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=PpE881p5ClV8zgzUG8mp8spUa3wngqOfil1u7w%2B%2FZZZNP7GotabJxMGXseH%2FpFBsFtlaUDo%2BmAcQB0LNlXA2zhVI%2BiA33eFoOQxvpVJlaLfRfspnXDWp2NPIIjiM1%2FY2aVHQASbmkEA%3D"}],"group":"cf-nel","max_age":604800}
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 72856d96cad34bc5-YUL
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
{"success":false}
~~~
It makes me sad that some third party service I didn't know about broke my instance. Can you please make ihm more resilient to exchangerate.host failure?
|
0.0
|
b32abadd05114aad93cdf52eb616ae7a5c63d979
|
[
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_failing_remote"
] |
[
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_default_configuration",
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_default_configuration_file",
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_env_var_configuration_file",
"ihatemoney/tests/main_test.py::ServerTestCase::test_homepage",
"ihatemoney/tests/main_test.py::ServerTestCase::test_prefixed",
"ihatemoney/tests/main_test.py::ServerTestCase::test_unprefixed",
"ihatemoney/tests/main_test.py::CommandTestCase::test_demo_project_deletion",
"ihatemoney/tests/main_test.py::CommandTestCase::test_generate_config",
"ihatemoney/tests/main_test.py::CommandTestCase::test_generate_password_hash",
"ihatemoney/tests/main_test.py::ModelsTestCase::test_bill_pay_each",
"ihatemoney/tests/main_test.py::ModelsTestCase::test_weighted_bills",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_creation_email_failure_smtp",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_creation_email_failure_socket",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_invitation_email_failure",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_password_reset_email_failure",
"ihatemoney/tests/main_test.py::CaptchaTestCase::test_api_project_creation_does_not_need_captcha",
"ihatemoney/tests/main_test.py::CaptchaTestCase::test_project_creation_with_captcha",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_exchange_currency",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_get_currencies",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_only_one_instance"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-10 13:37:23+00:00
|
bsd-2-clause
| 5,672 |
|
spiral-project__ihatemoney-1061
|
diff --git a/ihatemoney/forms.py b/ihatemoney/forms.py
index af44ead..c4fc32a 100644
--- a/ihatemoney/forms.py
+++ b/ihatemoney/forms.py
@@ -254,7 +254,7 @@ class ProjectFormWithCaptcha(ProjectForm):
)
def validate_captcha(self, field):
- if not field.data.lower() == _("euro"):
+ if not field.data.lower() == _("euro").lower():
message = _("Please, validate the captcha to proceed.")
raise ValidationError(Markup(message))
|
spiral-project/ihatemoney
|
8695b899db4091f3a1eca3c80b1377bf5a4c99ec
|
diff --git a/ihatemoney/tests/main_test.py b/ihatemoney/tests/main_test.py
index 97ab82a..f0a11d6 100644
--- a/ihatemoney/tests/main_test.py
+++ b/ihatemoney/tests/main_test.py
@@ -301,6 +301,23 @@ class EmailFailureTestCase(IhatemoneyTestCase):
class CaptchaTestCase(IhatemoneyTestCase):
ENABLE_CAPTCHA = True
+ def test_project_creation_with_captcha_case_insensitive(self):
+ # Test that case doesn't matter
+ # Patch the lazy_gettext as it is imported as '_' in forms for captcha value check
+ with patch("ihatemoney.forms._", new=lambda x: "ÉÙÜẞ"), self.client as c:
+ c.post(
+ "/create",
+ data={
+ "name": "raclette party",
+ "id": "raclette",
+ "password": "party",
+ "contact_email": "[email protected]",
+ "default_currency": "USD",
+ "captcha": "éùüß",
+ },
+ )
+ assert len(models.Project.query.all()) == 1
+
def test_project_creation_with_captcha(self):
with self.client as c:
c.post(
|
Creating new project on hosted site fails on captcha
Sorry in advance if this bug tracker is not meant for issues with the hosted site.
I tried to create a new project but the captcha validation always fails. I am 99.9% sure I am human and answering it correctly:

I tried in multiple browsers but always got the verification fail.
|
0.0
|
8695b899db4091f3a1eca3c80b1377bf5a4c99ec
|
[
"ihatemoney/tests/main_test.py::CaptchaTestCase::test_project_creation_with_captcha_case_insensitive"
] |
[
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_default_configuration",
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_default_configuration_file",
"ihatemoney/tests/main_test.py::ConfigurationTestCase::test_env_var_configuration_file",
"ihatemoney/tests/main_test.py::ServerTestCase::test_homepage",
"ihatemoney/tests/main_test.py::ServerTestCase::test_prefixed",
"ihatemoney/tests/main_test.py::ServerTestCase::test_unprefixed",
"ihatemoney/tests/main_test.py::CommandTestCase::test_demo_project_deletion",
"ihatemoney/tests/main_test.py::CommandTestCase::test_generate_config",
"ihatemoney/tests/main_test.py::CommandTestCase::test_generate_password_hash",
"ihatemoney/tests/main_test.py::ModelsTestCase::test_bill_pay_each",
"ihatemoney/tests/main_test.py::ModelsTestCase::test_weighted_bills",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_creation_email_failure_smtp",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_creation_email_failure_socket",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_invitation_email_failure",
"ihatemoney/tests/main_test.py::EmailFailureTestCase::test_password_reset_email_failure",
"ihatemoney/tests/main_test.py::CaptchaTestCase::test_api_project_creation_does_not_need_captcha",
"ihatemoney/tests/main_test.py::CaptchaTestCase::test_project_creation_with_captcha",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_exchange_currency",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_failing_remote",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_get_currencies",
"ihatemoney/tests/main_test.py::TestCurrencyConverter::test_only_one_instance"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-09 20:18:25+00:00
|
bsd-2-clause
| 5,673 |
|
spiral-project__ihatemoney-1108
|
diff --git a/ihatemoney/static/css/main.css b/ihatemoney/static/css/main.css
index 1700fec..713e706 100644
--- a/ihatemoney/static/css/main.css
+++ b/ihatemoney/static/css/main.css
@@ -14,18 +14,22 @@ body {
.navbar-brand span {
color: #abe128;
}
+
.navbar h1 {
font-size: 1rem;
margin: 0;
padding: 0;
}
+
.navbar .secondary-nav {
text-align: right;
flex-direction: row-reverse;
}
+
.secondary-nav .nav-link {
padding: 0.5rem 1rem;
}
+
.navbar-brand {
font-family: "Lobster", arial, serif;
font-size: 1.5rem;
@@ -51,7 +55,8 @@ body {
font-size: 2.4em;
}
-#header .tryout, #header .showcase {
+#header .tryout,
+#header .showcase {
color: #fff;
background-color: #414141;
border-color: #414141;
@@ -59,7 +64,8 @@ body {
margin-right: 3px;
}
-#header .tryout:hover, #header .showcase:hover {
+#header .tryout:hover,
+#header .showcase:hover {
background-color: #606060;
border-color: #606060;
cursor: pointer;
@@ -91,9 +97,11 @@ body {
.balance tr td {
font-weight: bold;
}
+
.positive {
color: green;
}
+
.negative {
color: red;
}
@@ -113,6 +121,7 @@ body {
flex: 1 1 auto;
overflow-y: auto;
}
+
.identifier {
margin-bottom: 15px;
}
@@ -143,10 +152,12 @@ body {
.home-container {
background: linear-gradient(150deg, #abe128 0%, #43ca61 100%);
}
+
.home {
padding-top: 1em;
padding-bottom: 3em;
}
+
#authentication-form legend {
text-align: right;
}
@@ -160,11 +171,13 @@ body {
margin-bottom: 20px;
margin-left: 25px;
}
+
@media (max-width: 450px) {
.home .card {
min-width: unset;
}
}
+
/* Other */
#bills {
@@ -174,6 +187,7 @@ body {
.empty-bill {
margin-top: 5rem !important;
}
+
.empty-bill .card {
border: 0;
}
@@ -250,12 +264,15 @@ footer .footer-right a {
border-radius: 50%;
opacity: 0.5;
}
+
@-moz-document url-prefix() {
+
/** Firefox style fix **/
footer .footer-right a {
padding-top: 2px;
}
}
+
footer .footer-right a:hover {
opacity: 1;
}
@@ -268,6 +285,7 @@ footer .footer-left {
/* If you don't want the footer to be responsive, remove these media queries */
@media (max-width: 600px) {
+
footer .footer-left,
footer .footer-right {
text-align: center;
@@ -298,9 +316,9 @@ footer .footer-left {
position: relative;
}
-.bill-actions > form > .delete,
-.bill-actions > .edit,
-.bill-actions > .show {
+.bill-actions>form>.delete,
+.bill-actions>.edit,
+.bill-actions>.show {
font-size: 0px;
display: block;
width: 16px;
@@ -316,15 +334,15 @@ footer .footer-left {
height: calc(100% - 8px);
}
-.bill-actions > form > .delete {
+.bill-actions>form>.delete {
background: url("../images/delete.png") no-repeat right;
}
-.bill-actions > .edit {
+.bill-actions>.edit {
background: url("../images/edit.png") no-repeat right;
}
-.bill-actions > .show {
+.bill-actions>.show {
background: url("../images/show.png") no-repeat right;
}
@@ -344,6 +362,7 @@ footer .footer-left {
}
@media (min-width: 768px) {
+
.split_bills,
#table_overflow.statistics {
/* The table is shifted to left, so add the spacer width on the right to match */
@@ -351,9 +370,9 @@ footer .footer-left {
}
}
-.project-actions > .delete,
-.project-actions > .edit,
-.project-actions > .show {
+.project-actions>form>.delete,
+.project-actions>.edit,
+.project-actions>.show {
font-size: 0px;
display: block;
width: 16px;
@@ -363,21 +382,22 @@ footer .footer-left {
float: left;
}
-.project-actions > .delete {
+.project-actions>form>.delete {
background: url("../images/delete.png") no-repeat right;
+ border: 0px !important;
}
-.project-actions > .edit {
+.project-actions>.edit {
background: url("../images/edit.png") no-repeat right;
}
-.project-actions > .show {
+.project-actions>.show {
background: url("../images/show.png") no-repeat right;
}
-.history_icon > .delete,
-.history_icon > .add,
-.history_icon > .edit {
+.history_icon>.delete,
+.history_icon>.add,
+.history_icon>.edit {
font-size: 0px;
display: block;
width: 16px;
@@ -388,15 +408,15 @@ footer .footer-left {
float: left;
}
-.history_icon > .delete {
+.history_icon>.delete {
background: url("../images/delete.png") no-repeat right;
}
-.history_icon > .edit {
+.history_icon>.edit {
background: url("../images/edit.png") no-repeat right;
}
-.history_icon > .add {
+.history_icon>.add {
background: url("../images/add.png") no-repeat right;
}
@@ -461,7 +481,7 @@ tr.payer_line .balance-name {
margin-top: 30px;
}
-#bill-form > fieldset {
+#bill-form>fieldset {
margin-top: 10px;
}
@@ -485,64 +505,81 @@ tr:hover .extra-info {
/* Fluid Offsets for Boostrap */
-.row-fluid > [class*="span"]:not([class*="offset"]):first-child {
+.row-fluid>[class*="span"]:not([class*="offset"]):first-child {
margin-left: 0;
}
-.row-fluid > .offset12 {
+
+.row-fluid>.offset12 {
margin-left: 100%;
}
-.row-fluid > .offset11 {
+
+.row-fluid>.offset11 {
margin-left: 93.5%;
}
-.row-fluid > .offset10 {
+
+.row-fluid>.offset10 {
margin-left: 85%;
}
-.row-fluid > .offset9 {
+
+.row-fluid>.offset9 {
margin-left: 76.5%;
}
-.row-fluid > .offset8 {
+
+.row-fluid>.offset8 {
margin-left: 68%;
}
-.row-fluid > .offset7 {
+
+.row-fluid>.offset7 {
margin-left: 59.5%;
}
-.row-fluid > .offset6 {
+
+.row-fluid>.offset6 {
margin-left: 51%;
}
-.row-fluid > .offset5 {
+
+.row-fluid>.offset5 {
margin-left: 42.5%;
}
-.row-fluid > .offset4 {
+
+.row-fluid>.offset4 {
margin-left: 34%;
}
-.row-fluid > .offset3 {
+
+.row-fluid>.offset3 {
margin-left: 25.5%;
}
-.row-fluid > .offset2 {
+
+.row-fluid>.offset2 {
margin-left: 17%;
}
-.row-fluid > .offset1 {
+
+.row-fluid>.offset1 {
margin-left: 8.5%;
}
.globe-europe svg {
fill: rgba(255, 255, 255, 0.5);
}
+
.navbar-nav .dropdown-toggle:hover .globe-europe svg {
fill: rgba(255, 255, 255, 0.75);
}
-.navbar-dark .navbar-nav .show > .nav-link svg {
+
+.navbar-dark .navbar-nav .show>.nav-link svg {
fill: white;
}
+
.navbar-dark .dropdown-menu {
max-height: 50vh;
overflow-y: auto;
}
+
.icon svg {
display: inline-block;
border-bottom: 0.2em solid transparent;
height: 1.2em;
- width: 1.2em; /* protection for IE11 */
+ width: 1.2em;
+ /* protection for IE11 */
}
.icon.high svg {
@@ -558,9 +595,11 @@ tr:hover .extra-info {
.icon.before-text svg {
margin-right: 3px;
}
+
footer .icon svg {
fill: white;
}
+
.icon.icon-white {
fill: white;
}
@@ -568,7 +607,8 @@ footer .icon svg {
.icon.icon-red {
fill: #dc3545;
}
-.btn:hover .icon.icon-red {
+
+.btn:hover .icon.icon-red {
fill: white !important;
}
@@ -592,6 +632,7 @@ footer .icon svg {
margin-top: 1em;
margin-bottom: 3em;
}
+
.edit-project .custom-file {
margin-bottom: 2em;
-}
+}
\ No newline at end of file
diff --git a/ihatemoney/templates/dashboard.html b/ihatemoney/templates/dashboard.html
index 6036de9..15baf96 100644
--- a/ihatemoney/templates/dashboard.html
+++ b/ihatemoney/templates/dashboard.html
@@ -2,34 +2,53 @@
{% block content %}
{% if is_admin_dashboard_activated %}
<table id="bill_table" class="table table-striped">
- <thead><tr><th>{{ _("Project") }}</th><th>{{ _("Number of participants") }}</th><th>{{ _("Number of bills") }}</th><th>{{_("Newest bill")}}</th><th>{{_("Oldest bill")}}</th><th>{{_("Actions")}}</th></tr></thead>
+ <thead>
+ <tr>
+ <th>{{ _("Project") }}</th>
+ <th>{{ _("Number of participants") }}</th>
+ <th>{{ _("Number of bills") }}</th>
+ <th>{{_("Newest bill")}}</th>
+ <th>{{_("Oldest bill")}}</th>
+ <th>{{_("Actions")}}</th>
+ </tr>
+ </thead>
<tbody>{% for project in projects|sort(attribute='name') %}
<tr>
- <td><a href="{{ url_for(".list_bills", project_id=project.id) }}" title="{{ project.name }}">{{ project.name }}</a></td><td>{{ project.members | count }}</td><td>{{ project.get_bills_unordered().count() }}</td>
- {% if project.has_bills() %}
- <td>{{ project.get_bills().all()[0].date }}</td>
- <td>{{ project.get_bills().all()[-1].date }}</td>
- {% else %}
- <td></td>
- <td></td>
- {% endif %}
- <td class="project-actions">
- <a class="edit" href="{{ url_for(".edit_project", project_id=project.id) }}" title="{{ _("edit") }}">{{ _('edit') }}</a>
- <a class="delete" href="{{ url_for(".delete_project", project_id=project.id) }}" title="{{ _("delete") }}">{{ _('delete') }}</a>
- <a class="show" href="{{ url_for(".list_bills", project_id=project.id) }}" title="{{ _("show") }}">{{ _('show') }}</a>
- </td>
+ <td><a href="{{ url_for('.list_bills', project_id=project.id) }}"
+ title="{{ project.name }}">{{project.name}}</a></td>
+ <td>{{ project.members | count }}</td>
+ <td>{{ project.get_bills_unordered().count() }}</td>
+ {% if project.has_bills() %}
+ <td>{{ project.get_bills().all()[0].date }}</td>
+ <td>{{ project.get_bills().all()[-1].date }}</td>
+ {% else %}
+ <td></td>
+ <td></td>
+ {% endif %}
+ <td class="project-actions">
+ <a class="edit" href="{{ url_for('.edit_project', project_id=project.id) }}" title=" {{ _('edit')}}">{{
+ _('edit') }}</a>
+
+ <form id="delete-project" class="form-horizontal" action="{{ url_for('.dashboard_delete_project',
+ project_id=project.id) }}" method="post">
+
+ <button class="delete">{{ _("Delete project") }}</button>
+ </form>
+ <a class="show" href="{{ url_for('.list_bills', project_id=project.id) }}" title="{{ _(" show") }}">{{
+ _('show') }}</a>
+ </td>
</tr>
- {% endfor %}
+ {% endfor %}
</tbody>
</table>
<script language="JavaScript">
-$(document).ready(function() {
- $('#bill_table').DataTable({
- paging: true
- });
-})
+ $(document).ready(function () {
+ $('#bill_table').DataTable({
+ paging: true
+ });
+ })
</script>
{% else %}
<div class="alert alert-danger">{{ _("The Dashboard is currently deactivated.") }}</div>
{% endif %}
-{% endblock %}
+{% endblock %}
\ No newline at end of file
diff --git a/ihatemoney/web.py b/ihatemoney/web.py
index b94a66d..9417ace 100644
--- a/ihatemoney/web.py
+++ b/ihatemoney/web.py
@@ -888,10 +888,19 @@ def dashboard():
return render_template(
"dashboard.html",
projects=Project.query.all(),
+ delete_project_form=DestructiveActionProjectForm,
is_admin_dashboard_activated=is_admin_dashboard_activated,
)
[email protected]("/dashboard/<project_id>/delete", methods=["POST"])
+@requires_admin()
+def dashboard_delete_project():
+ g.project.remove_project()
+ flash(_("Project successfully deleted"))
+ return redirect(request.headers.get("Referer") or url_for(".home"))
+
+
@main.route("/favicon.ico")
def favicon():
return send_from_directory(
|
spiral-project/ihatemoney
|
97a0aea2ba2d5709c4cf85bd1d263145f4c534bf
|
diff --git a/ihatemoney/tests/budget_test.py b/ihatemoney/tests/budget_test.py
index ee10319..a4dcf9e 100644
--- a/ihatemoney/tests/budget_test.py
+++ b/ihatemoney/tests/budget_test.py
@@ -926,18 +926,30 @@ class BudgetTestCase(IhatemoneyTestCase):
self.assertIn('<div class="alert alert-danger">', resp.data.decode("utf-8"))
# test access to the dashboard when it is activated
- self.app.config["ACTIVATE_ADMIN_DASHBOARD"] = True
- self.app.config["ADMIN_PASSWORD"] = generate_password_hash("adminpass")
- resp = self.client.post(
- "/admin?goto=%2Fdashboard",
- data={"admin_password": "adminpass"},
- follow_redirects=True,
- )
+ self.enable_admin()
+ resp = self.client.get("/dashboard")
self.assertIn(
- "<thead><tr><th>Project</th><th>Number of participants",
+ """<thead>
+ <tr>
+ <th>Project</th>
+ <th>Number of participants</th>""",
resp.data.decode("utf-8"),
)
+ def test_dashboard_project_deletion(self):
+ self.post_project("raclette")
+ self.enable_admin()
+ resp = self.client.get("/dashboard")
+ pattern = re.compile(r"<form id=\"delete-project\" [^>]*?action=\"(.*?)\"")
+ match = pattern.search(resp.data.decode("utf-8"))
+ assert match is not None
+ assert match.group(1) is not None
+
+ resp = self.client.post(match.group(1))
+
+ # project removed
+ assert len(models.Project.query.all()) == 0
+
def test_statistics_page(self):
self.post_project("raclette")
response = self.client.get("/raclette/statistics")
diff --git a/ihatemoney/tests/common/ihatemoney_testcase.py b/ihatemoney/tests/common/ihatemoney_testcase.py
index 4b11d47..7047537 100644
--- a/ihatemoney/tests/common/ihatemoney_testcase.py
+++ b/ihatemoney/tests/common/ihatemoney_testcase.py
@@ -110,3 +110,12 @@ class IhatemoneyTestCase(BaseTestCase):
resp.status_code,
f"{url} expected {expected}, got {resp.status_code}",
)
+
+ def enable_admin(self, password="adminpass"):
+ self.app.config["ACTIVATE_ADMIN_DASHBOARD"] = True
+ self.app.config["ADMIN_PASSWORD"] = generate_password_hash(password)
+ return self.client.post(
+ "/admin?goto=%2Fdashboard",
+ data={"admin_password": password},
+ follow_redirects=True,
+ )
|
Deleting a project in admin-dashboard
I’m still experiencing the same issue as #978. I cannot delete any project from the Admin dashboard.
I’m using docker which works perfectly otherwise.
Problem occurs with SESSION_COOKIE_SECURE set to True or False. No difference.
|
0.0
|
97a0aea2ba2d5709c4cf85bd1d263145f4c534bf
|
[
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_dashboard",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_dashboard_project_deletion"
] |
[
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_access_other_projects",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_admin_authentication",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_is_null",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_too_high",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication_with_upper_case",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_bill_placeholder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_bill_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_no_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_deactivated_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_decimals_on_weighted_members_list",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_edit_project",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite_code_invalidation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_login_throttler",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_manage_bills",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_member_delete_method",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_membership",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_multiple_join",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_negative_weight",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_notifications",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reminder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reset",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_person_model",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_with_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_without_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_deletion",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_rounding",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_zero",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_trimmed_members",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_balance",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_members_list"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-11 13:26:31+00:00
|
bsd-2-clause
| 5,674 |
|
spiral-project__ihatemoney-1193
|
diff --git a/ihatemoney/web.py b/ihatemoney/web.py
index c14c9b9..9e03402 100644
--- a/ihatemoney/web.py
+++ b/ihatemoney/web.py
@@ -322,8 +322,7 @@ def create_project():
db.session.commit()
# create the session object (authenticate)
- session[project.id] = True
- session.update()
+ set_authorized_project(project)
# send reminder email
g.project = project
|
spiral-project/ihatemoney
|
e61540dbbe0a1541249d9ad7d0b4a16639e16ebe
|
diff --git a/ihatemoney/tests/budget_test.py b/ihatemoney/tests/budget_test.py
index 696a4cd..1b51554 100644
--- a/ihatemoney/tests/budget_test.py
+++ b/ihatemoney/tests/budget_test.py
@@ -119,6 +119,16 @@ class BudgetTestCase(IhatemoneyTestCase):
resp = self.client.get("/raclette/join/token.invalid", follow_redirects=True)
self.assertIn("Provided token is invalid", resp.data.decode("utf-8"))
+ def test_create_should_remember_project(self):
+ """Test that creating a project adds it to the "logged in project" list,
+ as it does for authentication
+ """
+ self.login("raclette")
+ self.post_project("raclette")
+ self.post_project("tartiflette")
+ data = self.client.get("/raclette/").data.decode("utf-8")
+ self.assertEqual(data.count('href="/tartiflette/"'), 1)
+
def test_multiple_join(self):
"""Test that joining multiple times a project
doesn't add it multiple times in the session"""
|
Creating a project doesn't remember it
Currently, authentication form adds the project in a list that is rendered to quickly switch between project.
However, **creating** a project doesn't add it to this list.
|
0.0
|
e61540dbbe0a1541249d9ad7d0b4a16639e16ebe
|
[
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_create_should_remember_project"
] |
[
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_access_other_projects",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_admin_authentication",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_is_null",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_too_high",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication_with_upper_case",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_bill_placeholder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_bill_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_no_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_dashboard",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_dashboard_project_deletion",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_deactivated_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_decimals_on_weighted_members_list",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_edit_project",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite_code_invalidation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_login_throttler",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_manage_bills",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_member_delete_method",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_membership",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_multiple_join",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_negative_weight",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_notifications",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reminder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reset",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_person_model",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_with_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_without_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_deletion",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_rounding",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_zero",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_trimmed_members",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_balance",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_members_list"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-15 13:17:27+00:00
|
bsd-2-clause
| 5,675 |
|
spiral-project__ihatemoney-989
|
diff --git a/ihatemoney/forms.py b/ihatemoney/forms.py
index 2a7ba24..f1e852e 100644
--- a/ihatemoney/forms.py
+++ b/ihatemoney/forms.py
@@ -1,4 +1,5 @@
from datetime import datetime
+import decimal
from re import match
from types import SimpleNamespace
@@ -26,6 +27,7 @@ try:
from wtforms.fields.html5 import URLField
except ModuleNotFoundError:
from wtforms.fields import URLField
+
from wtforms.validators import (
URL,
DataRequired,
@@ -382,8 +384,11 @@ class BillForm(FlaskForm):
self.payed_for.data = self.payed_for.default
def validate_amount(self, field):
- if field.data == 0:
+ if field.data == "0":
raise ValidationError(_("Bills can't be null"))
+ elif decimal.Decimal(field.data) > decimal.MAX_EMAX:
+ # See https://github.com/python-babel/babel/issues/821
+ raise ValidationError(f"Result is too high: {field.data}")
class MemberForm(FlaskForm):
diff --git a/ihatemoney/models.py b/ihatemoney/models.py
index 8385ae7..3ff1087 100644
--- a/ihatemoney/models.py
+++ b/ihatemoney/models.py
@@ -21,7 +21,6 @@ from sqlalchemy_continuum.plugins import FlaskPlugin
from werkzeug.security import generate_password_hash
from ihatemoney.currency_convertor import CurrencyConverter
-from ihatemoney.patch_sqlalchemy_continuum import PatchedBuilder
from ihatemoney.utils import get_members, same_bill
from ihatemoney.versioning import (
ConditionalVersioningManager,
@@ -36,9 +35,6 @@ make_versioned(
# Conditionally Disable the versioning based on each
# project's privacy preferences
tracking_predicate=version_privacy_predicate,
- # Patch in a fix to a SQLAchemy-Continuum Bug.
- # See patch_sqlalchemy_continuum.py
- builder=PatchedBuilder(),
),
plugins=[
FlaskPlugin(
diff --git a/ihatemoney/patch_sqlalchemy_continuum.py b/ihatemoney/patch_sqlalchemy_continuum.py
deleted file mode 100644
index eecfe6f..0000000
--- a/ihatemoney/patch_sqlalchemy_continuum.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""
-A temporary work-around to patch SQLAlchemy-continuum per:
-https://github.com/kvesteri/sqlalchemy-continuum/pull/242
-
-Source code reproduced under their license:
-
- Copyright (c) 2012, Konsta Vesterinen
-
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- * The names of the contributors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
- OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-import sqlalchemy as sa
-from sqlalchemy_continuum import Operation
-from sqlalchemy_continuum.builder import Builder
-from sqlalchemy_continuum.expression_reflector import VersionExpressionReflector
-from sqlalchemy_continuum.relationship_builder import RelationshipBuilder
-from sqlalchemy_continuum.utils import adapt_columns, option
-
-
-class PatchedRelationShipBuilder(RelationshipBuilder):
- def association_subquery(self, obj):
- """
- Returns an EXISTS clause that checks if an association exists for given
- SQLAlchemy declarative object. This query is used by
- many_to_many_criteria method.
-
- Example query:
-
- .. code-block:: sql
-
- EXISTS (
- SELECT 1
- FROM article_tag_version
- WHERE article_id = 3
- AND tag_id = tags_version.id
- AND operation_type != 2
- AND EXISTS (
- SELECT 1
- FROM article_tag_version as article_tag_version2
- WHERE article_tag_version2.tag_id = article_tag_version.tag_id
- AND article_tag_version2.tx_id <=5
- AND article_tag_version2.article_id = 3
- GROUP BY article_tag_version2.tag_id
- HAVING
- MAX(article_tag_version2.tx_id) =
- article_tag_version.tx_id
- )
- )
-
- :param obj: SQLAlchemy declarative object
- """
-
- tx_column = option(obj, "transaction_column_name")
- join_column = self.property.primaryjoin.right.name
- object_join_column = self.property.primaryjoin.left.name
- reflector = VersionExpressionReflector(obj, self.property)
-
- association_table_alias = self.association_version_table.alias()
- association_cols = [
- association_table_alias.c[association_col.name]
- for _, association_col in self.remote_to_association_column_pairs
- ]
-
- association_exists = sa.exists(
- sa.select([1])
- .where(
- sa.and_(
- association_table_alias.c[tx_column] <= getattr(obj, tx_column),
- association_table_alias.c[join_column]
- == getattr(obj, object_join_column),
- *[
- association_col
- == self.association_version_table.c[association_col.name]
- for association_col in association_cols
- ],
- )
- )
- .group_by(*association_cols)
- .having(
- sa.func.max(association_table_alias.c[tx_column])
- == self.association_version_table.c[tx_column]
- )
- .correlate(self.association_version_table)
- )
- return sa.exists(
- sa.select([1])
- .where(
- sa.and_(
- reflector(self.property.primaryjoin),
- association_exists,
- self.association_version_table.c.operation_type != Operation.DELETE,
- adapt_columns(self.property.secondaryjoin),
- )
- )
- .correlate(self.local_cls, self.remote_cls)
- )
-
-
-class PatchedBuilder(Builder):
- def build_relationships(self, version_classes):
- """
- Builds relationships for all version classes.
-
- :param version_classes: list of generated version classes
- """
- for cls in version_classes:
- if not self.manager.option(cls, "versioning"):
- continue
-
- for prop in sa.inspect(cls).iterate_properties:
- if prop.key == "versions":
- continue
- builder = PatchedRelationShipBuilder(self.manager, cls, prop)
- builder()
diff --git a/ihatemoney/templates/forms.html b/ihatemoney/templates/forms.html
index f93cfc6..78398ce 100644
--- a/ihatemoney/templates/forms.html
+++ b/ihatemoney/templates/forms.html
@@ -166,7 +166,9 @@
{{ input(form.date, inline=True) }}
{{ input(form.what, inline=True) }}
{{ input(form.payer, inline=True, class="form-control custom-select") }}
- {{ input(form.amount, inline=True) }}
+ <div data-toggle="tooltip" data-placement="top" title='{{ _("Simple operations are allowed, e.g. (18+36.2)/3") }}'>
+ {{ input(form.amount, inline=True) }}
+ </div>
<div class="form-group row">
<label class="col-3" for="payed_for">{{ _("For whom?") }}</label>
diff --git a/setup.cfg b/setup.cfg
index 2e4fd40..e80866b 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -40,7 +40,7 @@ install_requires =
itsdangerous>=2,<3
Jinja2>=3,<4
requests>=2.22,<3
- SQLAlchemy-Continuum>=1.3.9,<2
+ SQLAlchemy-Continuum>=1.3.12,<2
SQLAlchemy>=1.3.0,<1.4 # New 1.4 changes API, see #728
python-dateutil
|
spiral-project/ihatemoney
|
a5452ccee505aa084a127e61385a24a34a908023
|
diff --git a/ihatemoney/tests/api_test.py b/ihatemoney/tests/api_test.py
index f5475b1..69c6ab8 100644
--- a/ihatemoney/tests/api_test.py
+++ b/ihatemoney/tests/api_test.py
@@ -910,6 +910,25 @@ class APITestCase(IhatemoneyTestCase):
self.assertEqual(resp.data.decode("utf-8").count("<td> -- </td>"), 2)
self.assertNotIn("127.0.0.1", resp.data.decode("utf-8"))
+ def test_amount_is_null(self):
+ self.api_create("raclette")
+ # add participants
+ self.api_add_member("raclette", "zorglub")
+
+ # add a bill null amount
+ req = self.client.post(
+ "/api/projects/raclette/bills",
+ data={
+ "date": "2011-08-10",
+ "what": "fromage",
+ "payer": "1",
+ "payed_for": ["1"],
+ "amount": "0",
+ },
+ headers=self.get_auth("raclette"),
+ )
+ self.assertStatus(400, req)
+
def test_project_creation_with_mixed_case(self):
self.api_create("Raclette")
# get information about it
@@ -918,6 +937,26 @@ class APITestCase(IhatemoneyTestCase):
)
self.assertStatus(200, resp)
+ def test_amount_too_high(self):
+ self.api_create("raclette")
+ # add participants
+ self.api_add_member("raclette", "zorglub")
+
+ # add a bill with too high amount
+ # See https://github.com/python-babel/babel/issues/821
+ req = self.client.post(
+ "/api/projects/raclette/bills",
+ data={
+ "date": "2011-08-10",
+ "what": "fromage",
+ "payer": "1",
+ "payed_for": ["1"],
+ "amount": "9347242149381274732472348728748723473278472843.12",
+ },
+ headers=self.get_auth("raclette"),
+ )
+ self.assertStatus(400, req)
+
if __name__ == "__main__":
unittest.main()
diff --git a/ihatemoney/tests/budget_test.py b/ihatemoney/tests/budget_test.py
index f778109..d94c618 100644
--- a/ihatemoney/tests/budget_test.py
+++ b/ihatemoney/tests/budget_test.py
@@ -1531,6 +1531,30 @@ class BudgetTestCase(IhatemoneyTestCase):
]
assert no_currency_bills == [(5.0, 5.0), (10.0, 10.0)]
+ def test_amount_is_null(self):
+ self.post_project("raclette")
+
+ # add participants
+ self.client.post("/raclette/members/add", data={"name": "zorglub"})
+
+ # null amount
+ resp = self.client.post(
+ "/raclette/add",
+ data={
+ "date": "2016-12-31",
+ "what": "fromage à raclette",
+ "payer": 1,
+ "payed_for": [1],
+ "amount": "0",
+ "original_currency": "EUR",
+ },
+ )
+ assert '<p class="alert alert-danger">' in resp.data.decode("utf-8")
+
+ resp = self.client.get("/raclette/")
+ # No bills, the previous one was not added
+ assert "No bills" in resp.data.decode("utf-8")
+
def test_decimals_on_weighted_members_list(self):
self.post_project("raclette")
@@ -1554,6 +1578,32 @@ class BudgetTestCase(IhatemoneyTestCase):
'fred<span class="light">(x1.15)</span>', resp.data.decode("utf-8")
)
+ def test_amount_too_high(self):
+ self.post_project("raclette")
+
+ # add participants
+ self.client.post("/raclette/members/add", data={"name": "zorglub"})
+
+ # High amount should be rejected.
+ # See https://github.com/python-babel/babel/issues/821
+ resp = self.client.post(
+ "/raclette/add",
+ data={
+ "date": "2016-12-31",
+ "what": "fromage à raclette",
+ "payer": 1,
+ "payed_for": [1],
+ "amount": "9347242149381274732472348728748723473278472843.12",
+ "original_currency": "EUR",
+ },
+ )
+ assert '<p class="alert alert-danger">' in resp.data.decode("utf-8")
+
+ # Without any check, the following request will fail.
+ resp = self.client.get("/raclette/")
+ # No bills, the previous one was not added
+ assert "No bills" in resp.data.decode("utf-8")
+
if __name__ == "__main__":
unittest.main()
|
High integer can corrupt demo database
So yesterday, I was trying out the demo on ihatemoney.org. And, I entered in a really high integer (something as big as 9347242149381274732472348728748723473278472843.) Now, it is easy to repair, but it requires editing your database. I did this on my own database again (nothing important is on it), and it gave me an internal server error. And yes, the ihatemoney.org demo I accidently corrupted still isn't working.
**Steps to reproduce**
1. Go into demo
2. Add a new bill
3. Add a big number, like 9347242149381274732472348728748723473278472843
Some error handling needs to be added.
|
0.0
|
a5452ccee505aa084a127e61385a24a34a908023
|
[
"ihatemoney/tests/api_test.py::APITestCase::test_amount_is_null",
"ihatemoney/tests/api_test.py::APITestCase::test_amount_too_high",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_is_null",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_amount_too_high"
] |
[
"ihatemoney/tests/api_test.py::APITestCase::test_basic_auth",
"ihatemoney/tests/api_test.py::APITestCase::test_bills",
"ihatemoney/tests/api_test.py::APITestCase::test_bills_with_calculation",
"ihatemoney/tests/api_test.py::APITestCase::test_cors_requests",
"ihatemoney/tests/api_test.py::APITestCase::test_currencies",
"ihatemoney/tests/api_test.py::APITestCase::test_log_created_from_api_call",
"ihatemoney/tests/api_test.py::APITestCase::test_member",
"ihatemoney/tests/api_test.py::APITestCase::test_project",
"ihatemoney/tests/api_test.py::APITestCase::test_project_creation_with_mixed_case",
"ihatemoney/tests/api_test.py::APITestCase::test_statistics",
"ihatemoney/tests/api_test.py::APITestCase::test_token_creation",
"ihatemoney/tests/api_test.py::APITestCase::test_token_login",
"ihatemoney/tests/api_test.py::APITestCase::test_username_xss",
"ihatemoney/tests/api_test.py::APITestCase::test_weighted_bills",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_access_other_projects",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_authentication_with_upper_case",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_bill_placeholder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_bill_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_currency_switch_to_no_currency",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_dashboard",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_deactivated_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_decimals_on_weighted_members_list",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_demo",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_edit_project",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_invite_code_invalidation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_login_throttler",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_manage_bills",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_member_delete_method",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_membership",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_negative_weight",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_notifications",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reminder",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_password_reset",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_person_model",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_with_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_creation_without_public_permissions",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_project_deletion",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_rounding",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_settle_zero",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_statistics_page",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_trimmed_members",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_balance",
"ihatemoney/tests/budget_test.py::BudgetTestCase::test_weighted_members_list"
] |
{
"failed_lite_validators": [
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-30 15:15:05+00:00
|
bsd-2-clause
| 5,676 |
|
spotify__cstar-22
|
diff --git a/cstar/job.py b/cstar/job.py
index 1dacab8..bfa60cc 100644
--- a/cstar/job.py
+++ b/cstar/job.py
@@ -29,7 +29,7 @@ import cstar.jobrunner
import cstar.jobprinter
import cstar.jobwriter
from cstar.exceptions import BadSSHHost, NoHostsSpecified, HostIsDown, \
- NoDefaultKeyspace, UnknownHost
+ NoDefaultKeyspace, UnknownHost, FailedExecution
from cstar.output import msg, debug, emph, info, error
MAX_ATTEMPTS = 3
@@ -144,9 +144,9 @@ class Job(object):
keyspaces = [self.key_space]
else:
keyspaces = self.get_keyspaces(conn)
-
+ has_error = True
for keyspace in keyspaces:
- if keyspace != "system":
+ try:
debug("Fetching endpoint mapping for keyspace", keyspace)
res = conn.run(("nodetool", "describering", keyspace))
has_error = False
@@ -157,6 +157,9 @@ class Job(object):
describering = cstar.nodetoolparser.parse_nodetool_describering(res.out)
range_mapping = cstar.nodetoolparser.convert_describering_to_range_mapping(describering)
mappings.append(cstar.endpoint_mapping.parse(range_mapping, topology, lookup=ip_lookup))
+ except Exception as e:
+ if not keyspace.startswith("system"):
+ raise FailedExecution(e)
if not has_error:
return cstar.endpoint_mapping.merge(mappings)
diff --git a/cstar/nodetoolparser/simple.py b/cstar/nodetoolparser/simple.py
index ff02d39..f9227bf 100644
--- a/cstar/nodetoolparser/simple.py
+++ b/cstar/nodetoolparser/simple.py
@@ -22,8 +22,7 @@ _ip_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
_token_re = re.compile(r"^\-?\d+$")
_status_re = re.compile(r"^[A-Za-z]+$")
_state_re = re.compile(r"^[A-Za-z]+$")
-_keyspace_name_re = re.compile(r"^\s*Keyspace:\s*(.*)$", re.MULTILINE)
-
+_keyspace_name_re = re.compile(r"^\s*Keyspace\s*:\s*(.*)$", re.MULTILINE)
def parse_describe_cluster(text):
return _cluster_name_re.search(text).group(1)
|
spotify/cstar
|
a66272690de28df15cc3a455ec6b19aece34e617
|
diff --git a/tests/nodetoolparser_test.py b/tests/nodetoolparser_test.py
index ee6bfa8..54661f8 100644
--- a/tests/nodetoolparser_test.py
+++ b/tests/nodetoolparser_test.py
@@ -152,7 +152,7 @@ class NodetoolParserTest(unittest.TestCase):
self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'booya', 'system', 'system_distributed', 'system_auth'])
with open("tests/resources/cfstats-3.11.txt", 'r') as f:
keyspaces = cstar.nodetoolparser.extract_keyspaces_from_cfstats(f.read())
- self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'booya', 'system', 'system_distributed', 'system_auth'])
+ self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'system', 'system_distributed', 'system_schema', 'system_auth'])
def test_convert_describering_to_json(self):
with open("tests/resources/describering-2.2.txt", 'r') as f:
diff --git a/tests/resources/cfstats-3.11.txt b/tests/resources/cfstats-3.11.txt
index 322e02d..e905c1f 100644
--- a/tests/resources/cfstats-3.11.txt
+++ b/tests/resources/cfstats-3.11.txt
@@ -1,50 +1,19 @@
-Keyspace: reaper_db
- Read Count: 61944
- Read Latency: 0.08025849154074648 ms.
- Write Count: 51
- Write Latency: 0.11233333333333333 ms.
+Total number of tables: 37
+----------------
+Keyspace : reaper_db
+ Read Count: 0
+ Read Latency: NaN ms
+ Write Count: 0
+ Write Latency: NaN ms
Pending Flushes: 0
- Table: cluster
- SSTable count: 1
- SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0]
- Space used (live): 4887
- Space used (total): 4887
- Space used by snapshots (total): 0
- Off heap memory used (total): 32
- SSTable Compression Ratio: 0.5714285714285714
- Number of keys (estimate): 1
- Memtable cell count: 0
- Memtable data size: 0
- Memtable off heap memory used: 0
- Memtable switch count: 0
- Local read count: 13935
- Local read latency: NaN ms
- Local write count: 0
- Local write latency: NaN ms
- Pending flushes: 0
- Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 16
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 259
- Compacted partition maximum bytes: 310
- Compacted partition mean bytes: 310
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
-
- Table: leader
+ Table: test
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -54,8 +23,9 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -67,15 +37,23 @@ Keyspace: reaper_db
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: node_metrics_v1
+----------------
+Keyspace : system_traces
+ Read Count: 0
+ Read Latency: NaN ms
+ Write Count: 0
+ Write Latency: NaN ms
+ Pending Flushes: 0
+ Table: events
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -85,8 +63,9 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -98,80 +77,89 @@ Keyspace: reaper_db
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: repair_run
- SSTable count: 1
- SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0]
- Space used (live): 24880
- Space used (total): 24880
+ Table: sessions
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 52
- SSTable Compression Ratio: 0.2806763962952568
- Number of keys (estimate): 3
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
Memtable switch count: 0
- Local read count: 44064
+ Local read count: 0
Local read latency: NaN ms
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 28
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 20502
- Compacted partition maximum bytes: 29521
- Compacted partition mean bytes: 26241
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: repair_run_by_cluster
- SSTable count: 1
- SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0]
- Space used (live): 4891
- Space used (total): 4891
+----------------
+Keyspace : system
+ Read Count: 35
+ Read Latency: 3.5249142857142854 ms
+ Write Count: 86
+ Write Latency: 0.46945348837209305 ms
+ Pending Flushes: 0
+ Table: IndexInfo
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 32
- SSTable Compression Ratio: 0.9465648854961832
- Number of keys (estimate): 1
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
Memtable switch count: 0
- Local read count: 2001
+ Local read count: 0
Local read latency: NaN ms
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 16
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 125
- Compacted partition maximum bytes: 149
- Compacted partition mean bytes: 149
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: repair_run_by_unit
- SSTable count: 1
- SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0]
- Space used (live): 4939
- Space used (total): 4939
+ Table: available_ranges
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 44
- SSTable Compression Ratio: 0.8741258741258742
- Number of keys (estimate): 1
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -181,29 +169,30 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 28
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 125
- Compacted partition maximum bytes: 149
- Compacted partition mean bytes: 149
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: repair_schedule_by_cluster_and_keyspace
+ Table: batches
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -213,8 +202,9 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -222,20 +212,20 @@ Keyspace: reaper_db
Compacted partition minimum bytes: 0
Compacted partition maximum bytes: 0
Compacted partition mean bytes: 0
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: repair_schedule_v1
+ Table: batchlog
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -245,8 +235,9 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -258,59 +249,61 @@ Keyspace: reaper_db
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: repair_unit_v1
- SSTable count: 1
- SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0]
- Space used (live): 4901
- Space used (total): 4901
+ Table: built_views
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 44
- SSTable Compression Ratio: 0.782608695652174
- Number of keys (estimate): 1
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
Memtable switch count: 0
- Local read count: 1938
+ Local read count: 0
Local read latency: NaN ms
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 28
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 150
- Compacted partition maximum bytes: 179
- Compacted partition mean bytes: 179
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: running_reapers
+ Table: compaction_history
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 1
- Memtable cell count: 150
- Memtable data size: 220
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 4
+ Memtable cell count: 5
+ Memtable data size: 988
Memtable off heap memory used: 0
Memtable switch count: 0
Local read count: 0
Local read latency: NaN ms
- Local write count: 50
- Local write latency: NaN ms
+ Local write count: 5
+ Local write latency: 0.081 ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -322,47 +315,16 @@ Keyspace: reaper_db
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: schema_migration
- SSTable count: 2
- Space used (live): 13193
- Space used (total): 13193
- Space used by snapshots (total): 0
- Off heap memory used (total): 58
- SSTable Compression Ratio: 0.4748570349221942
- Number of keys (estimate): 2
- Memtable cell count: 4
- Memtable data size: 179
- Memtable off heap memory used: 0
- Memtable switch count: 0
- Local read count: 6
- Local read latency: NaN ms
- Local write count: 1
- Local write latency: NaN ms
- Pending flushes: 0
- Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 26
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 771
- Compacted partition maximum bytes: 11864
- Compacted partition mean bytes: 6394
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
-
- Table: snapshot
+ Table: hints
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -372,8 +334,9 @@ Keyspace: reaper_db
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -385,53 +348,50 @@ Keyspace: reaper_db
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
-----------------
-Keyspace: system_traces
- Read Count: 0
- Read Latency: NaN ms.
- Write Count: 0
- Write Latency: NaN ms.
- Pending Flushes: 0
- Table: events
+ Table: local
SSTable count: 1
- Space used (live): 5059
- Space used (total): 5059
+ Space used (live): 10947
+ Space used (total): 10947
Space used by snapshots (total): 0
- Off heap memory used (total): 44
- SSTable Compression Ratio: 0.3553008595988539
- Number of keys (estimate): 1
- Memtable cell count: 0
- Memtable data size: 0
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 0.889298245614035
+ Number of partitions (estimate): 2
+ Memtable cell count: 3
+ Memtable data size: 61
Memtable off heap memory used: 0
- Memtable switch count: 0
- Local read count: 0
- Local read latency: NaN ms
- Local write count: 0
- Local write latency: NaN ms
+ Memtable switch count: 10
+ Local read count: 33
+ Local read latency: 1.258 ms
+ Local write count: 19
+ Local write latency: 0.212 ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 16
Bloom filter off heap memory used: 8
- Index summary off heap memory used: 28
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 643
- Compacted partition maximum bytes: 770
- Compacted partition mean bytes: 770
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Index summary off heap memory used: 17
+ Compression metadata off heap memory used: 16
+ Compacted partition minimum bytes: 4769
+ Compacted partition maximum bytes: 5722
+ Compacted partition mean bytes: 5722
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.5454545454545454
+ Maximum tombstones per slice (last five minutes): 7
+ Dropped Mutations: 0
- Table: sessions
- SSTable count: 1
- Space used (live): 4825
- Space used (total): 4825
+ Table: paxos
+ SSTable count: 0
+ SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 44
- SSTable Compression Ratio: 1.0
- Number of keys (estimate): 1
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -441,35 +401,30 @@ Keyspace: system_traces
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 28
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 43
- Compacted partition maximum bytes: 50
- Compacted partition mean bytes: 50
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
-----------------
-Keyspace: booya
- Read Count: 0
- Read Latency: NaN ms.
- Write Count: 0
- Write Latency: NaN ms.
- Pending Flushes: 0
- Table: booya1
- SSTable count: 2
- Space used (live): 17705
- Space used (total): 17705
+ Table: peer_events
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 304
- SSTable Compression Ratio: 0.3081875993640699
- Number of keys (estimate): 100
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -479,66 +434,63 @@ Keyspace: booya
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 272
- Bloom filter off heap memory used: 256
- Index summary off heap memory used: 32
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 61
- Compacted partition maximum bytes: 72
- Compacted partition mean bytes: 72
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: booya2
- SSTable count: 2
- Space used (live): 17741
- Space used (total): 17741
+ Table: peers
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 304
- SSTable Compression Ratio: 0.31104928457869635
- Number of keys (estimate): 100
- Memtable cell count: 0
- Memtable data size: 0
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 1
+ Memtable cell count: 30
+ Memtable data size: 18516
Memtable off heap memory used: 0
Memtable switch count: 0
- Local read count: 0
+ Local read count: 2
Local read latency: NaN ms
- Local write count: 0
- Local write latency: NaN ms
+ Local write count: 30
+ Local write latency: 0.289 ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 272
- Bloom filter off heap memory used: 256
- Index summary off heap memory used: 32
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 61
- Compacted partition maximum bytes: 72
- Compacted partition mean bytes: 72
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
+ Average live cells per slice (last five minutes): 1.75
+ Maximum live cells per slice (last five minutes): 2
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
-----------------
-Keyspace: system
- Read Count: 380
- Read Latency: 0.9852842105263158 ms.
- Write Count: 8887
- Write Latency: 0.0286327219534151 ms.
- Pending Flushes: 0
- Table: IndexInfo
+ Table: prepared_statements
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -548,8 +500,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -561,15 +514,16 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: available_ranges
+ Table: range_xfers
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -579,8 +533,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -592,26 +547,28 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: batchlog
+ Table: size_estimates
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
- Memtable cell count: 0
- Memtable data size: 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 2
+ Memtable cell count: 2322
+ Memtable data size: 282495
Memtable off heap memory used: 0
Memtable switch count: 0
Local read count: 0
Local read latency: NaN ms
- Local write count: 0
- Local write latency: NaN ms
+ Local write count: 9
+ Local write latency: 1.778 ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -623,77 +580,82 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: compaction_history
- SSTable count: 3
- Space used (live): 17681
- Space used (total): 17681
+ Table: sstable_activity
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 156
- SSTable Compression Ratio: 0.377732675750636
- Number of keys (estimate): 22
- Memtable cell count: 0
- Memtable data size: 0
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 22
+ Memtable cell count: 23
+ Memtable data size: 184
Memtable off heap memory used: 0
- Memtable switch count: 9
+ Memtable switch count: 0
Local read count: 0
Local read latency: NaN ms
- Local write count: 41
- Local write latency: NaN ms
+ Local write count: 23
+ Local write latency: 0.043 ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 72
- Bloom filter off heap memory used: 48
- Index summary off heap memory used: 84
- Compression metadata off heap memory used: 24
- Compacted partition minimum bytes: 259
- Compacted partition maximum bytes: 535
- Compacted partition mean bytes: 414
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: compactions_in_progress
- SSTable count: 3
- Space used (live): 14709
- Space used (total): 14709
+ Table: transferred_ranges
+ SSTable count: 0
+ Space used (live): 0
+ Space used (total): 0
Space used by snapshots (total): 0
- Off heap memory used (total): 132
- SSTable Compression Ratio: 0.934447128287708
- Number of keys (estimate): 2
+ Off heap memory used (total): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 3
+ Memtable switch count: 0
Local read count: 0
Local read latency: NaN ms
- Local write count: 4
+ Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 48
- Bloom filter off heap memory used: 24
- Index summary off heap memory used: 84
- Compression metadata off heap memory used: 24
- Compacted partition minimum bytes: 30
- Compacted partition maximum bytes: 372
- Compacted partition mean bytes: 188
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 0
+ Bloom filter off heap memory used: 0
+ Index summary off heap memory used: 0
+ Compression metadata off heap memory used: 0
+ Compacted partition minimum bytes: 0
+ Compacted partition maximum bytes: 0
+ Compacted partition mean bytes: 0
Average live cells per slice (last five minutes): NaN
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: hints
+ Table: views_builds_in_progress
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -703,8 +665,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -716,47 +679,23 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: local
- SSTable count: 3
- Space used (live): 14921
- Space used (total): 14921
- Space used by snapshots (total): 0
- Off heap memory used (total): 99
- SSTable Compression Ratio: 0.7974873399233466
- Number of keys (estimate): 1
- Memtable cell count: 0
- Memtable data size: 0
- Memtable off heap memory used: 0
- Memtable switch count: 5
- Local read count: 244
- Local read latency: NaN ms
- Local write count: 8
- Local write latency: NaN ms
- Pending flushes: 0
- Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 48
- Bloom filter off heap memory used: 24
- Index summary off heap memory used: 51
- Compression metadata off heap memory used: 24
- Compacted partition minimum bytes: 87
- Compacted partition maximum bytes: 770
- Compacted partition mean bytes: 332
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
-
- Table: paxos
+----------------
+Keyspace : system_distributed
+ Read Count: 0
+ Read Latency: NaN ms
+ Write Count: 0
+ Write Latency: NaN ms
+ Pending Flushes: 0
+ Table: parent_repair_history
SSTable count: 0
- SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0]
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -766,8 +705,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -779,15 +719,16 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: peer_events
+ Table: repair_history
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -797,8 +738,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -810,46 +752,16 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: peers
- SSTable count: 1
- Space used (live): 5133
- Space used (total): 5133
- Space used by snapshots (total): 0
- Off heap memory used (total): 32
- SSTable Compression Ratio: 0.5971107544141252
- Number of keys (estimate): 2
- Memtable cell count: 0
- Memtable data size: 0
- Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 3
- Local read latency: NaN ms
- Local write count: 57
- Local write latency: NaN ms
- Pending flushes: 0
- Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 16
- Bloom filter off heap memory used: 8
- Index summary off heap memory used: 16
- Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 311
- Compacted partition maximum bytes: 372
- Compacted partition mean bytes: 372
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
-
- Table: range_xfers
+ Table: view_build_status
SSTable count: 0
Space used (live): 0
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -859,8 +771,9 @@ Keyspace: system
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -872,361 +785,351 @@ Keyspace: system
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
- Table: schema_aggregates
- SSTable count: 2
- Space used (live): 9534
- Space used (total): 9534
+----------------
+Keyspace : system_schema
+ Read Count: 100
+ Read Latency: 0.29001 ms
+ Write Count: 39
+ Write Latency: 0.3707179487179487 ms
+ Pending Flushes: 0
+ Table: aggregates
+ SSTable count: 1
+ Space used (live): 5065
+ Space used (total): 5065
Space used by snapshots (total): 0
- Off heap memory used (total): 68
- SSTable Compression Ratio: 1.2727272727272727
- Number of keys (estimate): 1
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 8
- Local read latency: NaN ms
+ Memtable switch count: 1
+ Local read count: 5
+ Local read latency: 0.075 ms
Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 36
- Compression metadata off heap memory used: 16
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
Compacted partition minimum bytes: 21
- Compacted partition maximum bytes: 24
- Compacted partition mean bytes: 24
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_columnfamilies
+ Table: columns
SSTable count: 1
- Space used (live): 19414
- Space used (total): 19414
+ Space used (live): 11087
+ Space used (total): 11087
Space used by snapshots (total): 0
Off heap memory used (total): 55
- SSTable Compression Ratio: 0.1940360684817373
- Number of keys (estimate): 6
+ SSTable Compression Ratio: 0.32196138039745537
+ Number of partitions (estimate): 6
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 10
- Local read latency: NaN ms
- Local write count: 5
- Local write latency: NaN ms
+ Memtable switch count: 4
+ Local read count: 12
+ Local read latency: 0.362 ms
+ Local write count: 8
+ Local write latency: 0.379 ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 24
Bloom filter off heap memory used: 16
Index summary off heap memory used: 23
Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 2760
- Compacted partition maximum bytes: 42510
- Compacted partition mean bytes: 14457
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Compacted partition minimum bytes: 125
+ Compacted partition maximum bytes: 8239
+ Compacted partition mean bytes: 3234
+ Average live cells per slice (last five minutes): 64.8
+ Maximum live cells per slice (last five minutes): 258
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_columns
+ Table: dropped_columns
SSTable count: 1
- Space used (live): 25837
- Space used (total): 25837
+ Space used (live): 4979
+ Space used (total): 4979
Space used by snapshots (total): 0
- Off heap memory used (total): 55
- SSTable Compression Ratio: 0.18518385489157277
- Number of keys (estimate): 6
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 37
- Local read latency: NaN ms
- Local write count: 5
+ Memtable switch count: 1
+ Local read count: 10
+ Local read latency: 0.096 ms
+ Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 24
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 23
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 925
- Compacted partition maximum bytes: 73457
- Compacted partition mean bytes: 20178
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
+ Compacted partition minimum bytes: 21
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_functions
- SSTable count: 2
- Space used (live): 9534
- Space used (total): 9534
+ Table: functions
+ SSTable count: 1
+ Space used (live): 5065
+ Space used (total): 5065
Space used by snapshots (total): 0
- Off heap memory used (total): 68
- SSTable Compression Ratio: 1.2727272727272727
- Number of keys (estimate): 1
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 8
- Local read latency: NaN ms
+ Memtable switch count: 1
+ Local read count: 5
+ Local read latency: 0.067 ms
Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 36
- Compression metadata off heap memory used: 16
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
Compacted partition minimum bytes: 21
- Compacted partition maximum bytes: 24
- Compacted partition mean bytes: 24
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_keyspaces
+ Table: indexes
SSTable count: 1
- Space used (live): 5317
- Space used (total): 5317
+ Space used (live): 4979
+ Space used (total): 4979
Space used by snapshots (total): 0
- Off heap memory used (total): 47
- SSTable Compression Ratio: 0.3516988062442608
- Number of keys (estimate): 6
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 4
- Local read latency: NaN ms
- Local write count: 5
+ Memtable switch count: 1
+ Local read count: 12
+ Local read latency: 0.085 ms
+ Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 24
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 23
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
Compression metadata off heap memory used: 8
- Compacted partition minimum bytes: 150
- Compacted partition maximum bytes: 215
- Compacted partition mean bytes: 209
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Compacted partition minimum bytes: 21
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_triggers
+ Table: keyspaces
SSTable count: 2
- Space used (live): 9534
- Space used (total): 9534
+ Space used (live): 10676
+ Space used (total): 10676
Space used by snapshots (total): 0
- Off heap memory used (total): 68
- SSTable Compression Ratio: 1.2727272727272727
- Number of keys (estimate): 1
+ Off heap memory used (total): 92
+ SSTable Compression Ratio: 0.5386533665835411
+ Number of partitions (estimate): 6
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 35
- Local read latency: NaN ms
- Local write count: 2
- Local write latency: NaN ms
+ Memtable switch count: 5
+ Local read count: 12
+ Local read latency: 0.729 ms
+ Local write count: 9
+ Local write latency: 0.241 ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
- Bloom filter off heap memory used: 16
- Index summary off heap memory used: 36
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 21
- Compacted partition maximum bytes: 24
- Compacted partition mean bytes: 24
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 40
+ Bloom filter off heap memory used: 24
+ Index summary off heap memory used: 44
+ Compression metadata off heap memory used: 24
+ Compacted partition minimum bytes: 87
+ Compacted partition maximum bytes: 149
+ Compacted partition mean bytes: 122
+ Average live cells per slice (last five minutes): 2.4285714285714284
+ Maximum live cells per slice (last five minutes): 6
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: schema_usertypes
- SSTable count: 2
- Space used (live): 9534
- Space used (total): 9534
+ Table: tables
+ SSTable count: 1
+ Space used (live): 9403
+ Space used (total): 9403
Space used by snapshots (total): 0
- Off heap memory used (total): 68
- SSTable Compression Ratio: 1.2727272727272727
- Number of keys (estimate): 1
+ Off heap memory used (total): 55
+ SSTable Compression Ratio: 0.16976998904709747
+ Number of partitions (estimate): 6
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 2
- Local read count: 8
- Local read latency: NaN ms
- Local write count: 2
- Local write latency: NaN ms
+ Memtable switch count: 4
+ Local read count: 20
+ Local read latency: 0.356 ms
+ Local write count: 8
+ Local write latency: 0.299 ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 24
Bloom filter off heap memory used: 16
- Index summary off heap memory used: 36
+ Index summary off heap memory used: 23
Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 21
- Compacted partition maximum bytes: 24
- Compacted partition mean bytes: 24
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Compacted partition minimum bytes: 373
+ Compacted partition maximum bytes: 8239
+ Compacted partition mean bytes: 2982
+ Average live cells per slice (last five minutes): 7.5
+ Maximum live cells per slice (last five minutes): 42
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: size_estimates
- SSTable count: 2
- Space used (live): 12369
- Space used (total): 12369
+ Table: triggers
+ SSTable count: 1
+ Space used (live): 4979
+ Space used (total): 4979
Space used by snapshots (total): 0
- Off heap memory used (total): 94
- SSTable Compression Ratio: 0.16691314966847087
- Number of keys (estimate): 10
- Memtable cell count: 330
- Memtable data size: 5197
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
+ Memtable cell count: 0
+ Memtable data size: 0
Memtable off heap memory used: 0
- Memtable switch count: 20
- Local read count: 0
- Local read latency: NaN ms
- Local write count: 5126
+ Memtable switch count: 1
+ Local read count: 12
+ Local read latency: 0.073 ms
+ Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 48
- Bloom filter off heap memory used: 32
- Index summary off heap memory used: 46
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 536
- Compacted partition maximum bytes: 4768
- Compacted partition mean bytes: 1578
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
-
- Table: sstable_activity
- SSTable count: 2
- Space used (live): 13458
- Space used (total): 13458
- Space used by snapshots (total): 0
- Off heap memory used (total): 194
- SSTable Compression Ratio: 0.3279409178828908
- Number of keys (estimate): 38
- Memtable cell count: 135
- Memtable data size: 1335
- Memtable off heap memory used: 0
- Memtable switch count: 20
- Local read count: 23
- Local read latency: NaN ms
- Local write count: 3628
- Local write latency: 0,017 ms
- Pending flushes: 0
- Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 80
- Bloom filter off heap memory used: 64
- Index summary off heap memory used: 114
- Compression metadata off heap memory used: 16
- Compacted partition minimum bytes: 43
- Compacted partition maximum bytes: 179
- Compacted partition mean bytes: 152
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
+ Compacted partition minimum bytes: 21
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
-----------------
-Keyspace: system_distributed
- Read Count: 0
- Read Latency: NaN ms.
- Write Count: 598
- Write Latency: 0.09190635451505016 ms.
- Pending Flushes: 0
- Table: parent_repair_history
+ Table: types
SSTable count: 1
- Space used (live): 43448
- Space used (total): 43448
+ Space used (live): 4938
+ Space used (total): 4938
Space used by snapshots (total): 0
- Off heap memory used (total): 296
- SSTable Compression Ratio: 0.20285498694969137
- Number of keys (estimate): 170
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
Memtable switch count: 1
- Local read count: 0
- Local read latency: NaN ms
- Local write count: 46
+ Local read count: 5
+ Local read latency: 0.106 ms
+ Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 224
- Bloom filter off heap memory used: 216
- Index summary off heap memory used: 56
- Compression metadata off heap memory used: 24
- Compacted partition minimum bytes: 373
- Compacted partition maximum bytes: 1109
- Compacted partition mean bytes: 1099
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
+ Compacted partition minimum bytes: 21
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
- Table: repair_history
+ Table: views
SSTable count: 1
- Space used (live): 347020
- Space used (total): 347020
+ Space used (live): 4938
+ Space used (total): 4938
Space used by snapshots (total): 0
- Off heap memory used (total): 218
- SSTable Compression Ratio: 0.28505859645558396
- Number of keys (estimate): 14
+ Off heap memory used (total): 41
+ SSTable Compression Ratio: 1.0408163265306123
+ Number of partitions (estimate): 2
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
Memtable switch count: 1
- Local read count: 0
- Local read latency: NaN ms
- Local write count: 552
+ Local read count: 7
+ Local read latency: 0.147 ms
+ Local write count: 2
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 0.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
- Bloom filter space used: 32
- Bloom filter off heap memory used: 24
- Index summary off heap memory used: 42
- Compression metadata off heap memory used: 152
- Compacted partition minimum bytes: 643
- Compacted partition maximum bytes: 105778
- Compacted partition mean bytes: 86865
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
+ Bloom filter false ratio: 0.00000
+ Bloom filter space used: 16
+ Bloom filter off heap memory used: 8
+ Index summary off heap memory used: 25
+ Compression metadata off heap memory used: 8
+ Compacted partition minimum bytes: 21
+ Compacted partition maximum bytes: 29
+ Compacted partition mean bytes: 27
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
----------------
-Keyspace: system_auth
+Keyspace : system_auth
Read Count: 0
- Read Latency: NaN ms.
+ Read Latency: NaN ms
Write Count: 0
- Write Latency: NaN ms.
+ Write Latency: NaN ms
Pending Flushes: 0
Table: resource_role_permissons_index
SSTable count: 0
@@ -1234,8 +1137,8 @@ Keyspace: system_auth
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -1245,8 +1148,9 @@ Keyspace: system_auth
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -1258,6 +1162,7 @@ Keyspace: system_auth
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
Table: role_members
SSTable count: 0
@@ -1265,8 +1170,8 @@ Keyspace: system_auth
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -1276,8 +1181,9 @@ Keyspace: system_auth
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -1289,6 +1195,7 @@ Keyspace: system_auth
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
Table: role_permissions
SSTable count: 0
@@ -1296,8 +1203,8 @@ Keyspace: system_auth
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -1307,8 +1214,9 @@ Keyspace: system_auth
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -1320,6 +1228,7 @@ Keyspace: system_auth
Maximum live cells per slice (last five minutes): 0
Average tombstones per slice (last five minutes): NaN
Maximum tombstones per slice (last five minutes): 0
+ Dropped Mutations: 0
Table: roles
SSTable count: 0
@@ -1327,8 +1236,8 @@ Keyspace: system_auth
Space used (total): 0
Space used by snapshots (total): 0
Off heap memory used (total): 0
- SSTable Compression Ratio: 0.0
- Number of keys (estimate): 0
+ SSTable Compression Ratio: -1.0
+ Number of partitions (estimate): 0
Memtable cell count: 0
Memtable data size: 0
Memtable off heap memory used: 0
@@ -1338,8 +1247,9 @@ Keyspace: system_auth
Local write count: 0
Local write latency: NaN ms
Pending flushes: 0
+ Percent repaired: 100.0
Bloom filter false positives: 0
- Bloom filter false ratio: 0,00000
+ Bloom filter false ratio: 0.00000
Bloom filter space used: 0
Bloom filter off heap memory used: 0
Index summary off heap memory used: 0
@@ -1347,7 +1257,10 @@ Keyspace: system_auth
Compacted partition minimum bytes: 0
Compacted partition maximum bytes: 0
Compacted partition mean bytes: 0
- Average live cells per slice (last five minutes): NaN
- Maximum live cells per slice (last five minutes): 0
- Average tombstones per slice (last five minutes): NaN
- Maximum tombstones per slice (last five minutes): 0
\ No newline at end of file
+ Average live cells per slice (last five minutes): 1.0
+ Maximum live cells per slice (last five minutes): 1
+ Average tombstones per slice (last five minutes): 1.0
+ Maximum tombstones per slice (last five minutes): 1
+ Dropped Mutations: 0
+
+----------------
|
local variable 'has_error' referenced before assignment
hello
when run the cstar by this command :
`cstar run --command "nodetool status" --host 192.168.1.1 --ssh-username amirio --ssh-password foobar`
receive this error :
Generating endpoint mapping
Traceback (most recent call last):
File "/usr/local/bin/cstar", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/cstar/cstarcli.py", line 131, in main
namespace.func(namespace)
File "/usr/local/lib/python3.5/dist-packages/cstar/args.py", line 98, in <lambda>
command_parser.set_defaults(func=lambda args: execute_command(args), command=command)
File "/usr/local/lib/python3.5/dist-packages/cstar/cstarcli.py", line 115, in execute_command
ssh_identity_file = args.ssh_identity_file)
File "/usr/local/lib/python3.5/dist-packages/cstar/job.py", line 215, in setup
endpoint_mapping = self.get_endpoint_mapping(current_topology)
File "/usr/local/lib/python3.5/dist-packages/cstar/job.py", line 155, in get_endpoint_mapping
if not has_error:
UnboundLocalError: local variable 'has_error' referenced before assignment
|
0.0
|
a66272690de28df15cc3a455ec6b19aece34e617
|
[
"tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_keyspaces"
] |
[
"tests/nodetoolparser_test.py::NodetoolParserTest::test_bad_syntax",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_convert_describering_to_json",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_describecluster",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_describering",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_nodetool_ring",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_nodetool_ring_with_vnodes",
"tests/nodetoolparser_test.py::NodetoolParserTest::test_tokenize"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-26 06:59:49+00:00
|
apache-2.0
| 5,677 |
|
springload__draftjs_exporter-107
|
diff --git a/draftjs_exporter/entity_state.py b/draftjs_exporter/entity_state.py
index bffd6f8..4b10dcb 100644
--- a/draftjs_exporter/entity_state.py
+++ b/draftjs_exporter/entity_state.py
@@ -29,6 +29,9 @@ class EntityState:
self.completed_entity = self.entity_stack.pop()
+ def has_entity(self):
+ return self.entity_stack
+
def has_no_entity(self):
return not self.entity_stack
@@ -41,7 +44,7 @@ class EntityState:
return details
def render_entities(self, style_node):
-
+ # We have a complete (start, stop) entity to render.
if self.completed_entity is not None:
entity_details = self.get_entity_details(self.completed_entity)
opts = Options.for_entity(self.entity_decorators, entity_details['type'])
@@ -55,14 +58,17 @@ class EntityState:
for n in self.element_stack:
DOM.append_child(nodes, n)
- elt = DOM.create_element(opts.element, props, nodes)
-
self.completed_entity = None
self.element_stack = []
- elif self.has_no_entity():
- elt = style_node
- else:
+
+ # Is there still another entity? (adjacent) if so add the current style_node for it.
+ if self.has_entity():
+ self.element_stack.append(style_node)
+
+ return DOM.create_element(opts.element, props, nodes)
+
+ if self.has_entity():
self.element_stack.append(style_node)
- elt = None
+ return None
- return elt
+ return style_node
diff --git a/draftjs_exporter/html.py b/draftjs_exporter/html.py
index 5267bd7..347c237 100644
--- a/draftjs_exporter/html.py
+++ b/draftjs_exporter/html.py
@@ -80,7 +80,9 @@ class HTML:
if entity_node is not None:
DOM.append_child(content, entity_node)
- if styled_node != entity_node:
+
+ # Check whether there actually are two different nodes, confirming we are not inserting an upcoming entity.
+ if styled_node != entity_node and entity_state.has_no_entity():
DOM.append_child(content, styled_node)
# Fast track for blocks which do not contain styles nor entities, which is very common.
else:
|
springload/draftjs_exporter
|
cafdffcdeb35888882d98d6db1f0b99e417ebb3e
|
diff --git a/tests/test_exports.json b/tests/test_exports.json
index 088caa1..910abfd 100644
--- a/tests/test_exports.json
+++ b/tests/test_exports.json
@@ -148,6 +148,55 @@
}
},
+ {
+ "label": "Adjacent entities",
+ "output": {
+ "html5lib": "<p><a href=\"https://google.com\">G</a><a href=\"https://facebook.com\">F</a></p>",
+ "lxml": "<p><a href=\"https://google.com\">G</a><a href=\"https://facebook.com\">F</a></p>",
+ "string": "<p><a href=\"https://google.com\">G</a><a href=\"https://facebook.com\">F</a></p>"
+ },
+ "content_state": {
+ "blocks": [
+ {
+ "key": "9nc73",
+ "text": "GF",
+ "type": "unstyled",
+ "depth": 0,
+ "inlineStyleRanges": [],
+ "entityRanges": [
+ {
+ "offset": 0,
+ "length": 1,
+ "key": 7
+ },
+ {
+ "offset": 1,
+ "length": 1,
+ "key": 8
+ }
+ ],
+ "data": {}
+ }
+ ],
+ "entityMap": {
+ "7": {
+ "type": "LINK",
+ "mutability": "MUTABLE",
+ "data": {
+ "url": "https://google.com"
+ }
+ },
+ "8": {
+ "type": "LINK",
+ "mutability": "MUTABLE",
+ "data": {
+ "url": "https://facebook.com"
+ }
+ }
+ }
+ }
+ },
+
{
"label": "Style map defaults",
"output": {
|
Entities with adjacent offset are rendered incorrectly
Test version: v2.1.4
Test with the following code:
```python3
from draftjs_exporter.constants import BLOCK_TYPES
from draftjs_exporter.constants import ENTITY_TYPES
from draftjs_exporter.defaults import BLOCK_MAP
from draftjs_exporter.dom import DOM
from draftjs_exporter.html import HTML
import json
a = '''{
"blocks": [
{
"key": "bh6r4",
"text": "🙄😖",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [
{
"offset": 0,
"length": 1,
"key": 7
},
{
"offset": 1,
"length": 1,
"key": 8
}
],
"data": {}
}
],
"entityMap": {
"7": {
"type": "emoji",
"mutability": "IMMUTABLE",
"data": {
"emojiUnicode": "🙄"
}
},
"8": {
"type": "emoji",
"mutability": "IMMUTABLE",
"data": {
"emojiUnicode": "😖"
}
}
}
}'''
def emoji(props):
emoji_encode = []
for c in props.get('emojiUnicode'):
code = '%04x' % ord(c)
if code != '200d':
emoji_encode.append('%04x' % ord(c))
return DOM.create_element('span', {
'data-emoji': '-'.join(emoji_encode),
'class': 'emoji',
}, props['children'])
def entity_fallback(props):
return DOM.create_element('span', {'class': 'missing-entity'},
props['children'])
def style_fallback(props):
return props['children']
def block_fallback(props):
return DOM.create_element('div', {}, props['children'])
DRAFTJS_EXPORTER_CONFIG = {
'entity_decorators': {
'emoji': emoji,
ENTITY_TYPES.FALLBACK: entity_fallback,
},
'block_map': dict(BLOCK_MAP, **{
BLOCK_TYPES.FALLBACK: block_fallback,
})
}
exporter = HTML(DRAFTJS_EXPORTER_CONFIG)
if __name__ == '__main__':
print(exporter.render(json.loads(a)))
```
Actual output:
```html
<p><span class="emoji" data-emoji="1f644">🙄</span>😖<span class="emoji" data-emoji="1f616"></span></p>
```
Expected output:
```html
<p><span class="emoji" data-emoji="1f644">🙄</span><span class="emoji" data-emoji="1f616">😖</span></p>
```
|
0.0
|
cafdffcdeb35888882d98d6db1f0b99e417ebb3e
|
[
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_adjacent_entities",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_adjacent_entities",
"tests/test_exports.py::TestExportsSTRING::test_export_string_adjacent_entities"
] |
[
"tests/engines/test_engines_base.py::TestDOMEngine::test_append_child",
"tests/engines/test_engines_base.py::TestDOMEngine::test_create_tag",
"tests/engines/test_engines_base.py::TestDOMEngine::test_parse_html",
"tests/engines/test_engines_base.py::TestDOMEngine::test_render",
"tests/engines/test_engines_base.py::TestDOMEngine::test_render_debug",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_html5lib_html_escaping",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_html5lib_html_parsing",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_html5lib_invalid_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_html5lib_namespaced_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_html5lib_self_closing_tags",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_lxml_html_escaping",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_lxml_html_parsing",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_lxml_invalid_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_lxml_namespaced_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_lxml_self_closing_tags",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_string_html_escaping",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_string_html_parsing",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_string_invalid_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_string_namespaced_attributes",
"tests/engines/test_engines_differences.py::TestDOMEnginesDifferences::test_string_self_closing_tags",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_append_child",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_create_tag",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_create_tag_empty",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_parse_html",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_render",
"tests/engines/test_engines_html5lib.py::TestDOM_HTML5LIB::test_render_debug",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_append_child",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_create_tag",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_create_tag_empty",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_parse_html",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_render",
"tests/engines/test_engines_lxml.py::TestDOM_LXML::test_render_debug",
"tests/engines/test_engines_string.py::TestDOMString::test_append_child",
"tests/engines/test_engines_string.py::TestDOMString::test_append_child_identical_elements",
"tests/engines/test_engines_string.py::TestDOMString::test_append_child_identical_text",
"tests/engines/test_engines_string.py::TestDOMString::test_create_tag",
"tests/engines/test_engines_string.py::TestDOMString::test_create_tag_empty",
"tests/engines/test_engines_string.py::TestDOMString::test_parse_html",
"tests/engines/test_engines_string.py::TestDOMString::test_render",
"tests/engines/test_engines_string.py::TestDOMString::test_render_attrs",
"tests/engines/test_engines_string.py::TestDOMString::test_render_children",
"tests/engines/test_engines_string.py::TestDOMString::test_render_debug",
"tests/test_command.py::TestCommand::test_from_ranges_empty",
"tests/test_command.py::TestCommand::test_from_ranges_multiple",
"tests/test_command.py::TestCommand::test_from_ranges_single",
"tests/test_command.py::TestCommand::test_init",
"tests/test_command.py::TestCommand::test_key",
"tests/test_command.py::TestCommand::test_lt_false",
"tests/test_command.py::TestCommand::test_lt_true",
"tests/test_command.py::TestCommand::test_start_stop",
"tests/test_command.py::TestCommand::test_str",
"tests/test_composite_decorators.py::TestLinkify::test_render",
"tests/test_composite_decorators.py::TestLinkify::test_render_code_block",
"tests/test_composite_decorators.py::TestLinkify::test_render_www",
"tests/test_composite_decorators.py::TestHashtag::test_render",
"tests/test_composite_decorators.py::TestHashtag::test_render_code_block",
"tests/test_composite_decorators.py::TestBR::test_render",
"tests/test_composite_decorators.py::TestBR::test_render_code_block",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_conflicting_order_one",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_conflicting_order_two",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_data",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_empty",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_single",
"tests/test_constants.py::EnumConstants::test_enum_raises_an_error_for_invalid_keys",
"tests/test_constants.py::EnumConstants::test_enum_returns_the_key_if_valid",
"tests/test_constants.py::TestConstants::test_block_types",
"tests/test_constants.py::TestConstants::test_entity_types",
"tests/test_constants.py::TestConstants::test_inline_styles",
"tests/test_defaults.py::TestDefaults::test_default_block_map",
"tests/test_defaults.py::TestDefaults::test_default_style_map",
"tests/test_defaults.py::TestDefaults::test_render_children",
"tests/test_defaults.py::TestDefaults::test_render_code_block",
"tests/test_dom.py::TestDOM::test_append_child",
"tests/test_dom.py::TestDOM::test_camel_to_dash",
"tests/test_dom.py::TestDOM::test_create_element",
"tests/test_dom.py::TestDOM::test_create_element_empty",
"tests/test_dom.py::TestDOM::test_create_element_entity",
"tests/test_dom.py::TestDOM::test_create_element_nested",
"tests/test_dom.py::TestDOM::test_create_element_none",
"tests/test_dom.py::TestDOM::test_create_element_style_dict",
"tests/test_dom.py::TestDOM::test_create_element_style_str",
"tests/test_dom.py::TestDOM::test_parse_html",
"tests/test_dom.py::TestDOM::test_render_debug",
"tests/test_dom.py::TestDOM::test_use_custom",
"tests/test_dom.py::TestDOM::test_use_html5lib",
"tests/test_dom.py::TestDOM::test_use_invalid",
"tests/test_dom.py::TestDOM::test_use_lxml",
"tests/test_dom.py::TestDOM::test_use_string",
"tests/test_entities.py::TestIcon::test_render",
"tests/test_entities.py::TestImage::test_render",
"tests/test_entities.py::TestLink::test_render",
"tests/test_entities.py::TestButton::test_render_with_icon",
"tests/test_entities.py::TestButton::test_render_without_icon",
"tests/test_entity_state.py::TestEntityState::test_apply_raises",
"tests/test_entity_state.py::TestEntityState::test_apply_start_entity",
"tests/test_entity_state.py::TestEntityState::test_apply_stop_entity",
"tests/test_entity_state.py::TestEntityState::test_get_entity_details",
"tests/test_entity_state.py::TestEntityState::test_get_entity_details_raises",
"tests/test_entity_state.py::TestEntityState::test_has_no_entity_default",
"tests/test_entity_state.py::TestEntityState::test_has_no_entity_styled",
"tests/test_entity_state.py::TestEntityState::test_init",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_adjacent_inline_styles",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_big_content_export",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity_with_data-*",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity_with_inline_style",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_html_entities_escaping",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_multiple_decorators",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_nested_inline_styles",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_ordered_list",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_plain_text",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_same_content_multiple_times",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_single_inline_style",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_style_map_defaults",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_adjacent_inline_styles",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_entity",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_entity_with_inline_style",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_html_entities_escaping",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_multiple_decorators",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_nested_inline_styles",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_ordered_list",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_plain_text",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_same_content_multiple_times",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_single_inline_style",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_style_map_defaults",
"tests/test_exports.py::TestExportsSTRING::test_export_string_adjacent_inline_styles",
"tests/test_exports.py::TestExportsSTRING::test_export_string_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsSTRING::test_export_string_big_content_export",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity_with_data-*",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity_with_inline_style",
"tests/test_exports.py::TestExportsSTRING::test_export_string_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsSTRING::test_export_string_html_entities_escaping",
"tests/test_exports.py::TestExportsSTRING::test_export_string_multiple_decorators",
"tests/test_exports.py::TestExportsSTRING::test_export_string_nested_inline_styles",
"tests/test_exports.py::TestExportsSTRING::test_export_string_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsSTRING::test_export_string_ordered_list",
"tests/test_exports.py::TestExportsSTRING::test_export_string_plain_text",
"tests/test_exports.py::TestExportsSTRING::test_export_string_same_content_multiple_times",
"tests/test_exports.py::TestExportsSTRING::test_export_string_single_inline_style",
"tests/test_exports.py::TestExportsSTRING::test_export_string_style_map_defaults",
"tests/test_html.py::TestHTML::test_build_command_groups_empty",
"tests/test_html.py::TestHTML::test_build_command_groups_multiple",
"tests/test_html.py::TestHTML::test_build_commands_empty",
"tests/test_html.py::TestHTML::test_build_commands_multiple",
"tests/test_html.py::TestHTML::test_build_entity_commands_empty",
"tests/test_html.py::TestHTML::test_build_entity_commands_multiple",
"tests/test_html.py::TestHTML::test_build_entity_commands_single",
"tests/test_html.py::TestHTML::test_build_style_commands_empty",
"tests/test_html.py::TestHTML::test_build_style_commands_multiple",
"tests/test_html.py::TestHTML::test_build_style_commands_single",
"tests/test_html.py::TestHTML::test_init",
"tests/test_html.py::TestHTML::test_init_dom_engine_default",
"tests/test_html.py::TestHTML::test_render",
"tests/test_html.py::TestHTML::test_render_block_exists",
"tests/test_html.py::TestHTML::test_render_empty",
"tests/test_html.py::TestHTML::test_render_none",
"tests/test_html.py::TestHTML::test_render_twice",
"tests/test_options.py::TestOptions::test_eq",
"tests/test_options.py::TestOptions::test_for_block_full",
"tests/test_options.py::TestOptions::test_for_block_half",
"tests/test_options.py::TestOptions::test_for_block_raises_missing_element",
"tests/test_options.py::TestOptions::test_for_block_raises_missing_type",
"tests/test_options.py::TestOptions::test_for_block_simplest",
"tests/test_options.py::TestOptions::test_for_block_uses_fallback",
"tests/test_options.py::TestOptions::test_for_entity_full",
"tests/test_options.py::TestOptions::test_for_entity_half",
"tests/test_options.py::TestOptions::test_for_entity_raises_missing_element",
"tests/test_options.py::TestOptions::test_for_entity_raises_missing_type",
"tests/test_options.py::TestOptions::test_for_entity_simplest",
"tests/test_options.py::TestOptions::test_for_entity_uses_fallback",
"tests/test_options.py::TestOptions::test_for_style_full",
"tests/test_options.py::TestOptions::test_for_style_half",
"tests/test_options.py::TestOptions::test_for_style_raises_missing_element",
"tests/test_options.py::TestOptions::test_for_style_raises_missing_type",
"tests/test_options.py::TestOptions::test_for_style_simplest",
"tests/test_options.py::TestOptions::test_for_style_uses_fallback",
"tests/test_options.py::TestOptions::test_not_eq",
"tests/test_options.py::TestOptions::test_str",
"tests/test_output.py::TestOutput::test_render_empty",
"tests/test_output.py::TestOutput::test_render_with_backtracking_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_big_content",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_false",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_true",
"tests/test_output.py::TestOutput::test_render_with_default_block_map",
"tests/test_output.py::TestOutput::test_render_with_default_config",
"tests/test_output.py::TestOutput::test_render_with_default_style_map",
"tests/test_output.py::TestOutput::test_render_with_different_blocks",
"tests/test_output.py::TestOutput::test_render_with_element_options",
"tests/test_output.py::TestOutput::test_render_with_entities",
"tests/test_output.py::TestOutput::test_render_with_entities_crossing_raises",
"tests/test_output.py::TestOutput::test_render_with_entity",
"tests/test_output.py::TestOutput::test_render_with_entity_and_decorators",
"tests/test_output.py::TestOutput::test_render_with_immediate_jumping",
"tests/test_output.py::TestOutput::test_render_with_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_jumping_wrapping",
"tests/test_output.py::TestOutput::test_render_with_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_many_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_multiple_decorators",
"tests/test_output.py::TestOutput::test_render_with_multiple_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_no_zero_depth",
"tests/test_output.py::TestOutput::test_render_with_none_attribute",
"tests/test_output.py::TestOutput::test_render_with_none_component",
"tests/test_output.py::TestOutput::test_render_with_none_return_value",
"tests/test_output.py::TestOutput::test_render_with_number_attribute",
"tests/test_output.py::TestOutput::test_render_with_styles_in_entities",
"tests/test_output.py::TestOutput::test_render_with_unicode",
"tests/test_output.py::TestOutput::test_render_with_unidirectional_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_unknown_attribute",
"tests/test_output.py::TestOutput::test_render_with_wrapping",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset_block_components",
"tests/test_style_state.py::TestStyleState::test_apply_start_inline_style",
"tests/test_style_state.py::TestStyleState::test_apply_stop_inline_style",
"tests/test_style_state.py::TestStyleState::test_init",
"tests/test_style_state.py::TestStyleState::test_is_empty_default",
"tests/test_style_state.py::TestStyleState::test_is_empty_styled",
"tests/test_style_state.py::TestStyleState::test_render_styles_attributes",
"tests/test_style_state.py::TestStyleState::test_render_styles_component",
"tests/test_style_state.py::TestStyleState::test_render_styles_component_multiple",
"tests/test_style_state.py::TestStyleState::test_render_styles_component_multiple_invert",
"tests/test_style_state.py::TestStyleState::test_render_styles_data",
"tests/test_style_state.py::TestStyleState::test_render_styles_styled",
"tests/test_style_state.py::TestStyleState::test_render_styles_styled_multiple",
"tests/test_style_state.py::TestStyleState::test_render_styles_unicode",
"tests/test_style_state.py::TestStyleState::test_render_styles_unstyled",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_component",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_component_wrapper",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_data",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_dismiss_content",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_element_content",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_no_block",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_simple_content",
"tests/test_wrapper_state.py::TestWrapperState::test_init",
"tests/test_wrapper_state.py::TestWrapperState::test_str",
"tests/test_wrapper_state.py::TestWrapperState::test_str_elts",
"tests/test_wrapper_state.py::TestBlockquote::test_render_debug",
"tests/test_wrapper_state.py::TestListItem::test_render_debug",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_invalid",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_success",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_unexistent"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-14 08:24:22+00:00
|
mit
| 5,678 |
|
springload__draftjs_exporter-124
|
diff --git a/.travis.yml b/.travis.yml
index d42f54d..fb69f61 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -24,7 +24,7 @@ matrix:
- env: TOXENV=py38-upper_bound_deps
python: 3.8
install:
-- pip install tox coveralls
+- pip install tox coveralls==1.10.0
script:
- make test-ci
after_success:
diff --git a/docs/README.md b/docs/README.md
index b984ef4..b37d3ee 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -53,7 +53,7 @@
### Limitations of `html5lib`
-- Generated HTML is always "made valid" by being wrapped in '<html><head></head><body></body></html>'.
+- Generated HTML is always "made valid" by being wrapped in `<html><head></head><body></body></html>`.
### Limitations of `BeautifulSoup4`
@@ -113,3 +113,9 @@ pip install draftjs_exporter
Solution: see http://stackoverflow.com/a/6504860/1798491
`apt-get install libxml2-dev libxslt1-dev python-dev`
+
+### Entity props override
+
+Entities receive their `data` as props, except for the key `entity` which is overriden with a dict containing additional data (`type`, `mutability`, etc.). This is a known issue (see [#91](https://github.com/springload/draftjs_exporter/issues/91)). There is no workaround if you need to use a data key called `entity` – it won’t be available.
+
+This is also a problem if the entity’s `data` contains a `children` key – this will also get overriden without any workaround possible.
diff --git a/draftjs_exporter/entity_state.py b/draftjs_exporter/entity_state.py
index 191f9f5..85a934c 100644
--- a/draftjs_exporter/entity_state.py
+++ b/draftjs_exporter/entity_state.py
@@ -1,11 +1,11 @@
-from typing import List, Optional
+from typing import List, Optional, Sequence
from draftjs_exporter.command import Command
from draftjs_exporter.constants import ENTITY_TYPES
from draftjs_exporter.dom import DOM
from draftjs_exporter.error import ExporterException
from draftjs_exporter.options import Options, OptionsMap
-from draftjs_exporter.types import Element, EntityDetails, EntityKey, EntityMap
+from draftjs_exporter.types import Block, Element, EntityDetails, EntityKey, EntityMap
class EntityException(ExporterException):
@@ -48,7 +48,7 @@ class EntityState(object):
return details
- def render_entities(self, style_node: Element) -> Element:
+ def render_entities(self, style_node: Element, block: Block, blocks: Sequence[Block]) -> Element:
# We have a complete (start, stop) entity to render.
if self.completed_entity is not None:
entity_details = self.get_entity_details(self.completed_entity)
@@ -56,6 +56,12 @@ class EntityState(object):
props = entity_details['data'].copy()
props['entity'] = {
'type': entity_details['type'],
+ 'mutability': entity_details['mutability'] if 'mutability' in entity_details else None,
+ 'block': block,
+ 'blocks': blocks,
+ 'entity_range': {
+ 'key': self.completed_entity,
+ },
}
if len(self.element_stack) == 1:
diff --git a/draftjs_exporter/html.py b/draftjs_exporter/html.py
index a4766d4..eade7fb 100644
--- a/draftjs_exporter/html.py
+++ b/draftjs_exporter/html.py
@@ -82,7 +82,7 @@ class HTML(object):
decorated_node = text
styled_node = style_state.render_styles(decorated_node, block, wrapper_state.blocks)
- entity_node = entity_state.render_entities(styled_node)
+ entity_node = entity_state.render_entities(styled_node, block, wrapper_state.blocks)
if entity_node is not None:
DOM.append_child(content, entity_node)
diff --git a/example.py b/example.py
index be1f4d1..362126d 100644
--- a/example.py
+++ b/example.py
@@ -122,7 +122,8 @@ def block_fallback(props: Props) -> Element:
def entity_fallback(props: Props) -> Element:
type_ = props['entity']['type']
- logging.warn('Missing config for "%s".' % type_)
+ key = props['entity']['entity_range']['key']
+ logging.warn('Missing config for "%s", key "%s".' % (type_, key))
return DOM.create_element('span', {'class': 'missing-entity'}, props['children'])
diff --git a/setup.py b/setup.py
index 94b1ea9..5a3d711 100755
--- a/setup.py
+++ b/setup.py
@@ -29,7 +29,7 @@ dependencies['testing'] = [
'psutil==5.4.1',
# For coverage and PEP8 linting.
- 'coverage==4.5.4',
+ 'coverage==5.0.1',
'flake8>=3.2.0',
'isort==4.2.5',
'mypy==0.750',
|
springload/draftjs_exporter
|
f5b3f516859dfaa444fcdfc1493d8a2c0b65ed04
|
diff --git a/tests/test_entity_state.py b/tests/test_entity_state.py
index 15b6a08..ce29e61 100644
--- a/tests/test_entity_state.py
+++ b/tests/test_entity_state.py
@@ -1,6 +1,7 @@
import unittest
from draftjs_exporter.command import Command
+from draftjs_exporter.dom import DOM
from draftjs_exporter.entity_state import EntityException, EntityState
from draftjs_exporter.options import Options
from tests.test_entities import link
@@ -16,6 +17,12 @@ entity_map = {
'data': {
'url': 'http://example.com'
}
+ },
+ '2': {
+ 'type': 'LINK',
+ 'data': {
+ 'url': 'http://test.com'
+ }
}
}
@@ -62,3 +69,68 @@ class TestEntityState(unittest.TestCase):
def test_get_entity_details_raises(self):
with self.assertRaises(EntityException):
self.entity_state.get_entity_details('1')
+
+ def test_render_entities_unstyled(self):
+ self.assertEqual(self.entity_state.render_entities('Test text', {}, []), 'Test text')
+
+ def test_render_entities_unicode(self):
+ self.assertEqual(self.entity_state.render_entities('🍺', {}, []), '🍺')
+
+ def test_render_entities_inline(self):
+ self.entity_state.apply(Command('start_entity', 0, '0'))
+ self.entity_state.render_entities('Test text', {}, [])
+ self.entity_state.apply(Command('stop_entity', 9, '0'))
+ self.assertEqual(DOM.render_debug(self.entity_state.render_entities('Test text', {}, [])), '<a href="http://example.com">Test text</a>')
+
+ def test_render_entities_inline_multiple(self):
+ self.entity_state.apply(Command('start_entity', 0, '0'))
+ self.entity_state.render_entities('Test 1', {}, [])
+ self.entity_state.apply(Command('stop_entity', 5, '0'))
+ self.entity_state.apply(Command('start_entity', 5, '2'))
+ self.assertEqual(DOM.render_debug(self.entity_state.render_entities('Test text', {}, [])), '<a href="http://example.com">Test 1</a>')
+ self.entity_state.render_entities('Test 2', {}, [])
+ self.entity_state.apply(Command('stop_entity', 10, '2'))
+ self.assertEqual(DOM.render_debug(self.entity_state.render_entities('Test text', {}, [])), '<a href="http://test.com"><fragment>Test textTest 2</fragment></a>')
+
+ def test_render_entities_data(self):
+ blocks = [
+ {
+ 'key': '5s7g9',
+ 'text': 'test',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ ]
+
+ def component(props):
+ self.assertEqual(props['entity']['blocks'], blocks)
+ self.assertEqual(props['entity']['block'], blocks[0])
+ self.assertEqual(props['entity']['type'], 'LINK')
+ self.assertEqual(props['entity']['mutability'], 'MUTABLE')
+ self.assertEqual(props['entity']['entity_range']['key'], '0')
+ return None
+
+ entity_state = EntityState(Options.map_entities({
+ 'LINK': component,
+ }), entity_map)
+
+ entity_state.apply(Command('start_entity', 0, '0'))
+ entity_state.render_entities('Test text', blocks[0], blocks)
+ entity_state.apply(Command('stop_entity', 9, '0'))
+ entity_state.render_entities('Test text', blocks[0], blocks)
+
+ def test_render_entities_data_no_mutability(self):
+ def component(props):
+ self.assertEqual(props['entity']['mutability'], None)
+ return None
+
+ entity_state = EntityState(Options.map_entities({
+ 'LINK': component,
+ }), entity_map)
+
+ entity_state.apply(Command('start_entity', 0, '2'))
+ entity_state.render_entities('Test text', {}, [])
+ entity_state.apply(Command('stop_entity', 9, '2'))
+ entity_state.render_entities('Test text', {}, [])
|
Entity renderers should be given more data on render
Follow-up to #87. At the moment, entity components are only given a small amount of data about an entity for rendering: https://github.com/springload/draftjs_exporter/blob/764d377659f6c6b48be826c7a7d98cfdbc152015/draftjs_exporter/entity_state.py#L48-L58
There are a few more problems here:
- The shape of the props is different than how this is stored in the Draft.js `entityMap`.
- The entity `data` is given as the top-level props, which makes it impossible to add extra props without risking overwriting the entity data (say if the entity has a field called `type` that does something different from the entity type).
We should refactor this to something like:
```python
props = {}
props['entity'] = entity_details
props['entity']['key'] = key
props['block'] = block
props['blocks'] = blocks
# (Potentially the `entity_range` as well?)
```
This way, it's easy to add arbitrary props without risking overwrites. The components get full access to the entity data, mutability, type, and key. And to the current block and blocks list, like styles, decorators, blocks.
Compared to the changes introduced in #90, this would be a **breaking change**, so should be considered carefully. Users of the exporter will have to rewrite their renderers slightly to use the new props shape.
|
0.0
|
f5b3f516859dfaa444fcdfc1493d8a2c0b65ed04
|
[
"tests/test_entity_state.py::TestEntityState::test_render_entities_data",
"tests/test_entity_state.py::TestEntityState::test_render_entities_data_no_mutability",
"tests/test_entity_state.py::TestEntityState::test_render_entities_inline",
"tests/test_entity_state.py::TestEntityState::test_render_entities_inline_multiple",
"tests/test_entity_state.py::TestEntityState::test_render_entities_unicode",
"tests/test_entity_state.py::TestEntityState::test_render_entities_unstyled"
] |
[
"tests/test_entity_state.py::TestEntityState::test_apply_raises",
"tests/test_entity_state.py::TestEntityState::test_apply_start_entity",
"tests/test_entity_state.py::TestEntityState::test_apply_stop_entity",
"tests/test_entity_state.py::TestEntityState::test_get_entity_details",
"tests/test_entity_state.py::TestEntityState::test_get_entity_details_raises",
"tests/test_entity_state.py::TestEntityState::test_has_no_entity_default",
"tests/test_entity_state.py::TestEntityState::test_has_no_entity_styled",
"tests/test_entity_state.py::TestEntityState::test_init"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-01 17:26:53+00:00
|
mit
| 5,679 |
|
springload__draftjs_exporter-21
|
diff --git a/draftjs_exporter/constants.py b/draftjs_exporter/constants.py
index 882f5ee..8e6e18a 100644
--- a/draftjs_exporter/constants.py
+++ b/draftjs_exporter/constants.py
@@ -3,10 +3,13 @@ from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
- def __init__(self, tupleList):
- self.tupleList = tupleList
+ def __init__(self, *elements):
+ self.elements = tuple(elements)
def __getattr__(self, name):
+ if name not in self.elements:
+ raise AttributeError("'Enum' has no attribute '{}'".format(name))
+
return name
@@ -27,6 +30,6 @@ class BLOCK_TYPES:
ATOMIC = 'atomic'
HORIZONTAL_RULE = 'horizontal-rule'
-ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN'))
+ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN')
-INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
+INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
diff --git a/draftjs_exporter/dom.py b/draftjs_exporter/dom.py
index 0b76d7b..89ab65d 100644
--- a/draftjs_exporter/dom.py
+++ b/draftjs_exporter/dom.py
@@ -13,11 +13,11 @@ except NameError:
unicode = lambda s: str(s)
-def Soup(str):
+def Soup(raw_str):
"""
Wrapper around BeautifulSoup to keep the code DRY.
"""
- return BeautifulSoup(str, 'html5lib')
+ return BeautifulSoup(raw_str, 'html5lib')
class DOM(object):
@@ -25,11 +25,14 @@ class DOM(object):
Wrapper around our HTML building library to facilitate changes.
"""
@staticmethod
- def create_tag(type, attributes={}):
- return Soup('').new_tag(type, **attributes)
+ def create_tag(type_, attributes=None):
+ if attributes is None:
+ attributes = {}
+
+ return Soup('').new_tag(type_, **attributes)
@staticmethod
- def create_element(type=None, props={}, *children):
+ def create_element(type_=None, props=None, *children):
"""
Signature inspired by React.createElement.
createElement(
@@ -39,15 +42,17 @@ class DOM(object):
)
https://facebook.github.io/react/docs/top-level-api.html#react.createelement
"""
- if not type:
+ if props is None:
+ props = {}
+
+ if not type_:
elt = DOM.create_document_fragment()
else:
attributes = {}
# Map props from React/Draft.js to HTML lingo.
if 'className' in props:
- props['class'] = props.get('className')
- props.pop('className', None)
+ props['class'] = props.pop('className')
for key in props:
prop = props[key]
@@ -56,10 +61,10 @@ class DOM(object):
attributes[key] = prop
# "type" is either an entity with a render method, or a tag name.
- if inspect.isclass(type):
- elt = type().render(attributes)
+ if inspect.isclass(type_):
+ elt = type_().render(attributes)
else:
- elt = DOM.create_tag(type, attributes)
+ elt = DOM.create_tag(type_, attributes)
for child in children:
if child:
diff --git a/draftjs_exporter/entities.py b/draftjs_exporter/entities.py
index e0c15f8..2ee9d77 100644
--- a/draftjs_exporter/entities.py
+++ b/draftjs_exporter/entities.py
@@ -3,18 +3,18 @@ from __future__ import absolute_import, unicode_literals
from draftjs_exporter.dom import DOM
-class Null():
+class Null:
def render(self, props):
return DOM.create_element()
-class Icon():
+class Icon:
def render(self, props):
href = 'icon-%s' % props.get('name', '')
return DOM.create_element('svg', {'class': 'icon'}, DOM.create_element('use', {'xlink:href': href}))
-class Image():
+class Image:
def render(self, props):
data = props.get('data', {})
@@ -26,13 +26,13 @@ class Image():
})
-class Link():
+class Link:
attributes = ['url', 'rel', 'target', 'title']
@staticmethod
def is_valid_attribute(key):
# TODO How much do we need to whitelist / blacklist attributes?
- valid_data_attr = (key.startswith('data-') and key.replace('data-', '') and key.replace('data-', '').islower())
+ valid_data_attr = key.startswith('data-') and len(key) > 5 and key.islower()
return key in Link.attributes or valid_data_attr
def render(self, props):
@@ -48,11 +48,16 @@ class Link():
return DOM.create_element('a', attributes)
-class Button():
+class Button:
def render(self, props):
data = props.get('data', {})
href = data.get('href', '#')
icon = data.get('icon', None)
text = data.get('text', '')
- return DOM.create_element('a', {'class': 'icon-text' if icon else None, 'href': href}, DOM.create_element(Icon, {'name': icon}) if icon else None, DOM.create_element('span', {'class': 'icon-text__text'}, text) if icon else text)
+ return DOM.create_element(
+ 'a',
+ {'class': 'icon-text' if icon else None, 'href': href},
+ DOM.create_element(Icon, {'name': icon}) if icon else None,
+ DOM.create_element('span', {'class': 'icon-text__text'}, text) if icon else text
+ )
diff --git a/draftjs_exporter/entity_state.py b/draftjs_exporter/entity_state.py
index 2da83c6..b284a84 100644
--- a/draftjs_exporter/entity_state.py
+++ b/draftjs_exporter/entity_state.py
@@ -8,7 +8,7 @@ class EntityException(ExporterException):
pass
-class EntityState():
+class EntityState:
def __init__(self, root_element, entity_decorators, entity_map):
self.entity_decorators = entity_decorators
self.entity_map = entity_map
@@ -19,9 +19,9 @@ class EntityState():
self.entity_stack = [(stack_start, {})]
def apply(self, command):
- if (command.name == 'start_entity'):
+ if command.name == 'start_entity':
self.start_command(command)
- elif (command.name == 'stop_entity'):
+ elif command.name == 'stop_entity':
self.stop_command(command)
def current_parent(self):
@@ -37,11 +37,11 @@ class EntityState():
return details
def get_entity_decorator(self, entity_details):
- type = entity_details.get('type')
- decorator = self.entity_decorators.get(type)
+ type_ = entity_details.get('type')
+ decorator = self.entity_decorators.get(type_)
if decorator is None:
- raise EntityException('Decorator "%s" does not exist in entity_decorators' % type)
+ raise EntityException('Decorator "%s" does not exist in entity_decorators' % type_)
return decorator
@@ -52,7 +52,7 @@ class EntityState():
new_element = decorator.render(entity_details)
DOM.append_child(self.current_parent(), new_element)
- self.entity_stack.append([new_element, entity_details])
+ self.entity_stack.append((new_element, entity_details))
def stop_command(self, command):
entity_details = self.get_entity_details(command)
diff --git a/draftjs_exporter/html.py b/draftjs_exporter/html.py
index c7be12d..b0cc16b 100644
--- a/draftjs_exporter/html.py
+++ b/draftjs_exporter/html.py
@@ -7,12 +7,15 @@ from draftjs_exporter.style_state import StyleState
from draftjs_exporter.wrapper_state import WrapperState
-class HTML():
+class HTML:
"""
Entry point of the exporter. Combines entity, wrapper and style state
to generate the right HTML nodes.
"""
- def __init__(self, config={}):
+ def __init__(self, config=None):
+ if config is None:
+ config = {}
+
self.entity_decorators = config.get('entity_decorators', {})
self.wrapper_state = WrapperState(config.get('block_map', BLOCK_MAP))
self.style_state = StyleState(config.get('style_map', STYLE_MAP))
diff --git a/draftjs_exporter/style_state.py b/draftjs_exporter/style_state.py
index bb9ccdf..eed38d6 100644
--- a/draftjs_exporter/style_state.py
+++ b/draftjs_exporter/style_state.py
@@ -10,13 +10,13 @@ _first_cap_re = re.compile(r'(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
-def camelToDash(camelCasedStr):
- sub2 = _first_cap_re.sub(r'\1-\2', camelCasedStr)
+def camel_to_dash(camel_cased_str):
+ sub2 = _first_cap_re.sub(r'\1-\2', camel_cased_str)
dashed_case_str = _all_cap_re.sub(r'\1-\2', sub2).lower()
return dashed_case_str.replace('--', '-')
-class StyleState():
+class StyleState:
"""
Handles the creation of inline styles on elements.
Receives inline_style commands, and generates the element's `style`
@@ -52,7 +52,7 @@ class StyleState():
css_style = self.style_map.get(style, {})
for prop in css_style.keys():
if prop != 'element':
- rules.append('{0}: {1};'.format(camelToDash(prop), css_style[prop]))
+ rules.append('{0}: {1};'.format(camel_to_dash(prop), css_style[prop]))
return ''.join(sorted(rules))
diff --git a/draftjs_exporter/wrapper_state.py b/draftjs_exporter/wrapper_state.py
index 8bec7e1..2879d99 100644
--- a/draftjs_exporter/wrapper_state.py
+++ b/draftjs_exporter/wrapper_state.py
@@ -8,7 +8,7 @@ class BlockException(ExporterException):
pass
-class WrapperState():
+class WrapperState:
"""
This class does the initial node building for the tree.
It sets elements with the right tag, text content, and attributes.
@@ -25,19 +25,19 @@ class WrapperState():
]
def element_for(self, block):
- type = block.get('type', 'unstyled')
+ type_ = block.get('type', 'unstyled')
depth = block.get('depth', 0)
- block_options = self.get_block_options(type)
+ block_options = self.get_block_options(type_)
# Make an element from the options specified in the block map.
elt_options = self.map_element_options(block_options.get('element'))
elt = DOM.create_element(elt_options[0], elt_options[1])
- parent = self.parent_for(type, depth)
+ parent = self.parent_for(type_, depth)
DOM.append_child(parent, elt)
# At level 0, the element is added to the document.
- if (depth == 0):
+ if depth == 0:
DOM.append_child(self.document, parent)
return elt
@@ -48,8 +48,8 @@ class WrapperState():
def __str__(self):
return '<WrapperState: %s>' % self.to_string()
- def set_wrapper(self, options=[], depth=0):
- if len(options) == 0:
+ def set_wrapper(self, options=None, depth=0):
+ if not options:
element = DOM.create_document_fragment()
else:
element = DOM.create_element(options[0], options[1])
@@ -73,8 +73,8 @@ class WrapperState():
def get_wrapper_options(self, depth=-1):
return self.wrapper_stack[depth][2]
- def parent_for(self, type, depth):
- block_options = self.get_block_options(type)
+ def parent_for(self, type_, depth):
+ block_options = self.get_block_options(type_)
wrapper_options = block_options.get('wrapper', None)
if wrapper_options:
@@ -95,7 +95,7 @@ class WrapperState():
['ul']
['ul', {'className': 'bullet-list'}]
"""
- if (isinstance(opts, list)):
+ if isinstance(opts, list):
tag = opts[0]
attributes = opts[1] if len(opts) > 1 else {}
else:
@@ -104,11 +104,11 @@ class WrapperState():
return [tag, attributes]
- def get_block_options(self, type):
- block_options = self.block_map.get(type)
+ def get_block_options(self, type_):
+ block_options = self.block_map.get(type_)
if block_options is None:
- raise BlockException('Block "%s" does not exist in block_map' % type)
+ raise BlockException('Block "%s" does not exist in block_map' % type_)
return block_options
|
springload/draftjs_exporter
|
fb287b5d9132aa8f01538aec193eccbc940ccc59
|
diff --git a/tests/test_constants.py b/tests/test_constants.py
index 8d4ad3d..1bf3a41 100644
--- a/tests/test_constants.py
+++ b/tests/test_constants.py
@@ -2,7 +2,21 @@ from __future__ import absolute_import, unicode_literals
import unittest
-from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
+from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
+
+
+class EnumConstants(unittest.TestCase):
+ def test_enum_returns_the_key_if_valid(self):
+ foo_value = 'foo'
+ e = Enum(foo_value)
+
+ self.assertEqual(e.foo, foo_value)
+
+ def test_enum_raises_an_error_for_invalid_keys(self):
+ e = Enum('foo', 'bar')
+
+ with self.assertRaises(AttributeError):
+ e.invalid_key
class TestConstants(unittest.TestCase):
|
Fix code relying on mutable default values
Pointed out by @loicteixeira, this happens a couple of times within the codebase.
|
0.0
|
fb287b5d9132aa8f01538aec193eccbc940ccc59
|
[
"tests/test_constants.py::EnumConstants::test_enum_raises_an_error_for_invalid_keys"
] |
[
"tests/test_constants.py::EnumConstants::test_enum_returns_the_key_if_valid",
"tests/test_constants.py::TestConstants::test_block_types",
"tests/test_constants.py::TestConstants::test_entity_types",
"tests/test_constants.py::TestConstants::test_inline_styles"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-11-16 03:08:00+00:00
|
mit
| 5,680 |
|
springload__draftjs_exporter-22
|
diff --git a/docs/README.md b/docs/README.md
index 919d5dc..f460bf8 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -23,7 +23,6 @@ draftjs_exporter documentation
### Unsupported markup
-* Nested blocks where nesting jumps one level of depth (depth = 0, then depth = 2).
## R&D notes
diff --git a/draftjs_exporter/wrapper_state.py b/draftjs_exporter/wrapper_state.py
index 2879d99..d81e4ce 100644
--- a/draftjs_exporter/wrapper_state.py
+++ b/draftjs_exporter/wrapper_state.py
@@ -33,7 +33,7 @@ class WrapperState:
elt_options = self.map_element_options(block_options.get('element'))
elt = DOM.create_element(elt_options[0], elt_options[1])
- parent = self.parent_for(type_, depth)
+ parent = self.parent_for(block_options, depth)
DOM.append_child(parent, elt)
# At level 0, the element is added to the document.
@@ -48,22 +48,41 @@ class WrapperState:
def __str__(self):
return '<WrapperState: %s>' % self.to_string()
- def set_wrapper(self, options=None, depth=0):
- if not options:
- element = DOM.create_document_fragment()
- else:
- element = DOM.create_element(options[0], options[1])
+ def set_wrapper(self, options=None, elt_options=None, depth=0):
+ if depth >= len(self.wrapper_stack):
+ for d in range(len(self.wrapper_stack), depth + 1):
+ wrapper_elt = self.create_wrapper_elt(options)
+ new_wrapper = [wrapper_elt, d, options]
- new_wrapper = [element, depth, options]
+ wrapper_children = DOM.get_children(self.get_wrapper_elt())
- if depth >= len(self.wrapper_stack):
- DOM.append_child(DOM.get_children(self.get_wrapper_elt())[-1], element)
+ # Determine where to append the new wrapper.
+ if len(wrapper_children) > 0:
+ wrapper_parent = wrapper_children[-1]
+ else:
+ # If there is no content in the current wrapper, we need
+ # to add an intermediary node.
+ wrapper_parent = DOM.create_element(elt_options[0], elt_options[1])
+ DOM.append_child(self.get_wrapper_elt(), wrapper_parent)
- self.wrapper_stack.append(new_wrapper)
+ DOM.append_child(wrapper_parent, wrapper_elt)
+
+ self.wrapper_stack.append(new_wrapper)
else:
+ wrapper_elt = self.create_wrapper_elt(options)
+ new_wrapper = [wrapper_elt, depth, options]
+
# Cut the stack to where it now stops, and add new wrapper.
self.wrapper_stack = self.wrapper_stack[:depth] + [new_wrapper]
+ def create_wrapper_elt(self, options):
+ if options:
+ wrapper_elt = DOM.create_element(options[0], options[1])
+ else:
+ wrapper_elt = DOM.create_document_fragment()
+
+ return wrapper_elt
+
def get_wrapper_elt(self, depth=-1):
return self.wrapper_stack[depth][0]
@@ -73,12 +92,12 @@ class WrapperState:
def get_wrapper_options(self, depth=-1):
return self.wrapper_stack[depth][2]
- def parent_for(self, type_, depth):
- block_options = self.get_block_options(type_)
+ def parent_for(self, block_options, depth):
+ elt_options = self.map_element_options(block_options.get('element'))
wrapper_options = block_options.get('wrapper', None)
if wrapper_options:
- parent = self.get_wrapper(wrapper_options, depth)
+ parent = self.get_wrapper(self.map_element_options(wrapper_options), elt_options, depth)
else:
parent = self.reset_wrapper_stack()
@@ -112,11 +131,9 @@ class WrapperState:
return block_options
- def get_wrapper(self, wrapper_options, depth):
- new_options = self.map_element_options(wrapper_options)
-
- if depth > self.get_wrapper_depth() or new_options != self.get_wrapper_options():
- self.set_wrapper(new_options, depth)
+ def get_wrapper(self, wrapper_options, elt_options, depth):
+ if depth > self.get_wrapper_depth() or wrapper_options != self.get_wrapper_options():
+ self.set_wrapper(wrapper_options, elt_options, depth)
# If depth is lower than the maximum, we need to cut the stack.
if depth < self.get_wrapper_depth():
diff --git a/example.py b/example.py
index c55cfcc..25e7d5f 100644
--- a/example.py
+++ b/example.py
@@ -21,7 +21,7 @@ config = {
'block_map': dict(BLOCK_MAP, **{
BLOCK_TYPES.HEADER_TWO: {
'element': ['h2', {'className': 'c-amazing-heading'}],
- 'wrapper': 'hgroup',
+ 'wrapper': 'div',
},
BLOCK_TYPES.UNORDERED_LIST_ITEM: {
'element': 'li',
@@ -275,4 +275,4 @@ print(pretty)
# Output to a file
with codecs.open('example.html', 'w', 'utf-8') as file:
- file.write('<meta charset="utf-8" />\n' + pretty)
+ file.write('<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Test</title></head><body>\n{pretty}\n</body></html>'.format(pretty=pretty))
|
springload/draftjs_exporter
|
8805d4ad5665c56f8835a100b24408a42b72df60
|
diff --git a/tests/test_constants.py b/tests/test_constants.py
index 1bf3a41..1018e2e 100644
--- a/tests/test_constants.py
+++ b/tests/test_constants.py
@@ -2,7 +2,7 @@ from __future__ import absolute_import, unicode_literals
import unittest
-from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
+from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum
class EnumConstants(unittest.TestCase):
diff --git a/tests/test_output.py b/tests/test_output.py
index 36c4285..98d70de 100644
--- a/tests/test_output.py
+++ b/tests/test_output.py
@@ -596,6 +596,53 @@ class TestOutput(unittest.TestCase):
],
}), '<ul class="steps"><li>A list item (0)<ul class="steps"><li>Oops! (1)<ul class="steps"><li>Does this support nesting? (2)</li><li>Maybe? (2)<ul class="steps"><li>Yep it does! (3)<ul class="steps"><li>How many levels deep? (4)</li></ul></li></ul></li><li>Backtracking, two at once... (2)</li></ul></li><li>Uh oh (1)<ul class="steps"><li>Up, up, and away! (2)</li></ul></li><li>Arh! (1)</li></ul></li><li>Did this work? (0)</li><li>Yes! (0)</li></ul>')
+ def test_render_with_jumping_wrapping(self):
+ self.assertEqual(self.exporter.render({
+ 'entityMap': {},
+ 'blocks': [
+ {
+ 'key': '93agv',
+ 'text': 'A list item (0)',
+ 'type': 'unordered-list-item',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '4ht9m',
+ 'text': 'Jumps (2)',
+ 'type': 'unordered-list-item',
+ 'depth': 2,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc4',
+ 'text': 'Back (0)',
+ 'type': 'unordered-list-item',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc3',
+ 'text': 'Jumps again (3)',
+ 'type': 'unordered-list-item',
+ 'depth': 3,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '3mn5b',
+ 'text': 'Back (1)',
+ 'type': 'unordered-list-item',
+ 'depth': 1,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ ],
+ }), '<ul class="steps"><li>A list item (0)<ul class="steps"><li><ul class="steps"><li>Jumps (2)</li></ul></li></ul></li><li>Back (0)<ul class="steps"><li><ul class="steps"><li><ul class="steps"><li>Jumps again (3)</li></ul></li></ul></li><li>Back (1)</li></ul></li></ul>')
+
def test_render_with_big_content(self):
self.assertEqual(HTML({
'entity_decorators': {
|
Support arbitrary nesting levels
The exporter should support blocks going from depth 0 to depth 3, or any depth jump, as this frequently happens with real-world HTML.
|
0.0
|
8805d4ad5665c56f8835a100b24408a42b72df60
|
[
"tests/test_output.py::TestOutput::test_render_with_jumping_wrapping"
] |
[
"tests/test_constants.py::EnumConstants::test_enum_raises_an_error_for_invalid_keys",
"tests/test_constants.py::EnumConstants::test_enum_returns_the_key_if_valid",
"tests/test_constants.py::TestConstants::test_block_types",
"tests/test_constants.py::TestConstants::test_entity_types",
"tests/test_constants.py::TestConstants::test_inline_styles",
"tests/test_output.py::TestOutput::test_render_emptiest",
"tests/test_output.py::TestOutput::test_render_empty",
"tests/test_output.py::TestOutput::test_render_with_backtracking_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_big_content",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_false",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_true",
"tests/test_output.py::TestOutput::test_render_with_default_block_map",
"tests/test_output.py::TestOutput::test_render_with_default_config",
"tests/test_output.py::TestOutput::test_render_with_default_style_map",
"tests/test_output.py::TestOutput::test_render_with_different_blocks",
"tests/test_output.py::TestOutput::test_render_with_element_options",
"tests/test_output.py::TestOutput::test_render_with_entities",
"tests/test_output.py::TestOutput::test_render_with_entities_crossing_raises",
"tests/test_output.py::TestOutput::test_render_with_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_multiple_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_none_attribute",
"tests/test_output.py::TestOutput::test_render_with_number_attribute",
"tests/test_output.py::TestOutput::test_render_with_token_entity",
"tests/test_output.py::TestOutput::test_render_with_unicode",
"tests/test_output.py::TestOutput::test_render_with_unidirectional_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_unknown_attribute",
"tests/test_output.py::TestOutput::test_render_with_wrapping"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-11-16 16:44:35+00:00
|
mit
| 5,681 |
|
springload__draftjs_exporter-57
|
diff --git a/draftjs_exporter/wrapper_state.py b/draftjs_exporter/wrapper_state.py
index 23db901..6eddd06 100644
--- a/draftjs_exporter/wrapper_state.py
+++ b/draftjs_exporter/wrapper_state.py
@@ -116,10 +116,7 @@ class WrapperState:
DOM.append_child(parent, elt)
else:
# Reset the stack if there is no wrapper.
- head = self.stack.head()
- if self.stack.length() > 0 and head.depth != -1 and head.props is not None:
- self.stack.slice(-1)
- self.stack.append(Wrapper(-1, None))
+ self.stack = WrapperStack()
parent = elt
return parent
|
springload/draftjs_exporter
|
8b22a8c98b879c47eb54c58df3471c0d9680bd45
|
diff --git a/tests/test_output.py b/tests/test_output.py
index 0c61693..76de968 100644
--- a/tests/test_output.py
+++ b/tests/test_output.py
@@ -5,15 +5,26 @@ import unittest
from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
from draftjs_exporter.defaults import BLOCK_MAP
+from draftjs_exporter.dom import DOM
from draftjs_exporter.entity_state import EntityException
from draftjs_exporter.html import HTML
from tests.test_composite_decorators import BR, Hashtag, Linkify
-from tests.test_entities import HR, Link
+from tests.test_entities import HR, Image, Link
+
+
+def Blockquote(props):
+ block_data = props['block']['data']
+
+ return DOM.create_element('blockquote', {
+ 'cite': block_data.get('cite')
+ }, props['children'])
+
config = {
'entity_decorators': {
ENTITY_TYPES.LINK: Link,
ENTITY_TYPES.HORIZONTAL_RULE: HR,
+ ENTITY_TYPES.IMAGE: Image
},
'composite_decorators': [
Linkify,
@@ -26,6 +37,10 @@ config = {
'wrapper': 'ul',
'wrapper_props': {'className': 'steps'},
},
+ 'blockquote': {
+ 'element': Blockquote,
+ 'wrapper': 'div',
+ },
}),
'style_map': {
INLINE_STYLES.CODE: 'code',
@@ -496,6 +511,106 @@ class TestOutput(unittest.TestCase):
]
}), '<ul class="steps"><li>item1</li><li>item2</li></ul><hr/>')
+ def test_render_with_wrapping_reset(self):
+ self.assertEqual(self.exporter.render({
+ 'entityMap': {},
+ 'blocks': [
+ {
+ 'key': '93agv',
+ 'text': '1',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '4ht9m',
+ 'text': '2',
+ 'type': 'unordered-list-item',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc4',
+ 'text': '3',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc3',
+ 'text': '4',
+ 'type': 'unordered-list-item',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '3mn5b',
+ 'text': '5',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ ],
+ }), '<p>1</p><ul class="steps"><li>2</li></ul><p>3</p><ul class="steps"><li>4</li></ul><p>5</p>')
+
+ def test_render_with_wrapping_reset_block_components(self):
+ self.assertEqual(self.exporter.render({
+ 'entityMap': {},
+ 'blocks': [
+ {
+ 'key': '93agv',
+ 'text': '1',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '4ht9m',
+ 'text': '2',
+ 'type': 'blockquote',
+ 'depth': 0,
+ 'data': {
+ 'cite': '2'
+ },
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc4',
+ 'text': '3',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': 'c6gc3',
+ 'text': '4',
+ 'type': 'blockquote',
+ 'depth': 0,
+ 'data': {
+ 'cite': '4'
+ },
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ {
+ 'key': '3mn5b',
+ 'text': '5',
+ 'type': 'unstyled',
+ 'depth': 0,
+ 'inlineStyleRanges': [],
+ 'entityRanges': [],
+ },
+ ],
+ }), '<p>1</p><div><blockquote cite="2">2</blockquote></div><p>3</p><div><blockquote cite="4">4</blockquote></div><p>5</p>')
+
def test_render_with_unidirectional_nested_wrapping(self):
self.assertEqual(self.exporter.render({
'entityMap': {},
|
Custom components switch places
I have two custom components: image and direct speech. There's nothing very fancy in their code, e.g. image is rendered like this:
```py
class Image:
def render(self, props):
data = props['block']['data']
return self.wrapper(data)
def wrapper(self, data):
caption = data.get('caption', '')
return tags.div(
{'class': 'contentImage'},
self.image(data),
DOM.create_text_node(caption))
def image(self, data):
src = data.get('image', '')
caption = data.get('caption', '')
return tags.img({
'src': src,
'class': 'contentImage-image',
'alt': caption})
```
then I generate the content for the blocks (not important fields are dropped):
```
{
"blocks":[
{
"text":"Start text",
"type":"unstyled",
...
},
{
"type":"image",
"data":{
"caption":"Some image caption",
"image":"http://placekitten.com/401/402"
},
...
},
{
"text":"Middle text",
"type":"unstyled",
...
},
{
"type":"direct-speech",
"data":{
"name":"Steve Jobs",
"image":"http://placekitten.com/500/501",
"text":"Hello, world!!!!111"
},
...
},
{
"text":"Last text",
"type":"unstyled",
...
}
]
...
}
```
I expect "Middle text" block to be between the image and direct speech, but for some reason these two blocks are rendered together and the text appears before them:
```html
<p>Start text</p>
<p>Middle text</p>
<div>
<div class="contentImage">
<img class="contentImage-image" src="http://placekitten.com/401/402">Some image caption
</div>
<blockquote class="directSpeech">
<div class="directSpeech-image" style="background-image: url(http://placekitten.com/500/501);"></div>
<div class="directSpeech-wrapper">
<div class="directSpeech-title">
Steve Jobs
</div>
<p class="directSpeech-text">Hello, world!!!!111</p>
</div>
</blockquote>
</div>
<p>Last text</p>
```
I hope the bug is reproducable; if you have any questions or need more details I'll provide you any information.
|
0.0
|
8b22a8c98b879c47eb54c58df3471c0d9680bd45
|
[
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset_block_components"
] |
[
"tests/test_output.py::TestOutput::test_render_emptiest",
"tests/test_output.py::TestOutput::test_render_empty",
"tests/test_output.py::TestOutput::test_render_with_backtracking_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_big_content",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_false",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_true",
"tests/test_output.py::TestOutput::test_render_with_default_block_map",
"tests/test_output.py::TestOutput::test_render_with_default_config",
"tests/test_output.py::TestOutput::test_render_with_default_style_map",
"tests/test_output.py::TestOutput::test_render_with_different_blocks",
"tests/test_output.py::TestOutput::test_render_with_element_options",
"tests/test_output.py::TestOutput::test_render_with_entities",
"tests/test_output.py::TestOutput::test_render_with_entities_crossing_raises",
"tests/test_output.py::TestOutput::test_render_with_entity_and_decorators",
"tests/test_output.py::TestOutput::test_render_with_immediate_jumping",
"tests/test_output.py::TestOutput::test_render_with_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_jumping_wrapping",
"tests/test_output.py::TestOutput::test_render_with_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_many_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_multiple_decorators",
"tests/test_output.py::TestOutput::test_render_with_multiple_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_no_zero_depth",
"tests/test_output.py::TestOutput::test_render_with_none_attribute",
"tests/test_output.py::TestOutput::test_render_with_number_attribute",
"tests/test_output.py::TestOutput::test_render_with_styles_in_entities",
"tests/test_output.py::TestOutput::test_render_with_token_entity",
"tests/test_output.py::TestOutput::test_render_with_unicode",
"tests/test_output.py::TestOutput::test_render_with_unidirectional_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_unknown_attribute",
"tests/test_output.py::TestOutput::test_render_with_wrapping",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-25 08:00:08+00:00
|
mit
| 5,682 |
|
springload__draftjs_exporter-81
|
diff --git a/benchmark.py b/benchmark.py
index 40ae663..0d0855e 100644
--- a/benchmark.py
+++ b/benchmark.py
@@ -69,7 +69,7 @@ config = {
'component': br,
}
],
- 'engine': 'string',
+ 'engine': DOM.STRING,
}
exporter = HTML(config)
@@ -78,8 +78,7 @@ content_states = get_content_sample()
BENCHMARK_RUNS = int(os.environ.get('BENCHMARK_RUNS', 1))
-print('Exporting %s ContentStates %s times' %
- (len(content_states), BENCHMARK_RUNS))
+print('Exporting %s ContentStates %s times' % (len(content_states), BENCHMARK_RUNS))
pr = cProfile.Profile()
pr.enable()
diff --git a/draftjs_exporter/dom.py b/draftjs_exporter/dom.py
index e3b9424..967253b 100644
--- a/draftjs_exporter/dom.py
+++ b/draftjs_exporter/dom.py
@@ -1,10 +1,8 @@
from __future__ import absolute_import, unicode_literals
-import inspect
import re
-from draftjs_exporter.engines.html5lib import DOM_HTML5LIB
-from draftjs_exporter.error import ConfigException
+from draftjs_exporter.utils.module_loading import import_string
# Python 2/3 unicode compatibility hack.
# See http://stackoverflow.com/questions/6812031/how-to-make-unicode-string-with-python3
@@ -24,11 +22,11 @@ class DOM(object):
Component building API, abstracting the DOM implementation.
"""
- HTML5LIB = 'html5lib'
- LXML = 'lxml'
- STRING = 'string'
+ HTML5LIB = 'draftjs_exporter.engines.html5lib.DOM_HTML5LIB'
+ LXML = 'draftjs_exporter.engines.lxml.DOM_LXML'
+ STRING = 'draftjs_exporter.engines.string.DOMString'
- dom = DOM_HTML5LIB
+ dom = None
@staticmethod
def camel_to_dash(camel_cased_str):
@@ -37,23 +35,11 @@ class DOM(object):
return dashed_case_str.replace('--', '-')
@classmethod
- def use(cls, engine=DOM_HTML5LIB):
+ def use(cls, engine):
"""
Choose which DOM implementation to use.
"""
- if engine:
- if inspect.isclass(engine):
- cls.dom = engine
- elif engine.lower() == cls.HTML5LIB:
- cls.dom = DOM_HTML5LIB
- elif engine.lower() == cls.LXML:
- from draftjs_exporter.engines.lxml import DOM_LXML
- cls.dom = DOM_LXML
- elif engine.lower() == cls.STRING:
- from draftjs_exporter.engines.string import DOMString
- cls.dom = DOMString
- else:
- raise ConfigException('Invalid DOM engine.')
+ cls.dom = import_string(engine)
@classmethod
def create_element(cls, type_=None, props=None, *children):
diff --git a/draftjs_exporter/html.py b/draftjs_exporter/html.py
index 0f0a9bd..2eb5264 100644
--- a/draftjs_exporter/html.py
+++ b/draftjs_exporter/html.py
@@ -25,7 +25,7 @@ class HTML:
self.block_map = config.get('block_map', BLOCK_MAP)
self.style_map = config.get('style_map', STYLE_MAP)
- DOM.use(config.get('engine'))
+ DOM.use(config.get('engine', DOM.HTML5LIB))
def render(self, content_state=None):
"""
diff --git a/draftjs_exporter/utils/__init__.py b/draftjs_exporter/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/draftjs_exporter/utils/module_loading.py b/draftjs_exporter/utils/module_loading.py
new file mode 100644
index 0000000..5207cab
--- /dev/null
+++ b/draftjs_exporter/utils/module_loading.py
@@ -0,0 +1,26 @@
+from __future__ import absolute_import, unicode_literals
+
+from importlib import import_module
+
+
+def import_string(dotted_path):
+ """
+ Import a dotted module path and return the attribute/class designated by the
+ last name in the path. Raise ImportError if the import failed.
+
+ Taken from Django:
+ https://github.com/django/django/blob/f6bd00131e687aedf2719ad31e84b097562ca5f2/django/utils/module_loading.py#L7-L24
+ """
+ try:
+ module_path, class_name = dotted_path.rsplit('.', 1)
+ except ValueError:
+ raise ImportError("%s doesn't look like a module path" % dotted_path)
+
+ module = import_module(module_path)
+
+ try:
+ return getattr(module, class_name)
+ except AttributeError:
+ raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
+ module_path, class_name)
+ )
diff --git a/example.py b/example.py
index bd4f657..6fa442b 100644
--- a/example.py
+++ b/example.py
@@ -186,7 +186,7 @@ if __name__ == '__main__':
},
],
# Specify which DOM backing engine to use.
- 'engine': 'string',
+ 'engine': DOM.STRING,
}
exporter = HTML(config)
@@ -623,11 +623,9 @@ if __name__ == '__main__':
pr.disable()
p = Stats(pr)
-
def prettify(markup):
return re.sub(r'</?(body|html|head)>', '', BeautifulSoup(markup, 'html5lib').prettify()).strip()
-
pretty = prettify(markup)
# Display in console.
|
springload/draftjs_exporter
|
183d06db62cbbc5c9d1d6bc41e22fff1f8a5e6b5
|
diff --git a/tests/__init__.py b/tests/__init__.py
index e69de29..21a0fb6 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -0,0 +1,6 @@
+from __future__ import absolute_import, unicode_literals
+
+from draftjs_exporter.dom import DOM
+
+# Initialise a default engine for the test suites.
+DOM.use(DOM.HTML5LIB)
diff --git a/tests/test_dom.py b/tests/test_dom.py
index e4b7617..48eed62 100644
--- a/tests/test_dom.py
+++ b/tests/test_dom.py
@@ -5,7 +5,6 @@ import unittest
from draftjs_exporter.dom import DOM
from draftjs_exporter.engines.html5lib import DOM_HTML5LIB
from draftjs_exporter.engines.lxml import DOM_LXML
-from draftjs_exporter.error import ConfigException
from tests.test_entities import icon
@@ -19,7 +18,7 @@ class TestDOM(unittest.TestCase):
DOM.use(DOM.HTML5LIB)
def test_use_custom(self):
- DOM.use(DOMTestImpl)
+ DOM.use('tests.test_dom.DOMTestImpl')
self.assertEqual(DOM.dom, DOMTestImpl)
def test_use_lxml(self):
@@ -31,7 +30,7 @@ class TestDOM(unittest.TestCase):
self.assertEqual(DOM.dom, DOM_HTML5LIB)
def test_use_invalid(self):
- with self.assertRaises(ConfigException):
+ with self.assertRaises(ImportError):
DOM.use('test')
diff --git a/tests/test_exports.py b/tests/test_exports.py
index dfd50a6..7cd4060 100644
--- a/tests/test_exports.py
+++ b/tests/test_exports.py
@@ -50,26 +50,20 @@ class TestExportsMeta(type):
See http://stackoverflow.com/a/20870875/1798491
"""
def __new__(mcs, name, bases, tests):
- def gen_test(export, engine):
+ def gen_test(content, html):
def test(self):
- self.maxDiff = None
- DOM.use(engine)
- self.assertEqual(exporter.render(export['content_state']), export['output'][engine])
+ self.assertEqual(exporter.render(content), html)
return test
- if name == 'TestExportsHTML5LIB':
- engine = 'html5lib'
- elif name == 'TestExportsLXML':
- engine = 'lxml'
- elif name == 'TestExportsSTRING':
- engine = 'string'
+ engine = name.replace('TestExports', '').lower()
for export in fixtures:
test_label = export['label'].lower().replace(' ', '_')
test_name = 'test_export_{0}_{1}'.format(engine, test_label)
- tests[test_name] = gen_test(export, engine)
-
+ content = export['content_state']
+ html = export['output'][engine]
+ tests[test_name] = gen_test(content, html)
return type.__new__(mcs, name, bases, tests)
@@ -77,6 +71,7 @@ class TestExportsMeta(type):
class TestExportsHTML5LIB(six.with_metaclass(TestExportsMeta, unittest.TestCase)):
@classmethod
def setUpClass(cls):
+ DOM.use(DOM.HTML5LIB)
cls.pr = cProfile.Profile()
cls.pr.enable()
print('\nhtml5lib')
@@ -86,13 +81,11 @@ class TestExportsHTML5LIB(six.with_metaclass(TestExportsMeta, unittest.TestCase)
cls.pr.disable()
Stats(cls.pr).strip_dirs().sort_stats('cumulative').print_stats(0)
- def test_init_html5lib(self):
- self.assertIsInstance(exporter, HTML)
-
class TestExportsLXML(six.with_metaclass(TestExportsMeta, unittest.TestCase)):
@classmethod
def setUpClass(cls):
+ DOM.use(DOM.LXML)
cls.pr = cProfile.Profile()
cls.pr.enable()
print('\nlxml')
@@ -102,13 +95,11 @@ class TestExportsLXML(six.with_metaclass(TestExportsMeta, unittest.TestCase)):
cls.pr.disable()
Stats(cls.pr).strip_dirs().sort_stats('cumulative').print_stats(0)
- def test_init(self):
- self.assertIsInstance(exporter, HTML)
-
class TestExportsSTRING(six.with_metaclass(TestExportsMeta, unittest.TestCase)):
@classmethod
def setUpClass(cls):
+ DOM.use(DOM.STRING)
cls.pr = cProfile.Profile()
cls.pr.enable()
print('\nstring')
@@ -118,9 +109,6 @@ class TestExportsSTRING(six.with_metaclass(TestExportsMeta, unittest.TestCase)):
cls.pr.disable()
Stats(cls.pr).strip_dirs().sort_stats('cumulative').print_stats(0)
- def test_init(self):
- self.assertIsInstance(exporter, HTML)
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_output.py b/tests/test_output.py
index fac2bfb..28726d7 100644
--- a/tests/test_output.py
+++ b/tests/test_output.py
@@ -5,6 +5,7 @@ import unittest
from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
from draftjs_exporter.defaults import BLOCK_MAP
+from draftjs_exporter.dom import DOM
from draftjs_exporter.entity_state import EntityException
from draftjs_exporter.html import HTML
from tests.test_composite_decorators import BR_DECORATOR, HASHTAG_DECORATOR, LINKIFY_DECORATOR
@@ -42,7 +43,7 @@ config = {
'props': {'style': {'textDecoration': 'underline'}},
},
},
- 'engine': 'html5lib'
+ 'engine': DOM.HTML5LIB
}
@@ -50,6 +51,7 @@ class TestOutput(unittest.TestCase):
"""
Test cases related to specific features of the HTML builder.
"""
+
def setUp(self):
self.maxDiff = None
self.exporter = HTML(config)
diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/utils/test_module_loading.py b/tests/utils/test_module_loading.py
new file mode 100644
index 0000000..d6735d8
--- /dev/null
+++ b/tests/utils/test_module_loading.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+
+import unittest
+
+from draftjs_exporter.utils.module_loading import import_string
+
+
+class TestModuleLoading(unittest.TestCase):
+ """
+ Taken from Django:
+ https://github.com/django/django/blob/f6bd00131e687aedf2719ad31e84b097562ca5f2/tests/utils_tests/test_module_loading.py#L122-L132
+ """
+ def test_import_string_success(self):
+ cls = import_string('draftjs_exporter.utils.module_loading.import_string')
+ self.assertEqual(cls, import_string)
+
+ def test_import_string_invalid(self):
+ with self.assertRaises(ImportError):
+ import_string('no_dots_in_path')
+
+ def test_import_string_unexistent(self):
+ with self.assertRaises(ImportError):
+ import_string('tests.utils.unexistent')
|
Use Django-style loading via path for custom backing engines
> It would be handy to allow custom engines to be loaded via path (and not only by passing the class) with `django.utils.module_loading.import_string`.
So we don't tie this project to Django, here is the [`import_string` source code](https://docs.djangoproject.com/en/1.11/_modules/django/utils/module_loading/#import_string) which only relies on `six`.
|
0.0
|
183d06db62cbbc5c9d1d6bc41e22fff1f8a5e6b5
|
[
"tests/test_dom.py::TestDOM::test_append_child",
"tests/test_dom.py::TestDOM::test_camel_to_dash",
"tests/test_dom.py::TestDOM::test_create_element",
"tests/test_dom.py::TestDOM::test_create_element_empty",
"tests/test_dom.py::TestDOM::test_create_element_entity",
"tests/test_dom.py::TestDOM::test_create_element_nested",
"tests/test_dom.py::TestDOM::test_create_element_none",
"tests/test_dom.py::TestDOM::test_create_element_style_dict",
"tests/test_dom.py::TestDOM::test_create_element_style_str",
"tests/test_dom.py::TestDOM::test_parse_html",
"tests/test_dom.py::TestDOM::test_render_debug",
"tests/test_dom.py::TestDOM::test_use_custom",
"tests/test_dom.py::TestDOM::test_use_html5lib",
"tests/test_dom.py::TestDOM::test_use_invalid",
"tests/test_dom.py::TestDOM::test_use_lxml",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_adjacent_inline_styles",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_big_content_export",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity_with_data-*",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_entity_with_inline_style",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_html_entities_escaping",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_multiple_decorators",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_nested_inline_styles",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_ordered_list",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_plain_text",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_same_content_multiple_times",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_single_inline_style",
"tests/test_exports.py::TestExportsHTML5LIB::test_export_html5lib_style_map_defaults",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_adjacent_inline_styles",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_entity",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_entity_with_inline_style",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_html_entities_escaping",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_multiple_decorators",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_nested_inline_styles",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_ordered_list",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_plain_text",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_same_content_multiple_times",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_single_inline_style",
"tests/test_exports.py::TestExportsLXML::test_export_lxml_style_map_defaults",
"tests/test_exports.py::TestExportsSTRING::test_export_string_adjacent_inline_styles",
"tests/test_exports.py::TestExportsSTRING::test_export_string_all_plain_html_elements_we_need",
"tests/test_exports.py::TestExportsSTRING::test_export_string_big_content_export",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity_with_data-*",
"tests/test_exports.py::TestExportsSTRING::test_export_string_entity_with_inline_style",
"tests/test_exports.py::TestExportsSTRING::test_export_string_from_https://github.com/icelab/draft-js-ast-exporter/blob/651c807bea12d97dad6f4965ab40481c8f2130dd/test/fixtures/content.js",
"tests/test_exports.py::TestExportsSTRING::test_export_string_html_entities_escaping",
"tests/test_exports.py::TestExportsSTRING::test_export_string_multiple_decorators",
"tests/test_exports.py::TestExportsSTRING::test_export_string_nested_inline_styles",
"tests/test_exports.py::TestExportsSTRING::test_export_string_nested_inline_styles_(inverted)",
"tests/test_exports.py::TestExportsSTRING::test_export_string_ordered_list",
"tests/test_exports.py::TestExportsSTRING::test_export_string_plain_text",
"tests/test_exports.py::TestExportsSTRING::test_export_string_same_content_multiple_times",
"tests/test_exports.py::TestExportsSTRING::test_export_string_single_inline_style",
"tests/test_exports.py::TestExportsSTRING::test_export_string_style_map_defaults",
"tests/test_output.py::TestOutput::test_render_empty",
"tests/test_output.py::TestOutput::test_render_with_backtracking_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_big_content",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_false",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_true",
"tests/test_output.py::TestOutput::test_render_with_default_block_map",
"tests/test_output.py::TestOutput::test_render_with_default_config",
"tests/test_output.py::TestOutput::test_render_with_default_style_map",
"tests/test_output.py::TestOutput::test_render_with_different_blocks",
"tests/test_output.py::TestOutput::test_render_with_element_options",
"tests/test_output.py::TestOutput::test_render_with_entities",
"tests/test_output.py::TestOutput::test_render_with_entities_crossing_raises",
"tests/test_output.py::TestOutput::test_render_with_entity",
"tests/test_output.py::TestOutput::test_render_with_entity_and_decorators",
"tests/test_output.py::TestOutput::test_render_with_immediate_jumping",
"tests/test_output.py::TestOutput::test_render_with_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_jumping_wrapping",
"tests/test_output.py::TestOutput::test_render_with_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_many_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_multiple_decorators",
"tests/test_output.py::TestOutput::test_render_with_multiple_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_no_zero_depth",
"tests/test_output.py::TestOutput::test_render_with_none_attribute",
"tests/test_output.py::TestOutput::test_render_with_none_component",
"tests/test_output.py::TestOutput::test_render_with_none_return_value",
"tests/test_output.py::TestOutput::test_render_with_number_attribute",
"tests/test_output.py::TestOutput::test_render_with_styles_in_entities",
"tests/test_output.py::TestOutput::test_render_with_unicode",
"tests/test_output.py::TestOutput::test_render_with_unidirectional_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_unknown_attribute",
"tests/test_output.py::TestOutput::test_render_with_wrapping",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset_block_components",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_invalid",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_success",
"tests/utils/test_module_loading.py::TestModuleLoading::test_import_string_unexistent"
] |
[] |
{
"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
}
|
2017-11-21 10:21:54+00:00
|
mit
| 5,683 |
|
springload__draftjs_exporter-85
|
diff --git a/README.rst b/README.rst
index 94898d6..20b58a9 100644
--- a/README.rst
+++ b/README.rst
@@ -248,33 +248,22 @@ See ``examples.py`` in the repository for more details.
Alternative backing engines
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-By default the exporter uses ``html5lib`` via BeautifulSoup to build the DOM tree. There are two alternative backing engines: ``string`` and ``lxml``.
+By default, the exporter uses a dependency-free engine called ``string`` to build the DOM tree. There are two alternative backing engines: ``html5lib`` (via BeautifulSoup) and ``lxml``.
-The ``string`` engine is the fastest, and does not have any dependencies. Its only drawback is that the ``parse_html`` method does not escape/sanitise HTML like that of other engines.
+The ``string`` engine is the fastest, and does not have any dependencies. Its only drawback is that the ``parse_html`` method does not escape/sanitise HTML like that of other engines. It is also more recent, so hasn't been as battle-tested as the other ones.
-To use it, add the following to the exporter config:
+* For ``html5lib``, do ``pip install draftjs_exporter[html5lib]``.
+* For ``lxml``, do ``pip install draftjs_exporter[lxml]``. It also requires ``libxml2`` and ``libxslt`` to be available on your system.
-.. code:: python
-
- config = {
- # Specify which DOM backing engine to use.
- 'engine': 'string',
- }
-
-``lxml`` is also supported. It requires ``libxml2`` and ``libxslt`` to be available on your system.
-
-.. code:: sh
-
- # Use the `lxml` extra to install the exporter and its lxml dependencies:
- pip install draftjs_exporter[lxml]
-
-Add the following to the exporter config:
+Then, use the ``engine`` attribute of the exporter config:
.. code:: python
config = {
# Specify which DOM backing engine to use.
- 'engine': 'lxml',
+ 'engine': DOM.HTML5LIB,
+ # Or for lxml:
+ 'engine': DOM.LXML,
}
Custom backing engines
@@ -307,7 +296,10 @@ Here is an example implementation:
return elt
- exporter = HTML({'engine': DOMListTree})
+ exporter = HTML({
+ # Use the dotted module syntax to point to the DOMEngine implementation.
+ 'engine': 'myproject.example.DOMListTree'
+ })
Development
-----------
diff --git a/draftjs_exporter/html.py b/draftjs_exporter/html.py
index 2eb5264..9c4ce2b 100644
--- a/draftjs_exporter/html.py
+++ b/draftjs_exporter/html.py
@@ -25,7 +25,7 @@ class HTML:
self.block_map = config.get('block_map', BLOCK_MAP)
self.style_map = config.get('style_map', STYLE_MAP)
- DOM.use(config.get('engine', DOM.HTML5LIB))
+ DOM.use(config.get('engine', DOM.STRING))
def render(self, content_state=None):
"""
diff --git a/setup.py b/setup.py
index c6438ed..4f0cb3b 100755
--- a/setup.py
+++ b/setup.py
@@ -11,8 +11,9 @@ try:
except ImportError:
from distutils.core import setup
+dependencies = []
-dependencies = [
+html5lib_dependencies = [
'beautifulsoup4>=4.4.1,<5',
'html5lib>=0.999,<=1.0b10',
]
@@ -34,7 +35,7 @@ testing_dependencies = [
'coverage>=4.1.0',
'flake8>=3.2.0',
'isort==4.2.5',
-] + lxml_dependencies
+] + html5lib_dependencies + lxml_dependencies
documentation_dependencies = [
@@ -78,5 +79,6 @@ setup(
'testing': testing_dependencies,
'docs': documentation_dependencies,
'lxml': lxml_dependencies,
+ 'html5lib': html5lib_dependencies,
},
zip_safe=False)
|
springload/draftjs_exporter
|
7acd6218f1a8460efd67965bb227dca16cf65bf0
|
diff --git a/tests/test_composite_decorators.py b/tests/test_composite_decorators.py
index 721f4dd..aeb029c 100644
--- a/tests/test_composite_decorators.py
+++ b/tests/test_composite_decorators.py
@@ -55,7 +55,7 @@ class TestHashtag(unittest.TestCase):
self.assertEqual(DOM.render(DOM.create_element(HASHTAG_DECORATOR['component'], {'block': {'type': BLOCK_TYPES.UNSTYLED}}, '#hashtagtest')), '<span class="hashtag">#hashtagtest</span>')
def test_render_code_block(self):
- self.assertEqual(DOM.render(DOM.create_element(HASHTAG_DECORATOR['component'], {'block': {'type': BLOCK_TYPES.CODE}}, '#hashtagtest')), '#hashtagtest')
+ self.assertEqual(DOM.create_element(HASHTAG_DECORATOR['component'], {'block': {'type': BLOCK_TYPES.CODE}}, '#hashtagtest'), '#hashtagtest')
class TestBR(unittest.TestCase):
@@ -68,7 +68,7 @@ class TestBR(unittest.TestCase):
class TestCompositeDecorators(unittest.TestCase):
def test_render_decorators_empty(self):
- self.assertEqual(DOM.render(render_decorators([], 'test https://www.example.com#hash #hashtagtest', {'type': BLOCK_TYPES.UNSTYLED, 'depth': 0})), 'test https://www.example.com#hash #hashtagtest')
+ self.assertEqual(render_decorators([], 'test https://www.example.com#hash #hashtagtest', {'type': BLOCK_TYPES.UNSTYLED, 'depth': 0}), 'test https://www.example.com#hash #hashtagtest')
def test_render_decorators_single(self):
self.assertEqual(DOM.render(render_decorators([LINKIFY_DECORATOR], 'test https://www.example.com#hash #hashtagtest', {'type': BLOCK_TYPES.UNSTYLED, 'depth': 0})), 'test <a href="https://www.example.com#hash">https://www.example.com#hash</a> #hashtagtest')
diff --git a/tests/test_dom.py b/tests/test_dom.py
index 48eed62..e5d5172 100644
--- a/tests/test_dom.py
+++ b/tests/test_dom.py
@@ -5,6 +5,7 @@ import unittest
from draftjs_exporter.dom import DOM
from draftjs_exporter.engines.html5lib import DOM_HTML5LIB
from draftjs_exporter.engines.lxml import DOM_LXML
+from draftjs_exporter.engines.string import DOMString
from tests.test_entities import icon
@@ -29,6 +30,10 @@ class TestDOM(unittest.TestCase):
DOM.use(DOM.HTML5LIB)
self.assertEqual(DOM.dom, DOM_HTML5LIB)
+ def test_use_string(self):
+ DOM.use(DOM.STRING)
+ self.assertEqual(DOM.dom, DOMString)
+
def test_use_invalid(self):
with self.assertRaises(ImportError):
DOM.use('test')
diff --git a/tests/test_html.py b/tests/test_html.py
index 86a2ceb..069196a 100644
--- a/tests/test_html.py
+++ b/tests/test_html.py
@@ -3,6 +3,8 @@ from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.command import Command
+from draftjs_exporter.dom import DOM
+from draftjs_exporter.engines.string import DOMString
from draftjs_exporter.html import HTML
config = {
@@ -29,6 +31,10 @@ class TestHTML(unittest.TestCase):
def test_init(self):
self.assertIsInstance(self.exporter, HTML)
+ def test_init_dom_engine_default(self):
+ HTML()
+ self.assertEqual(DOM.dom, DOMString)
+
def test_render_block_exists(self):
self.assertTrue('render_block' in dir(self.exporter))
diff --git a/tests/test_output.py b/tests/test_output.py
index 28726d7..3922ee4 100644
--- a/tests/test_output.py
+++ b/tests/test_output.py
@@ -43,7 +43,7 @@ config = {
'props': {'style': {'textDecoration': 'underline'}},
},
},
- 'engine': DOM.HTML5LIB
+ 'engine': DOM.STRING,
}
diff --git a/tests/test_style_state.py b/tests/test_style_state.py
index 8101933..44b3120 100644
--- a/tests/test_style_state.py
+++ b/tests/test_style_state.py
@@ -32,7 +32,7 @@ style_map = {
class TestStyleState(unittest.TestCase):
def setUp(self):
- DOM.use(DOM.HTML5LIB)
+ DOM.use(DOM.STRING)
self.style_state = StyleState(style_map)
def test_init(self):
diff --git a/tests/test_wrapper_state.py b/tests/test_wrapper_state.py
index 60deb78..8d2cebe 100644
--- a/tests/test_wrapper_state.py
+++ b/tests/test_wrapper_state.py
@@ -9,7 +9,7 @@ from example import blockquote, list_item, ordered_list
class TestWrapperState(unittest.TestCase):
def setUp(self):
- DOM.use(DOM.HTML5LIB)
+ DOM.use(DOM.STRING)
self.wrapper_state = WrapperState({
'header-one': 'h1',
@@ -106,7 +106,7 @@ class TestWrapperState(unittest.TestCase):
class TestBlockquote(unittest.TestCase):
def setUp(self):
- DOM.use(DOM.HTML5LIB)
+ DOM.use(DOM.STRING)
def test_render_debug(self):
self.assertEqual(DOM.render_debug(DOM.create_element(blockquote, {
@@ -120,7 +120,7 @@ class TestBlockquote(unittest.TestCase):
class TestListItem(unittest.TestCase):
def setUp(self):
- DOM.use(DOM.HTML5LIB)
+ DOM.use(DOM.STRING)
def test_render_debug(self):
self.assertEqual(DOM.render_debug(DOM.create_element(list_item, {
|
Change default engine to the new dependency-free one introduced in #77
The exporter now has an engine that doesn't have any dependencies. It should probably be the one activated by default, to make the whole package dependency-free unless another engine is configured. It also happens to be faster, and less memory-hungry.
This is a breaking change though, no matter how little difference there is with the output of the current default (html5lib + BeautifulSoup), so should be part of the 2.0.0 release.
As part of this change, it will also be necessary to move the html5lib / BS4 dependencies to a separate extra like for lxml (`pip install draftjs_exporter[html5lib]`), as well as update the documentation.
|
0.0
|
7acd6218f1a8460efd67965bb227dca16cf65bf0
|
[
"tests/test_html.py::TestHTML::test_init_dom_engine_default"
] |
[
"tests/test_composite_decorators.py::TestLinkify::test_render",
"tests/test_composite_decorators.py::TestLinkify::test_render_code_block",
"tests/test_composite_decorators.py::TestLinkify::test_render_www",
"tests/test_composite_decorators.py::TestHashtag::test_render",
"tests/test_composite_decorators.py::TestHashtag::test_render_code_block",
"tests/test_composite_decorators.py::TestBR::test_render",
"tests/test_composite_decorators.py::TestBR::test_render_code_block",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_conflicting_order_one",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_conflicting_order_two",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_empty",
"tests/test_composite_decorators.py::TestCompositeDecorators::test_render_decorators_single",
"tests/test_dom.py::TestDOM::test_append_child",
"tests/test_dom.py::TestDOM::test_camel_to_dash",
"tests/test_dom.py::TestDOM::test_create_element",
"tests/test_dom.py::TestDOM::test_create_element_empty",
"tests/test_dom.py::TestDOM::test_create_element_entity",
"tests/test_dom.py::TestDOM::test_create_element_nested",
"tests/test_dom.py::TestDOM::test_create_element_none",
"tests/test_dom.py::TestDOM::test_create_element_style_dict",
"tests/test_dom.py::TestDOM::test_create_element_style_str",
"tests/test_dom.py::TestDOM::test_parse_html",
"tests/test_dom.py::TestDOM::test_render_debug",
"tests/test_dom.py::TestDOM::test_use_custom",
"tests/test_dom.py::TestDOM::test_use_html5lib",
"tests/test_dom.py::TestDOM::test_use_invalid",
"tests/test_dom.py::TestDOM::test_use_lxml",
"tests/test_dom.py::TestDOM::test_use_string",
"tests/test_html.py::TestHTML::test_build_command_groups_empty",
"tests/test_html.py::TestHTML::test_build_command_groups_multiple",
"tests/test_html.py::TestHTML::test_build_commands_empty",
"tests/test_html.py::TestHTML::test_build_commands_multiple",
"tests/test_html.py::TestHTML::test_build_entity_commands_empty",
"tests/test_html.py::TestHTML::test_build_entity_commands_multiple",
"tests/test_html.py::TestHTML::test_build_entity_commands_single",
"tests/test_html.py::TestHTML::test_build_style_commands_empty",
"tests/test_html.py::TestHTML::test_build_style_commands_multiple",
"tests/test_html.py::TestHTML::test_build_style_commands_single",
"tests/test_html.py::TestHTML::test_init",
"tests/test_html.py::TestHTML::test_render",
"tests/test_html.py::TestHTML::test_render_block_exists",
"tests/test_html.py::TestHTML::test_render_empty",
"tests/test_html.py::TestHTML::test_render_none",
"tests/test_html.py::TestHTML::test_render_twice",
"tests/test_output.py::TestOutput::test_render_empty",
"tests/test_output.py::TestOutput::test_render_with_backtracking_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_big_content",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_false",
"tests/test_output.py::TestOutput::test_render_with_boolean_attribute_true",
"tests/test_output.py::TestOutput::test_render_with_default_block_map",
"tests/test_output.py::TestOutput::test_render_with_default_config",
"tests/test_output.py::TestOutput::test_render_with_default_style_map",
"tests/test_output.py::TestOutput::test_render_with_different_blocks",
"tests/test_output.py::TestOutput::test_render_with_element_options",
"tests/test_output.py::TestOutput::test_render_with_entities",
"tests/test_output.py::TestOutput::test_render_with_entities_crossing_raises",
"tests/test_output.py::TestOutput::test_render_with_entity",
"tests/test_output.py::TestOutput::test_render_with_entity_and_decorators",
"tests/test_output.py::TestOutput::test_render_with_immediate_jumping",
"tests/test_output.py::TestOutput::test_render_with_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_jumping_wrapping",
"tests/test_output.py::TestOutput::test_render_with_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_many_line_breaks",
"tests/test_output.py::TestOutput::test_render_with_multiple_decorators",
"tests/test_output.py::TestOutput::test_render_with_multiple_inline_styles",
"tests/test_output.py::TestOutput::test_render_with_no_zero_depth",
"tests/test_output.py::TestOutput::test_render_with_none_attribute",
"tests/test_output.py::TestOutput::test_render_with_none_component",
"tests/test_output.py::TestOutput::test_render_with_none_return_value",
"tests/test_output.py::TestOutput::test_render_with_number_attribute",
"tests/test_output.py::TestOutput::test_render_with_styles_in_entities",
"tests/test_output.py::TestOutput::test_render_with_unicode",
"tests/test_output.py::TestOutput::test_render_with_unidirectional_nested_wrapping",
"tests/test_output.py::TestOutput::test_render_with_unknown_attribute",
"tests/test_output.py::TestOutput::test_render_with_wrapping",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset",
"tests/test_output.py::TestOutput::test_render_with_wrapping_reset_block_components",
"tests/test_style_state.py::TestStyleState::test_apply_start_inline_style",
"tests/test_style_state.py::TestStyleState::test_apply_stop_inline_style",
"tests/test_style_state.py::TestStyleState::test_init",
"tests/test_style_state.py::TestStyleState::test_is_empty_default",
"tests/test_style_state.py::TestStyleState::test_is_empty_styled",
"tests/test_style_state.py::TestStyleState::test_render_styles_attributes",
"tests/test_style_state.py::TestStyleState::test_render_styles_component",
"tests/test_style_state.py::TestStyleState::test_render_styles_component_multiple",
"tests/test_style_state.py::TestStyleState::test_render_styles_component_multiple_invert",
"tests/test_style_state.py::TestStyleState::test_render_styles_styled",
"tests/test_style_state.py::TestStyleState::test_render_styles_styled_multiple",
"tests/test_style_state.py::TestStyleState::test_render_styles_unicode",
"tests/test_style_state.py::TestStyleState::test_render_styles_unstyled",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_component",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_component_wrapper",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_dismiss_content",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_element_content",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_no_block",
"tests/test_wrapper_state.py::TestWrapperState::test_element_for_simple_content",
"tests/test_wrapper_state.py::TestWrapperState::test_init",
"tests/test_wrapper_state.py::TestWrapperState::test_str",
"tests/test_wrapper_state.py::TestWrapperState::test_str_elts",
"tests/test_wrapper_state.py::TestBlockquote::test_render_debug",
"tests/test_wrapper_state.py::TestListItem::test_render_debug"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-10 01:14:40+00:00
|
mit
| 5,684 |
|
springload__typed_environment_configuration-7
|
diff --git a/typed_environment_configuration/typed_environment_configuration.py b/typed_environment_configuration/typed_environment_configuration.py
index 6429966..04e33ac 100644
--- a/typed_environment_configuration/typed_environment_configuration.py
+++ b/typed_environment_configuration/typed_environment_configuration.py
@@ -73,6 +73,10 @@ class StringVariable(Variable):
_value_type = typepy.type.String
_strict_level = 0
+class IntegerVariable(Variable):
+ _value_type = typepy.type.Integer
+ _strict_level = 1
+
class StringListVariable(Variable):
"""
|
springload/typed_environment_configuration
|
6891908e830fb5e5669174edc0386dae4e81395f
|
diff --git a/tests/test_typed_environment_configuration.py b/tests/test_typed_environment_configuration.py
index ad2babf..cb88eed 100644
--- a/tests/test_typed_environment_configuration.py
+++ b/tests/test_typed_environment_configuration.py
@@ -9,7 +9,11 @@ import os
from typed_environment_configuration import *
-_ENVVARS = [BoolVariable("DEBUG"), StringVariable("DEFAULT_STRING", default="")]
+_ENVVARS = [
+ BoolVariable("DEBUG"),
+ IntegerVariable("INT_VAR"),
+ StringVariable("DEFAULT_STRING", default=""),
+]
_PREFIXED_ENVVARS = [
StringVariable("PREFIXED_VERSION"),
@@ -18,12 +22,14 @@ _PREFIXED_ENVVARS = [
v = vars()
+
class TestTyped_environment_configuration(unittest.TestCase):
"""Tests for `typed_environment_configuration` package."""
def setUp(self):
"""Set up test fixtures, if any."""
os.environ["DEBUG"] = "True"
+ os.environ["INT_VAR"] = "10"
os.environ["PREFIXED_VERSION"] = "1.2.3"
FillVars(_ENVVARS, v)
@@ -36,6 +42,10 @@ class TestTyped_environment_configuration(unittest.TestCase):
"""Tests that setting boolean variable in env creates a python variable DEBUG=True"""
self.assertEqual(DEBUG, True)
+ def test_IntegerVariable(self):
+ """Tests that setting integer variable in env creates a python variable NUM_VAR=10"""
+ self.assertEqual(INT_VAR, 10)
+
def test_PrefixedVariable(self):
"""Tests a prefixed variable"""
self.assertEqual(VERSION, "1.2.3")
|
Add integer number variable class
* Typed Environment Configuration version: 0.1.3
* Python version: 3.8.3
* Operating System: alpine linux
### Description
There is no way to set integer variable from environment variables currently.
### What I Did
```
from os import getenv
CACHE_MIDDLEWARE_SECONDS = int(getenv("DJANGO_CACHE_MIDDLEWARE_SECONDS", default=0))
```
|
0.0
|
6891908e830fb5e5669174edc0386dae4e81395f
|
[
"tests/test_typed_environment_configuration.py::TestTyped_environment_configuration::test_BoolVariable",
"tests/test_typed_environment_configuration.py::TestTyped_environment_configuration::test_DefaultVariable",
"tests/test_typed_environment_configuration.py::TestTyped_environment_configuration::test_IntegerVariable",
"tests/test_typed_environment_configuration.py::TestTyped_environment_configuration::test_PrefixedVariable"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-07-21 02:40:46+00:00
|
mit
| 5,685 |
|
sprymix__csscompressor-8
|
diff --git a/csscompressor/__init__.py b/csscompressor/__init__.py
index e1ae16b..e34af04 100644
--- a/csscompressor/__init__.py
+++ b/csscompressor/__init__.py
@@ -113,6 +113,7 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
max_idx = len(css) - 1
append_idx = 0
sb = []
+ nest_term = None
for match in regexp.finditer(css):
name = match.group(1)
@@ -121,17 +122,29 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
term = match.group(2) if match.lastindex > 1 else None
if not term:
term = ')'
+ nest_term = '('
found_term = False
end_idx = match.end(0) - 1
+ nest_idx = end_idx if nest_term else 0
+ nested = False
while not found_term and (end_idx + 1) <= max_idx:
+ if nest_term:
+ nest_idx = css.find(nest_term, nest_idx + 1)
end_idx = css.find(term, end_idx + 1)
if end_idx > 0:
+ if nest_idx > 0 and nest_idx < end_idx and \
+ css[nest_idx - 1] != '\\':
+ nested = True
+
if css[end_idx - 1] != '\\':
- found_term = True
- if term != ')':
- end_idx = css.find(')', end_idx)
+ if nested:
+ nested = False
+ else:
+ found_term = True
+ if term != ')':
+ end_idx = css.find(')', end_idx)
else:
raise ValueError('malformed css')
@@ -139,7 +152,7 @@ def _preserve_call_tokens(css, regexp, preserved_tokens, remove_ws=False):
assert found_term
- token = css[start_idx:end_idx]
+ token = css[start_idx:end_idx].strip()
if remove_ws:
token = _ws_re.sub('', token)
|
sprymix/csscompressor
|
bec3e582cb5ab7182a0ca08ba381e491b94ed10c
|
diff --git a/csscompressor/tests/test_compress.py b/csscompressor/tests/test_compress.py
index 8d11e01..e65768a 100644
--- a/csscompressor/tests/test_compress.py
+++ b/csscompressor/tests/test_compress.py
@@ -52,3 +52,16 @@ class Tests(unittest.TestCase):
a {content: calc(10px-10%}
'''
self.assertRaises(ValueError, compress, input)
+
+ def test_nested_1(self):
+ input = '''
+ a { width: calc( (10vh - 100px) / 4 + 30px ) }
+ '''
+ output = compress(input)
+ assert output == "a{width:calc((10vh - 100px) / 4 + 30px)}"
+
+ def test_nested_2(self):
+ input = '''
+ a { width: calc( ((10vh - 100px) / 4 + 30px ) }
+ '''
+ self.assertRaises(ValueError, compress, input)
|
Major breakage when using some calc statements
I noticed csscompressor completely breaks some css rules with + in them. For example:
`>>> csscompressor.compress("calc( (10vh - 100px) + 30px )");
'calc( (10vh - 100px)+30px)'
> > > csscompressor.compress("calc( (10vh - 100px) / 4 + 30px )");
> > > 'calc( (10vh - 100px) / 4+30px)'
> > > `
The + and - operators must always be surrounded by whitespace, according to the [spec](https://developer.mozilla.org/en-US/docs/Web/CSS/calc), and when compressed, this rule is now broken and doesn't work in the browser.
Considering calc should be well-supported by just about every browser updated in the last 4 years, calc is super handy... but unfortunately breaks if you decide to compress with csscompress.
|
0.0
|
bec3e582cb5ab7182a0ca08ba381e491b94ed10c
|
[
"csscompressor/tests/test_compress.py::Tests::test_nested_1",
"csscompressor/tests/test_compress.py::Tests::test_nested_2"
] |
[
"csscompressor/tests/test_compress.py::Tests::test_compress_1",
"csscompressor/tests/test_compress.py::Tests::test_compress_2",
"csscompressor/tests/test_compress.py::Tests::test_linelen_1",
"csscompressor/tests/test_compress.py::Tests::test_linelen_2",
"csscompressor/tests/test_compress.py::Tests::test_linelen_3"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-11-25 03:33:22+00:00
|
bsd-3-clause
| 5,686 |
|
spulec__freezegun-353
|
diff --git a/README.rst b/README.rst
index a95059e..6997939 100644
--- a/README.rst
+++ b/README.rst
@@ -43,6 +43,23 @@ Decorator
def test_the_class(self):
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
+ # Or method decorator, might also pass frozen time object as kwarg
+
+ class TestUnitTestMethodDecorator(unittest.TestCase):
+ @freeze_time('2013-04-09')
+ def test_method_decorator_works_on_unittest(self):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+
+ @freeze_time('2013-04-09', as_kwarg='frozen_time')
+ def test_method_decorator_works_on_unittest(self, frozen_time):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+ self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.today())
+
+ @freeze_time('2013-04-09', as_kwarg='hello')
+ def test_method_decorator_works_on_unittest(self, **kwargs):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+ self.assertEqual(datetime.date(2013, 4, 9), kwargs.get('hello').time_to_freeze.today())
+
Context manager
~~~~~~~~~~~~~~~
diff --git a/freezegun/api.py b/freezegun/api.py
index 06450e1..738016d 100644
--- a/freezegun/api.py
+++ b/freezegun/api.py
@@ -513,8 +513,7 @@ class StepTickTimeFactory(object):
class _freeze_time(object):
-
- def __init__(self, time_to_freeze_str, tz_offset, ignore, tick, as_arg, auto_tick_seconds):
+ def __init__(self, time_to_freeze_str, tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds):
self.time_to_freeze = _parse_time_to_freeze(time_to_freeze_str)
self.tz_offset = _parse_tz_offset(tz_offset)
self.ignore = tuple(ignore)
@@ -523,6 +522,7 @@ class _freeze_time(object):
self.undo_changes = []
self.modules_at_start = set()
self.as_arg = as_arg
+ self.as_kwarg = as_kwarg
def __call__(self, func):
if inspect.isclass(func):
@@ -693,7 +693,7 @@ class _freeze_time(object):
continue
elif mod_name.startswith(self.ignore) or mod_name.endswith('.six.moves'):
continue
- elif (not hasattr(module, "__name__") or module.__name__ in ('datetime', 'time')):
+ elif not hasattr(module, "__name__") or module.__name__ in ('datetime', 'time'):
continue
for module_attribute in dir(module):
@@ -729,8 +729,13 @@ class _freeze_time(object):
def decorate_callable(self, func):
def wrapper(*args, **kwargs):
with self as time_factory:
- if self.as_arg:
+ if self.as_arg and self.as_kwarg:
+ assert False, "You can't specify both as_arg and as_kwarg at the same time. Pick one."
+ elif self.as_arg:
result = func(time_factory, *args, **kwargs)
+ elif self.as_kwarg:
+ kwargs[self.as_kwarg] = time_factory
+ result = func(*args, **kwargs)
else:
result = func(*args, **kwargs)
return result
@@ -743,7 +748,8 @@ class _freeze_time(object):
return wrapper
-def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_arg=False, auto_tick_seconds=0):
+def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_arg=False, as_kwarg='',
+ auto_tick_seconds=0):
acceptable_times = (type(None), _string_type, datetime.date, datetime.timedelta,
types.FunctionType, types.GeneratorType)
@@ -782,7 +788,7 @@ def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_ar
'gi',
])
- return _freeze_time(time_to_freeze, tz_offset, ignore, tick, as_arg, auto_tick_seconds)
+ return _freeze_time(time_to_freeze, tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds)
# Setup adapters for sqlite
|
spulec/freezegun
|
181f7ac7f909e561e26f5b293d2d40e82eb99f7a
|
diff --git a/tests/test_datetimes.py b/tests/test_datetimes.py
index b9b8685..994fb6c 100644
--- a/tests/test_datetimes.py
+++ b/tests/test_datetimes.py
@@ -485,6 +485,22 @@ def test_isinstance_without_active():
assert isinstance(today, datetime.date)
+class TestUnitTestMethodDecorator(unittest.TestCase):
+ @freeze_time('2013-04-09')
+ def test_method_decorator_works_on_unittest(self):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+
+ @freeze_time('2013-04-09', as_kwarg='frozen_time')
+ def test_method_decorator_works_on_unittest(self, frozen_time):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+ self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.today())
+
+ @freeze_time('2013-04-09', as_kwarg='hello')
+ def test_method_decorator_works_on_unittest(self, **kwargs):
+ self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
+ self.assertEqual(datetime.date(2013, 4, 9), kwargs.get('hello').time_to_freeze.today())
+
+
@freeze_time('2013-04-09')
class TestUnitTestClassDecorator(unittest.TestCase):
|
as_arg adds frozen_time argument to front of list of arguments
Currently the following code does not work with test classes (Django, etc).
https://github.com/spulec/freezegun/blob/master/freezegun/api.py#L669
That line does the following
```python
result = func(time_factory, *args, **kwargs)
```
That is incompatible with `self` being the first param to class methods and it behaves differently than most other decorators, which add their argument to the end, not the beginning. Here is an example that doesn't work
```python
from django.test import TestCase
from freezegun import freeze_time
class MyTest(TestCase):
@freeze_time('2016-11-01', as_arg=True)
def test_something_with_time(self, time_factory):
# freeze_time overrides self instead of time_factory
# self is now the time_factory variable
print(self) # <TimeFactory>
print(time_factory) # <MyTestCase>
```
It should do this instead.
```python
result = func(*args, time_factory, **kwargs)
```
This is a backwards incompatible change, but will allow the decorator to be used with class based tests. Would you be open to accepting a PR that makes this breaking change?
|
0.0
|
181f7ac7f909e561e26f5b293d2d40e82eb99f7a
|
[
"tests/test_datetimes.py::test_simple_api",
"tests/test_datetimes.py::test_tz_offset",
"tests/test_datetimes.py::test_timedelta_tz_offset",
"tests/test_datetimes.py::test_tz_offset_with_today",
"tests/test_datetimes.py::test_zero_tz_offset_with_time",
"tests/test_datetimes.py::test_tz_offset_with_time",
"tests/test_datetimes.py::test_time_with_microseconds",
"tests/test_datetimes.py::test_time_with_dst",
"tests/test_datetimes.py::test_manual_increment",
"tests/test_datetimes.py::test_manual_increment_seconds",
"tests/test_datetimes.py::test_move_to",
"tests/test_datetimes.py::test_bad_time_argument",
"tests/test_datetimes.py::test_time_gmtime",
"tests/test_datetimes.py::test_time_localtime",
"tests/test_datetimes.py::test_strftime",
"tests/test_datetimes.py::test_real_strftime_fall_through",
"tests/test_datetimes.py::test_date_object",
"tests/test_datetimes.py::test_old_date_object",
"tests/test_datetimes.py::test_invalid_type",
"tests/test_datetimes.py::test_datetime_object",
"tests/test_datetimes.py::test_function_object",
"tests/test_datetimes.py::test_lambda_object",
"tests/test_datetimes.py::test_generator_object",
"tests/test_datetimes.py::test_maya_datetimes",
"tests/test_datetimes.py::test_old_datetime_object",
"tests/test_datetimes.py::test_decorator",
"tests/test_datetimes.py::test_decorator_wrapped_attribute",
"tests/test_datetimes.py::Tester::test_the_class",
"tests/test_datetimes.py::Tester::test_still_the_same",
"tests/test_datetimes.py::Tester::test_class_name_preserved_by_decorator",
"tests/test_datetimes.py::Tester::test_class_decorator_ignores_nested_class",
"tests/test_datetimes.py::Tester::test_class_decorator_wraps_callable_object_py3",
"tests/test_datetimes.py::Tester::test_class_decorator_respects_staticmethod",
"tests/test_datetimes.py::test_nice_datetime",
"tests/test_datetimes.py::test_datetime_date_method",
"tests/test_datetimes.py::test_context_manager",
"tests/test_datetimes.py::test_nested_context_manager",
"tests/test_datetimes.py::test_nested_context_manager_with_tz_offsets",
"tests/test_datetimes.py::test_isinstance_with_active",
"tests/test_datetimes.py::test_isinstance_without_active",
"tests/test_datetimes.py::TestUnitTestMethodDecorator::test_method_decorator_works_on_unittest",
"tests/test_datetimes.py::TestUnitTestClassDecorator::test_class_decorator_works_on_unittest",
"tests/test_datetimes.py::TestUnitTestClassDecorator::test_class_name_preserved_by_decorator",
"tests/test_datetimes.py::TestUnitTestClassDecoratorWithNoSetUpOrTearDown::test_class_decorator_works_on_unittest",
"tests/test_datetimes.py::TestUnitTestClassDecoratorSubclass::test_class_decorator_works_on_unittest",
"tests/test_datetimes.py::TestUnitTestClassDecoratorSubclass::test_class_name_preserved_by_decorator",
"tests/test_datetimes.py::UnfrozenInheritedTests::test_time_is_not_frozen",
"tests/test_datetimes.py::FrozenInheritedTests::test_time_is_frozen",
"tests/test_datetimes.py::TestOldStyleClasses::test_direct_method",
"tests/test_datetimes.py::TestOldStyleClasses::test_inherited_method",
"tests/test_datetimes.py::test_min_and_max",
"tests/test_datetimes.py::test_freeze_with_timezone_aware_datetime_in_utc",
"tests/test_datetimes.py::test_freeze_with_timezone_aware_datetime_in_non_utc",
"tests/test_datetimes.py::test_time_with_nested",
"tests/test_datetimes.py::test_should_use_real_time",
"tests/test_datetimes.py::test_time_ns",
"tests/test_datetimes.py::test_compare_datetime_and_time_with_timezone",
"tests/test_datetimes.py::test_timestamp_with_tzoffset"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-28 07:24:36+00:00
|
apache-2.0
| 5,687 |
|
spulec__freezegun-525
|
diff --git a/freezegun/api.py b/freezegun/api.py
index f732ff8..2917fa1 100644
--- a/freezegun/api.py
+++ b/freezegun/api.py
@@ -544,7 +544,7 @@ class StepTickTimeFactory:
class _freeze_time:
- def __init__(self, time_to_freeze_str, tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds):
+ def __init__(self, time_to_freeze_str, tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds, real_asyncio):
self.time_to_freeze = _parse_time_to_freeze(time_to_freeze_str)
self.tz_offset = _parse_tz_offset(tz_offset)
self.ignore = tuple(ignore)
@@ -554,6 +554,7 @@ class _freeze_time:
self.modules_at_start = set()
self.as_arg = as_arg
self.as_kwarg = as_kwarg
+ self.real_asyncio = real_asyncio
def __call__(self, func):
if inspect.isclass(func):
@@ -727,20 +728,21 @@ class _freeze_time:
setattr(module, attribute_name, fake)
add_change((module, attribute_name, attribute_value))
- # To avoid breaking `asyncio.sleep()`, let asyncio event loops see real
- # monotonic time even though we've just frozen `time.monotonic()` which
- # is normally used there. If we didn't do this, `await asyncio.sleep()`
- # would be hanging forever breaking many tests that use `freeze_time`.
- #
- # Note that we cannot statically tell the class of asyncio event loops
- # because it is not officially documented and can actually be changed
- # at run time using `asyncio.set_event_loop_policy`. That's why we check
- # the type by creating a loop here and destroying it immediately.
- event_loop = asyncio.new_event_loop()
- event_loop.close()
- EventLoopClass = type(event_loop)
- add_change((EventLoopClass, "time", EventLoopClass.time))
- EventLoopClass.time = lambda self: real_monotonic()
+ if self.real_asyncio:
+ # To avoid breaking `asyncio.sleep()`, let asyncio event loops see real
+ # monotonic time even though we've just frozen `time.monotonic()` which
+ # is normally used there. If we didn't do this, `await asyncio.sleep()`
+ # would be hanging forever breaking many tests that use `freeze_time`.
+ #
+ # Note that we cannot statically tell the class of asyncio event loops
+ # because it is not officially documented and can actually be changed
+ # at run time using `asyncio.set_event_loop_policy`. That's why we check
+ # the type by creating a loop here and destroying it immediately.
+ event_loop = asyncio.new_event_loop()
+ event_loop.close()
+ EventLoopClass = type(event_loop)
+ add_change((EventLoopClass, "time", EventLoopClass.time))
+ EventLoopClass.time = lambda self: real_monotonic()
return freeze_factory
@@ -830,7 +832,7 @@ class _freeze_time:
def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_arg=False, as_kwarg='',
- auto_tick_seconds=0):
+ auto_tick_seconds=0, real_asyncio=False):
acceptable_times = (type(None), str, datetime.date, datetime.timedelta,
types.FunctionType, types.GeneratorType)
@@ -845,14 +847,14 @@ def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_ar
raise SystemError('Calling freeze_time with tick=True is only compatible with CPython')
if isinstance(time_to_freeze, types.FunctionType):
- return freeze_time(time_to_freeze(), tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds)
+ return freeze_time(time_to_freeze(), tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds, real_asyncio=real_asyncio)
if isinstance(time_to_freeze, types.GeneratorType):
- return freeze_time(next(time_to_freeze), tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds)
+ return freeze_time(next(time_to_freeze), tz_offset, ignore, tick, as_arg, as_kwarg, auto_tick_seconds, real_asyncio=real_asyncio)
if MayaDT is not None and isinstance(time_to_freeze, MayaDT):
return freeze_time(time_to_freeze.datetime(), tz_offset, ignore,
- tick, as_arg, as_kwarg, auto_tick_seconds)
+ tick, as_arg, as_kwarg, auto_tick_seconds, real_asyncio=real_asyncio)
if ignore is None:
ignore = []
@@ -868,6 +870,7 @@ def freeze_time(time_to_freeze=None, tz_offset=0, ignore=None, tick=False, as_ar
as_arg=as_arg,
as_kwarg=as_kwarg,
auto_tick_seconds=auto_tick_seconds,
+ real_asyncio=real_asyncio,
)
diff --git a/freezegun/api.pyi b/freezegun/api.pyi
index f0efbda..2ff9bdc 100644
--- a/freezegun/api.pyi
+++ b/freezegun/api.pyi
@@ -34,6 +34,7 @@ class _freeze_time:
as_arg: bool,
as_kwarg: str,
auto_tick_seconds: float,
+ real_asyncio: bool,
) -> None: ...
@overload
def __call__(self, func: type[_T]) -> type[_T]: ...
@@ -57,4 +58,5 @@ def freeze_time(
as_arg: bool | None = ...,
as_kwarg: str | None = ...,
auto_tick_seconds: float | None = ...,
+ real_asyncio: bool | None = ...
) -> _freeze_time: ...
|
spulec/freezegun
|
1af533984e118f5fe58d3264a52c904737df7d77
|
diff --git a/tests/test_asyncio.py b/tests/test_asyncio.py
index fe0d10c..6afc6e3 100644
--- a/tests/test_asyncio.py
+++ b/tests/test_asyncio.py
@@ -43,7 +43,7 @@ def test_asyncio_sleeping_not_affected_by_freeze_time():
async def coroutine():
# Sleeping with time frozen should sleep the expected duration.
before_sleep = time.time()
- with freeze_time('1970-01-02'):
+ with freeze_time('1970-01-02', real_asyncio=True):
await asyncio.sleep(0.05)
assert 0.02 <= time.time() - before_sleep < 0.3
@@ -76,5 +76,5 @@ def test_asyncio_to_call_later_with_frozen_time():
await asyncio.sleep(0.15)
assert timestamps == [86400]
- with freeze_time('1970-01-02'):
+ with freeze_time('1970-01-02', real_asyncio=True):
asyncio.run(coroutine())
diff --git a/tests/test_configure.py b/tests/test_configure.py
index 9dc0806..32fd2d4 100644
--- a/tests/test_configure.py
+++ b/tests/test_configure.py
@@ -31,6 +31,7 @@ def test_default_ignore_list_is_overridden():
as_arg=False,
as_kwarg='',
auto_tick_seconds=0,
+ real_asyncio=False,
)
def test_extend_default_ignore_list():
@@ -64,4 +65,5 @@ def test_extend_default_ignore_list():
as_arg=False,
as_kwarg='',
auto_tick_seconds=0,
+ real_asyncio=False,
)
|
[Discussion] about freezing asyncio
PR https://github.com/spulec/freezegun/pull/470 basically unfroze asyncio during freeze_time.
Although i understand the need for it (not breaking tests that perform real waits on real events), it breaks the main purpose of freeze_time: Asyncio is no-longer frozen even without tick and i can no longer trigger events that would happen in an asyncio future without waiting the full duration( for instance, a common pattern is to do asyncio.sleep(remaining_time)). This makes some tests that were instant have to wait for whole timeout instead with freezegun>=1.3.0.
I understand that both properties may be desirable, but, the first one should only work with tick=True (it is currently inconditional), and may still manipulate monotonic for asyncio (it is desirable to trigger futures events with freezegun).
A switch to get one behaviour or another may be needed; i guess there are even case where monotonic and time may need to be handled in a completely othogonal manner (as manipulating monotonic *will* always end up breaking a fundamental promise of the api: being monotonic).
So should i make a PR to make this behavior opt-in ? Add a new switch for asyncio ?
(Note, i have a longer take on this on a similar (but note quite the same) issue in time-machine: https://github.com/adamchainz/time-machine/pull/406)
|
0.0
|
1af533984e118f5fe58d3264a52c904737df7d77
|
[
"tests/test_asyncio.py::test_asyncio_sleeping_not_affected_by_freeze_time",
"tests/test_asyncio.py::test_asyncio_to_call_later_with_frozen_time",
"tests/test_configure.py::test_default_ignore_list_is_overridden",
"tests/test_configure.py::test_extend_default_ignore_list"
] |
[
"tests/test_asyncio.py::test_datetime_in_coroutine",
"tests/test_asyncio.py::test_freezing_time_in_coroutine",
"tests/test_asyncio.py::test_freezing_time_before_running_coroutine"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-07 20:08:14+00:00
|
apache-2.0
| 5,688 |
|
sputt__req-compile-28
|
diff --git a/pylintrc b/pylintrc
index d40030d..223e587 100644
--- a/pylintrc
+++ b/pylintrc
@@ -11,4 +11,4 @@ disable=
bad-continuation,
consider-using-f-string,
-ignored-modules=distutils.core
\ No newline at end of file
+ignored-modules=distutils.core
diff --git a/req_compile/filename.py b/req_compile/filename.py
index 6206248..48f77ef 100644
--- a/req_compile/filename.py
+++ b/req_compile/filename.py
@@ -59,5 +59,8 @@ def parse_source_filename(
version_parts = version_parts[:idx]
break
- version = utils.parse_version(".".join(version_parts))
+ try:
+ version = utils.parse_version(".".join(version_parts))
+ except Exception: # pylint: disable=broad-except
+ version = None
return pkg_name, version
diff --git a/req_compile/repos/repository.py b/req_compile/repos/repository.py
index ddcaad8..fff8374 100644
--- a/req_compile/repos/repository.py
+++ b/req_compile/repos/repository.py
@@ -103,11 +103,7 @@ def manylinux_tag_is_compatible_with_this_system(tag: str) -> bool:
else:
if hasattr(_manylinux, "manylinux_compatible"):
# pylint: disable=no-member
- result = _manylinux.manylinux_compatible(
- tag_major,
- tag_minor,
- tag_arch,
- )
+ result = _manylinux.manylinux_compatible(tag_major, tag_minor, tag_arch,)
if result is not None:
return bool(result)
else:
@@ -444,8 +440,11 @@ def _wheel_filename_to_candidate(source: Any, filename: str) -> Optional[Candida
build_tag = data_parts.pop(2)
name = data_parts[0]
abi = data_parts[3]
- # Convert old-style post-versions to new style so it will sort correctly
- version = parse_version(data_parts[1].replace("_", "-"))
+ try:
+ # Convert old-style post-versions to new style so it will sort correctly
+ version = parse_version(data_parts[1].replace("_", "-"))
+ except Exception: # pylint: disable=broad-except
+ return None
plats = data_parts[4].split(".")
requires_python = WheelVersionTags(tuple(data_parts[2].split(".")))
@@ -743,9 +742,7 @@ class Repository(metaclass=abc.ABCMeta):
): # pylint: disable=invalid-name
# type: (pkg_resources.Requirement, Candidate, Set[NormName]) -> CantUseReason
reason = check_usability(
- req,
- candidate,
- allow_prereleases=self.allow_prerelease,
+ req, candidate, allow_prereleases=self.allow_prerelease,
)
if reason is None or reason == CantUseReason.U_CAN_USE:
if (
diff --git a/requirements.in b/requirements.in
index 1dc9a4e..5106357 100644
--- a/requirements.in
+++ b/requirements.in
@@ -5,3 +5,4 @@ packaging
wheel
overrides
typing_extensions
+setuptools
diff --git a/requirements.txt b/requirements.txt
index b40ce3f..1592e5c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,44 +1,47 @@
-appdirs==1.4.4 # req-compile
-astroid==2.14.1 # pylint (<=2.16.0-dev0,>=2.14.1)
+--index-url https://pypi.org/simple
+
+appdirs==1.4.4 # requirements.in
+astroid==2.15.0 # pylint (<=2.17.0-dev0,>=2.15.0)
attrs==22.2.0 # pytest (>=19.2.0)
black==23.1.0 # test-requirements.in
certifi==2022.12.7 # requests (>=2017.4.17)
-charset-normalizer==3.0.1 # requests (<4,>=2)
+charset-normalizer==3.1.0 # requests (<4,>=2)
click==8.1.3 # black (>=8.0.0)
-colorama==0.4.6 # click, pylint (>=0.4.5), pytest
dill==0.3.6 # pylint (>=0.2)
-exceptiongroup==1.1.0 # pytest (>=1.0.0rc8)
+exceptiongroup==1.1.1 # pytest (>=1.0.0rc8)
idna==3.4 # requests (<4,>=2.5)
-importlib-metadata==6.0.0 # click, pluggy (>=0.12), pytest (>=0.12)
+importlib-metadata==6.1.0 # click, pluggy (>=0.12), pytest (>=0.12)
iniconfig==2.0.0 # pytest
isort==5.11.5 # pylint (<6,>=4.2.5), test-requirements.in
lazy-object-proxy==1.9.0 # astroid (>=1.4.0)
mccabe==0.7.0 # pylint (<0.8,>=0.6)
-mypy==1.0.0 # test-requirements.in
-mypy-extensions==1.0.0 # black (>=0.4.3), mypy (>=0.4.3)
-overrides==7.3.1 # req-compile
-packaging==23.0 # black (>=22.0), pytest, req-compile
-pathspec==0.11.0 # black (>=0.9.0)
-platformdirs==3.0.0 # black (>=2), pylint (>=2.2.0)
+mypy==1.1.1 # test-requirements.in
+mypy-extensions==1.0.0 # black (>=0.4.3), mypy (>=1.0.0)
+overrides==7.3.1 # requirements.in
+packaging==23.0 # black (>=22.0), pytest, requirements.in
+pathspec==0.11.1 # black (>=0.9.0)
+platformdirs==3.1.1 # black (>=2), pylint (>=2.2.0)
pluggy==1.0.0 # pytest (<2.0,>=0.12)
-pylint==2.16.1 # test-requirements.in
-pytest==7.2.1 # pytest-mock (>=5.0), test-requirements.in
+pylint==2.17.0 # test-requirements.in
+pytest==7.2.2 # pytest-mock (>=5.0), test-requirements.in
pytest-mock==3.10.0 # test-requirements.in
-requests==2.28.2 # req-compile, responses (<3.0,>=2.22.0)
-responses==0.22.0 # test-requirements.in
+PyYAML==6.0 # responses
+requests==2.28.2 # requirements.in, responses (<3.0,>=2.22.0)
+responses==0.23.1 # test-requirements.in
+setuptools==67.6.0 # requirements.in
six==1.16.0 # test-requirements.in
-toml==0.10.2 # req-compile, responses
+toml==0.10.2 # requirements.in
tomli==2.0.1 # black (>=1.1.0), mypy (>=1.1.0), pylint (>=1.1.0), pytest (>=1.0.0)
tomlkit==0.11.6 # pylint (>=0.10.1)
typed-ast==1.5.4 # astroid (<2.0,>=1.4.0), black (>=1.4.2), mypy (<2,>=1.4.0)
-types-appdirs==1.4.3.1 # test-requirements.in
-types-docutils==0.19.1.3 # types-setuptools
-types-requests==2.28.11.12 # test-requirements.in
-types-setuptools==67.2.0.0 # test-requirements.in
-types-toml==0.10.8.3 # responses, test-requirements.in
-types-urllib3==1.26.25.5 # types-requests (<1.27)
-typing_extensions==4.4.0 # astroid (>=4.0.0), black (>=3.10.0.0), importlib-metadata (>=3.6.4), mypy (>=3.10), platformdirs (>=4.4), pylint (>=3.10.0), req-compile, responses
-urllib3==1.26.14 # requests (<1.27,>=1.21.1), responses (>=1.25.10)
-wheel==0.38.4 # req-compile
-wrapt==1.14.1 # astroid (<2,>=1.11)
-zipp==3.12.1 # importlib-metadata (>=0.5)
+types-appdirs==1.4.3.5 # test-requirements.in
+types-PyYAML==6.0.12.8 # responses
+types-requests==2.28.11.15 # test-requirements.in
+types-setuptools==67.6.0.5 # test-requirements.in
+types-toml==0.10.8.5 # test-requirements.in
+types-urllib3==1.26.25.8 # types-requests (<1.27)
+typing_extensions==4.5.0 # astroid (>=4.0.0), black (>=3.10.0.0), importlib-metadata (>=3.6.4), mypy (>=3.10), platformdirs (>=4.4), pylint (>=3.10.0), requirements.in, responses
+urllib3==1.26.15 # requests (<1.27,>=1.21.1), responses (>=1.25.10)
+wheel==0.40.0 # requirements.in
+wrapt==1.15.0 # astroid (<2,>=1.11)
+zipp==3.15.0 # importlib-metadata (>=0.5)
diff --git a/setup.py b/setup.py
index d4d451e..bbdb188 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name="req-compile",
- version="1.0.0pre4",
+ version="1.0.0pre5",
author="Spencer Putt",
author_email="[email protected]",
description="Python requirements compiler",
|
sputt/req-compile
|
f11d522da614b9c1744afa781e0beb61f14336a6
|
diff --git a/tests/test_filename.py b/tests/test_filename.py
new file mode 100644
index 0000000..6497094
--- /dev/null
+++ b/tests/test_filename.py
@@ -0,0 +1,36 @@
+import pkg_resources
+import pytest
+
+
+import req_compile.filename
+
+
[email protected](
+ "filename,result_name,result_version",
+ [
+ ["post-2.3.1-2.tar.gz", "post", "2.3.1-2"],
+ ["pytest-ui-0.3b0.linux-x86_64.tar.gz", "pytest-ui", "0.3beta0"],
+ ["backports-thing-1.0.1.tar.gz", "backports-thing", "1.0.1"],
+ ["backports-thing-1.0.1.tar.gz", "backports-thing", "1.0.1"],
+ ["project-v1.0.tar.gz", "project", "1.0"],
+ ["pyvmomi-5.5.0.2014.1.1.tar.gz", "pyvmomi", "5.5.0.2014.1.1"],
+ ["pyvmomi-5.5.0-2014.1.1.tar.gz", "pyvmomi", None],
+ ["python-project-3-0.0.1.tar.gz", "python-project-3", "0.0.1"],
+ ["python-project-v2-0.1.1.tar.gz", "python-project-v2", "0.1.1"],
+ ["divisor-1.0.0s-1.0.0.zip", "divisor-1.0.0s", "1.0.0"],
+ [
+ "django-1.6-fine-uploader-0.2.0.3.tar.gz",
+ "django-1.6-fine-uploader",
+ "0.2.0.3",
+ ],
+ ["selenium-2.0-dev-9429.tar.gz", "selenium", "2.0-dev-9429"],
+ ["django-ajax-forms_0.3.1.tar.gz", "django-ajax-forms", "0.3.1"],
+ ["lskdjfknw.sdi.siqwenr", "lskdjfknw.sdi.siqwenr", None],
+ ],
+)
+def test_parse_source_filename(filename, result_name, result_version):
+ result = req_compile.filename.parse_source_filename(filename)
+ assert result == (
+ result_name,
+ pkg_resources.parse_version(result_version) if result_version else None,
+ )
diff --git a/tests/test_integration.py b/tests/test_integration.py
index bd3b007..841ebd7 100644
--- a/tests/test_integration.py
+++ b/tests/test_integration.py
@@ -39,7 +39,16 @@ def test_no_candidates(tmp_path):
def test_compile_req_compile(tmp_path):
"""Test compiling this project from source."""
result = subprocess.run(
- [sys.executable, "-m", "req_compile", ".", "--wheel-dir", str(tmp_path)],
+ [
+ sys.executable,
+ "-m",
+ "req_compile",
+ "-i",
+ "https://pypi.org/simple",
+ ".",
+ "--wheel-dir",
+ str(tmp_path),
+ ],
encoding="utf-8",
capture_output=True,
cwd=ROOT_DIR,
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
index 5252c9d..3411b5a 100644
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -85,33 +85,6 @@ def test_pylint_python(metadata_provider):
assert set(info.requires()) == set(pkg_resources.parse_requirements(expected_reqs))
[email protected](
- "filename,result_name,result_version",
- [
- ["post-2.3.1-2.tar.gz", "post", "2.3.1-2"],
- ["pytest-ui-0.3b0.linux-x86_64.tar.gz", "pytest-ui", "0.3beta0"],
- ["backports-thing-1.0.1.tar.gz", "backports-thing", "1.0.1"],
- ["backports-thing-1.0.1.tar.gz", "backports-thing", "1.0.1"],
- ["project-v1.0.tar.gz", "project", "1.0"],
- ["pyvmomi-5.5.0.2014.1.1.tar.gz", "pyvmomi", "5.5.0.2014.1.1"],
- ["pyvmomi-5.5.0-2014.1.1.tar.gz", "pyvmomi", "5.5.0-2014.1.1"],
- ["python-project-3-0.0.1.tar.gz", "python-project-3", "0.0.1"],
- ["python-project-v2-0.1.1.tar.gz", "python-project-v2", "0.1.1"],
- ["divisor-1.0.0s-1.0.0.zip", "divisor-1.0.0s", "1.0.0"],
- [
- "django-1.6-fine-uploader-0.2.0.3.tar.gz",
- "django-1.6-fine-uploader",
- "0.2.0.3",
- ],
- ["selenium-2.0-dev-9429.tar.gz", "selenium", "2.0-dev-9429"],
- ["django-ajax-forms_0.3.1.tar.gz", "django-ajax-forms", "0.3.1"],
- ],
-)
-def test_parse_source_filename(filename, result_name, result_version):
- result = req_compile.filename.parse_source_filename(filename)
- assert result == (result_name, pkg_resources.parse_version(result_version))
-
-
def test_compound(mock_targz):
"""Test one tar after another directly that have failed in the passed"""
archive = mock_targz("et_xmlfile-1.0.1")
diff --git a/tests/test_repositories.py b/tests/test_repositories.py
index e6700c5..fd5d30c 100644
--- a/tests/test_repositories.py
+++ b/tests/test_repositories.py
@@ -30,7 +30,11 @@ def test_version_compatible(mock_py_version, sys_py_version, py_requires):
@pytest.mark.parametrize(
- "sys_py_version, py_requires", [("3.6.3", ("py2",)), ("2.7.16", ("py3",)),],
+ "sys_py_version, py_requires",
+ [
+ ("3.6.3", ("py2",)),
+ ("2.7.16", ("py3",)),
+ ],
)
def test_version_incompatible(mock_py_version, sys_py_version, py_requires):
mock_py_version(sys_py_version)
@@ -61,9 +65,6 @@ def test_sort_non_semver():
"2013b0",
"2012rc0",
"2012b0",
- "2009r",
- "2013d",
- "2011k",
)
candidates = []
for ver in candidate_vers:
@@ -83,7 +84,8 @@ def test_sort_non_semver():
def test_sort_specific_platforms(mock_py_version, mocker):
mock_py_version("3.7.4")
mocker.patch(
- "req_compile.repos.repository.PLATFORM_TAGS", ("this_platform",),
+ "req_compile.repos.repository.PLATFORM_TAGS",
+ ("this_platform",),
)
candidate_wheels = (
"sounddevice-0.4.1-cp32.cp33.cp34.cp35.cp36.cp37.cp38.cp39.pp32.pp33.pp34.pp35.pp36.pp37.py3-None-this_platform.whl",
@@ -102,7 +104,8 @@ def test_sort_specific_platforms(mock_py_version, mocker):
def test_sort_wheels_with_any(mock_py_version, mocker):
mock_py_version("3.7.4")
mocker.patch(
- "req_compile.repos.repository.PLATFORM_TAGS", ("this_platform",),
+ "req_compile.repos.repository.PLATFORM_TAGS",
+ ("this_platform",),
)
candidate_wheels = (
"pyenchant-3.2.1-py3-None-this_platform.and_another.whl",
|
Invalid Versions
A single invalid version listed on a candidates html page causes compilation to fail. These candidates should be ignored or otherwise flagged and compilation should continue.For example, with setuptools 66+, joblib on pypi has a version which is no longer valid:
pkg_resources.extern.packaging.version.InvalidVersion: Invalid version: '0.3.2d.dev'
|
0.0
|
f11d522da614b9c1744afa781e0beb61f14336a6
|
[
"tests/test_filename.py::test_parse_source_filename[pyvmomi-5.5.0-2014.1.1.tar.gz-pyvmomi-None]"
] |
[
"tests/test_filename.py::test_parse_source_filename[post-2.3.1-2.tar.gz-post-2.3.1-2]",
"tests/test_filename.py::test_parse_source_filename[pytest-ui-0.3b0.linux-x86_64.tar.gz-pytest-ui-0.3beta0]",
"tests/test_filename.py::test_parse_source_filename[backports-thing-1.0.1.tar.gz-backports-thing-1.0.10]",
"tests/test_filename.py::test_parse_source_filename[backports-thing-1.0.1.tar.gz-backports-thing-1.0.11]",
"tests/test_filename.py::test_parse_source_filename[project-v1.0.tar.gz-project-1.0]",
"tests/test_filename.py::test_parse_source_filename[pyvmomi-5.5.0.2014.1.1.tar.gz-pyvmomi-5.5.0.2014.1.1]",
"tests/test_filename.py::test_parse_source_filename[python-project-3-0.0.1.tar.gz-python-project-3-0.0.1]",
"tests/test_filename.py::test_parse_source_filename[python-project-v2-0.1.1.tar.gz-python-project-v2-0.1.1]",
"tests/test_filename.py::test_parse_source_filename[divisor-1.0.0s-1.0.0.zip-divisor-1.0.0s-1.0.0]",
"tests/test_filename.py::test_parse_source_filename[django-1.6-fine-uploader-0.2.0.3.tar.gz-django-1.6-fine-uploader-0.2.0.3]",
"tests/test_filename.py::test_parse_source_filename[selenium-2.0-dev-9429.tar.gz-selenium-2.0-dev-9429]",
"tests/test_filename.py::test_parse_source_filename[django-ajax-forms_0.3.1.tar.gz-django-ajax-forms-0.3.1]",
"tests/test_filename.py::test_parse_source_filename[lskdjfknw.sdi.siqwenr-lskdjfknw.sdi.siqwenr-None]",
"tests/test_integration.py::test_source_candidates",
"tests/test_integration.py::test_no_candidates",
"tests/test_integration.py::test_compile_req_compile",
"tests/test_metadata.py::test_a_with_no_extra",
"tests/test_metadata.py::test_parse_flat_metadata_extra_space",
"tests/test_metadata.py::test_parse_flat_metadata_two_names",
"tests/test_metadata.py::test_parse_flat_metadata_bizarre_extra",
"tests/test_metadata.py::test_a_with_extra",
"tests/test_metadata.py::test_a_with_wrong_extra",
"tests/test_metadata.py::test_pylint_python",
"tests/test_metadata.py::test_compound",
"tests/test_metadata.py::test_source_dist[svn-0.3.46-svn-0.3.46-reqs0-mock_targz]",
"tests/test_metadata.py::test_source_dist[svn-0.3.46-svn-0.3.46-reqs0-mock_zip]",
"tests/test_metadata.py::test_source_dist[svn-0.3.46-svn-0.3.46-reqs0-mock_fs]",
"tests/test_metadata.py::test_source_dist[dir-exists-1.0-dir-exists-1.0-reqs1-mock_targz]",
"tests/test_metadata.py::test_source_dist[dir-exists-1.0-dir-exists-1.0-reqs1-mock_zip]",
"tests/test_metadata.py::test_source_dist[dir-exists-1.0-dir-exists-1.0-reqs1-mock_fs]",
"tests/test_metadata.py::test_source_dist[invalid-extra-2.1-invalid-extra-2.1-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[invalid-extra-2.1-invalid-extra-2.1-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[invalid-extra-2.1-invalid-extra-2.1-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[scapy-2.4.0-scapy-2.4.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[scapy-2.4.0-scapy-2.4.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[scapy-2.4.0-scapy-2.4.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[dill-0.3.0-dill-0.3.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[dill-0.3.0-dill-0.3.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[dill-0.3.0-dill-0.3.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[path-exists-2.0-path-exists-2.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[path-exists-2.0-path-exists-2.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[path-exists-2.0-path-exists-2.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[post-3.2.1-1-post-3.2.1-1-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[post-3.2.1-1-post-3.2.1-1-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[post-3.2.1-1-post-3.2.1-1-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[comtypes-1.1.7-comtypes-1.1.7-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[comtypes-1.1.7-comtypes-1.1.7-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[comtypes-1.1.7-comtypes-1.1.7-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[pkg-with-cython-1.0-pkg-with-cython-1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[pkg-with-cython-1.0-pkg-with-cython-1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[pkg-with-cython-1.0-pkg-with-cython-1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[billiard-3.6.0.0-billiard-3.6.0.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[billiard-3.6.0.0-billiard-3.6.0.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[billiard-3.6.0.0-billiard-3.6.0.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[ptl-2015.11.4-ptl-2015.11.4-reqs10-mock_targz]",
"tests/test_metadata.py::test_source_dist[ptl-2015.11.4-ptl-2015.11.4-reqs10-mock_zip]",
"tests/test_metadata.py::test_source_dist[ptl-2015.11.4-ptl-2015.11.4-reqs10-mock_fs]",
"tests/test_metadata.py::test_source_dist[reloader-1.0-reloader-1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[reloader-1.0-reloader-1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[reloader-1.0-reloader-1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[PyYAML-5.1-PyYAML-5.1-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[PyYAML-5.1-PyYAML-5.1-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[PyYAML-5.1-PyYAML-5.1-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[ed-1.4-ed-None-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[ed-1.4-ed-None-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[ed-1.4-ed-None-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[pyreadline-2.1-pyreadline-2.1-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[pyreadline-2.1-pyreadline-2.1-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[pyreadline-2.1-pyreadline-2.1-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[termcolor-1.1.0-termcolor-1.1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[termcolor-1.1.0-termcolor-1.1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[termcolor-1.1.0-termcolor-1.1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[wuc-0.5-wuc-0.5-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[wuc-0.5-wuc-0.5-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[wuc-0.5-wuc-0.5-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[pint-0.6-Pint-0.6-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[pint-0.6-Pint-0.6-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[pint-0.6-Pint-0.6-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[tar-utf8-1.1.0-tar-utf8-1.1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[tar-utf8-1.1.0-tar-utf8-1.1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[tar-utf8-1.1.0-tar-utf8-1.1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[tar-1.0.0-tar-1.0.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[tar-1.0.0-tar-1.0.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[tar-1.0.0-tar-1.0.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[et_xmlfile-1.0.1-et_xmlfile-1.0.1-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[et_xmlfile-1.0.1-et_xmlfile-1.0.1-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[et_xmlfile-1.0.1-et_xmlfile-1.0.1-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[dot-slash-dir-1.0-dot-slash-dir-1.0-reqs21-mock_targz]",
"tests/test_metadata.py::test_source_dist[dot-slash-dir-1.0-dot-slash-dir-1.0-reqs21-mock_zip]",
"tests/test_metadata.py::test_source_dist[dot-slash-dir-1.0-dot-slash-dir-1.0-reqs21-mock_fs]",
"tests/test_metadata.py::test_source_dist[setup-cfg-0.2.0-setup-cfg-0.2.0-reqs22-mock_targz]",
"tests/test_metadata.py::test_source_dist[setup-cfg-0.2.0-setup-cfg-0.2.0-reqs22-mock_zip]",
"tests/test_metadata.py::test_source_dist[setup-cfg-0.2.0-setup-cfg-0.2.0-reqs22-mock_fs]",
"tests/test_metadata.py::test_source_dist[cython-check-1.0-cython-check-1.0-reqs23-mock_targz]",
"tests/test_metadata.py::test_source_dist[cython-check-1.0-cython-check-1.0-reqs23-mock_zip]",
"tests/test_metadata.py::test_source_dist[cython-check-1.0-cython-check-1.0-reqs23-mock_fs]",
"tests/test_metadata.py::test_source_dist[ez-setup-test-1.0-ez-setup-test-1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[ez-setup-test-1.0-ez-setup-test-1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[ez-setup-test-1.0-ez-setup-test-1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[gdal-3.0.1-GDAL-3.0.1-reqs25-mock_targz]",
"tests/test_metadata.py::test_source_dist[gdal-3.0.1-GDAL-3.0.1-reqs25-mock_zip]",
"tests/test_metadata.py::test_source_dist[gdal-3.0.1-GDAL-3.0.1-reqs25-mock_fs]",
"tests/test_metadata.py::test_source_dist[pymc-2.3.6-pymc-2.3.6-reqs26-mock_targz]",
"tests/test_metadata.py::test_source_dist[pymc-2.3.6-pymc-2.3.6-reqs26-mock_zip]",
"tests/test_metadata.py::test_source_dist[pymc-2.3.6-pymc-2.3.6-reqs26-mock_fs]",
"tests/test_metadata.py::test_source_dist[file-iter-7.2.0-file-iter-7.2.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[file-iter-7.2.0-file-iter-7.2.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[file-iter-7.2.0-file-iter-7.2.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[psutil-5.6.2-psutil-5.6.2-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[psutil-5.6.2-psutil-5.6.2-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[psutil-5.6.2-psutil-5.6.2-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[pt-2.0.0-pt-2.0.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[pt-2.0.0-pt-2.0.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[pt-2.0.0-pt-2.0.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[dir-changer-0.1.1-dir-changer-0.1.1-reqs30-mock_targz]",
"tests/test_metadata.py::test_source_dist[dir-changer-0.1.1-dir-changer-0.1.1-reqs30-mock_zip]",
"tests/test_metadata.py::test_source_dist[dir-changer-0.1.1-dir-changer-0.1.1-reqs30-mock_fs]",
"tests/test_metadata.py::test_source_dist[file-input-1.0-file-input-1.0-None-mock_targz]",
"tests/test_metadata.py::test_source_dist[file-input-1.0-file-input-1.0-None-mock_zip]",
"tests/test_metadata.py::test_source_dist[file-input-1.0-file-input-1.0-None-mock_fs]",
"tests/test_metadata.py::test_source_dist[capital-s-1.0-capital-s-1.0-reqs32-mock_targz]",
"tests/test_metadata.py::test_source_dist[capital-s-1.0-capital-s-1.0-reqs32-mock_zip]",
"tests/test_metadata.py::test_source_dist[capital-s-1.0-capital-s-1.0-reqs32-mock_fs]",
"tests/test_metadata.py::test_source_dist[dirsep-1.0-dirsep-1.0-reqs33-mock_targz]",
"tests/test_metadata.py::test_source_dist[dirsep-1.0-dirsep-1.0-reqs33-mock_zip]",
"tests/test_metadata.py::test_source_dist[dirsep-1.0-dirsep-1.0-reqs33-mock_fs]",
"tests/test_metadata.py::test_source_dist[newline-req-1.0-newline-req-1.0-reqs34-mock_targz]",
"tests/test_metadata.py::test_source_dist[newline-req-1.0-newline-req-1.0-reqs34-mock_zip]",
"tests/test_metadata.py::test_source_dist[newline-req-1.0-newline-req-1.0-reqs34-mock_fs]",
"tests/test_metadata.py::test_source_dist[version-writer-1.2-version-writer-1.2-reqs35-mock_targz]",
"tests/test_metadata.py::test_source_dist[version-writer-1.2-version-writer-1.2-reqs35-mock_zip]",
"tests/test_metadata.py::test_source_dist[version-writer-1.2-version-writer-1.2-reqs35-mock_fs]",
"tests/test_metadata.py::test_source_dist[tinyrpc-1.0.4-tinyrpc-1.0.4-reqs36-mock_targz]",
"tests/test_metadata.py::test_source_dist[tinyrpc-1.0.4-tinyrpc-1.0.4-reqs36-mock_zip]",
"tests/test_metadata.py::test_source_dist[tinyrpc-1.0.4-tinyrpc-1.0.4-reqs36-mock_fs]",
"tests/test_metadata.py::test_source_dist[spec-loading-1.0-spec-loading-1.0-reqs37-mock_targz]",
"tests/test_metadata.py::test_source_dist[spec-loading-1.0-spec-loading-1.0-reqs37-mock_zip]",
"tests/test_metadata.py::test_source_dist[spec-loading-1.0-spec-loading-1.0-reqs37-mock_fs]",
"tests/test_metadata.py::test_relative_import",
"tests/test_metadata.py::test_extern_import",
"tests/test_metadata.py::test_self_source",
"tests/test_repositories.py::test_version_compatible[3.5.0-None]",
"tests/test_repositories.py::test_version_compatible[2.6.10-None]",
"tests/test_repositories.py::test_version_compatible[3.6.3-py_requires2]",
"tests/test_repositories.py::test_version_compatible[3.6.3-py_requires3]",
"tests/test_repositories.py::test_version_compatible[3.6.3-py_requires4]",
"tests/test_repositories.py::test_version_incompatible[3.6.3-py_requires0]",
"tests/test_repositories.py::test_version_incompatible[2.7.16-py_requires1]",
"tests/test_repositories.py::test_version_str[py_requires0-py2]",
"tests/test_repositories.py::test_version_str[py_requires1-py2.py3]",
"tests/test_repositories.py::test_version_str[py_requires2-py2.py3]",
"tests/test_repositories.py::test_version_str[py_requires3-any]",
"tests/test_repositories.py::test_version_str[None-any]",
"tests/test_repositories.py::test_sort_non_semver",
"tests/test_repositories.py::test_sort_specific_platforms",
"tests/test_repositories.py::test_sort_wheels_with_any",
"tests/test_repositories.py::test_sort_manylinux",
"tests/test_repositories.py::test_impl_major_minor[py3-results0]",
"tests/test_repositories.py::test_impl_major_minor[cp37-results1]",
"tests/test_repositories.py::test_impl_major_minor[cp3x-results2]",
"tests/test_repositories.py::test_impl_major_minor[-results3]",
"tests/test_repositories.py::test_py_version_score"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-18 18:21:52+00:00
|
mit
| 5,689 |
|
spyder-ide__pyls-spyder-10
|
diff --git a/pyls_spyder/plugin.py b/pyls_spyder/plugin.py
index e185f03..e01c1c9 100644
--- a/pyls_spyder/plugin.py
+++ b/pyls_spyder/plugin.py
@@ -17,8 +17,35 @@ from pyls import hookimpl
from pyls.config.config import Config
from pyls.workspace import Workspace, Document
-CELL_REGEX = re.compile(r'^[\t ]*# (%%+)(.*)?$')
-BLOCK_REGEX = re.compile(r'^[\t ]*# (--+)(.*)?$')
+# Local imports
+from pyls_spyder.utils import RegexEvaluator
+
+# Code cell regular expressions
+# 1. Cells declared with percentages, i.e., # %% Cell
+CELL_PERCENTAGE, CELL_PERCENTAGE_REGEX = (
+ 'CELL_PERCENTAGE', re.compile(r'^[\t ]*# ?(%%+)(.*)?$'))
+# 2. Cells declared with "<codecell>", i.e., # <codecell>
+CELL_CODECELL, CELL_CODECELL_REGEX = (
+ 'CELL_CODECELL', re.compile(r'^[\t ]*# ?(<codecell>)(.*)?$'))
+# 3. Cells declared with "In[.*], i.e., # In[23]"
+CELL_IN, CELL_IN_REGEX = (
+ 'CELL_IN', re.compile(r'^[\t ]*# ?(In\[)([^\]\r\n]*)?\]?$'))
+
+CELL_REGEX = RegexEvaluator({
+ CELL_PERCENTAGE: CELL_PERCENTAGE_REGEX,
+ CELL_CODECELL: CELL_CODECELL_REGEX,
+ CELL_IN: CELL_IN_REGEX
+})
+
+# Block comment regular expressions
+# 1. Block comments declared with 4 dashes, i.e., # ---- Block comment
+BLOCK_DASH = (
+ 'BLOCK_DASH', re.compile(r'^[\t ]*# ?-{4}([^-\n\r]?.*)?$'))
+# 2. Block comments declared with 3 consecutive hashes, i.e., #### Comment
+BLOCK_HASH = (
+ 'BLOCK_HASH', re.compile(r'^[\t ]*##{3}([^\#\n\r]?.*)?$'))
+
+BLOCK_REGEX = RegexEvaluator(dict([BLOCK_DASH, BLOCK_HASH]))
def peek_symbol(list: List) -> Tuple:
@@ -70,8 +97,8 @@ def pyls_document_symbols(config: Config,
unnamed_block = 1
for line_num, line in enumerate(lines):
- cell_match = CELL_REGEX.match(line)
- block_match = BLOCK_REGEX.match(line)
+ cell_rule, cell_match = CELL_REGEX.match(line)
+ block_rule, block_match = BLOCK_REGEX.match(line)
if cell_match is not None:
percentages = cell_match.group(1)
@@ -81,7 +108,7 @@ def pyls_document_symbols(config: Config,
cell_name = 'Unnamed cell {0}'.format(unnamed_cell)
unnamed_cell += 1
- if not group_cells:
+ if not group_cells or cell_rule != CELL_PERCENTAGE:
cells.append(create_symbol(
cell_name, document, line_num, line_num + 1))
else:
@@ -99,7 +126,7 @@ def pyls_document_symbols(config: Config,
current_name) = peek_symbol(cell_stack)
cell_stack.insert(0, (line_num, cell_level, cell_name))
elif block_match is not None and enable_block_comments:
- block_name = block_match.group(2).strip()
+ block_name = block_match.group(1).strip()
if block_name == '':
block_name = 'Unnamed comment {0}'.format(unnamed_block)
unnamed_block += 1
diff --git a/pyls_spyder/utils.py b/pyls_spyder/utils.py
new file mode 100644
index 0000000..94aef27
--- /dev/null
+++ b/pyls_spyder/utils.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+# ----------------------------------------------------------------------------
+# Copyright (c) Spyder Project Contributors
+#
+# Licensed under the terms of the MIT License
+# (see LICENSE.txt for details)
+# ----------------------------------------------------------------------------
+
+"""pyls-spyder misc utillites."""
+
+# Standard library imports
+from typing import Tuple, Dict
+
+
+class RegexEvaluator:
+ """Wrapper class around multiple regular expressions."""
+
+ def __init__(self, regex_map: Dict):
+ self.regexes = regex_map
+
+ def match(self, string: str) -> Tuple:
+ """
+ Match a string `string` against a set of regular expressions.
+
+ The regular expressions are applied in a short-circuit fashion.
+
+ Parameters
+ ----------
+ string: str
+ Input string to match regexes against.
+
+ Returns
+ -------
+ output: Tuple[Optional[str], Optional[re.Match]]
+ A tuple containing the regex identifier that first matched the
+ input, alongside the corresponding regex match object. If no regex
+ did matched the input, then a tuple containing `None` is returned.
+ """
+ re_match = None
+ re_rule = None
+ for regex_name in self.regexes:
+ regex = self.regexes[regex_name]
+ re_match = regex.match(string)
+ if re_match is not None:
+ re_rule = regex_name
+ break
+ return re_rule, re_match
|
spyder-ide/pyls-spyder
|
117a52c8986659bcb0bc31707826ee1e08cb0bb4
|
diff --git a/.github/workflows/linux-tests.yml b/.github/workflows/linux-tests.yml
index e497b22..8e79031 100644
--- a/.github/workflows/linux-tests.yml
+++ b/.github/workflows/linux-tests.yml
@@ -22,7 +22,7 @@ jobs:
- name: Checkout branch/PR
uses: actions/checkout@v1
- name: Install Conda
- uses: goanpeca/setup-miniconda@v1
+ uses: conda-incubator/setup-miniconda@v2
with:
activate-environment: test
auto-update-conda: true
diff --git a/pyls_spyder/tests/test_plugin.py b/pyls_spyder/tests/test_plugin.py
index 8582c49..8a8adc1 100644
--- a/pyls_spyder/tests/test_plugin.py
+++ b/pyls_spyder/tests/test_plugin.py
@@ -8,9 +8,6 @@
"""pyls-spyder plugin tests."""
-# Standard library imports
-import os
-
# PyLS imports
from pyls import uris
from pyls.workspace import Document
@@ -26,12 +23,14 @@ from pyls_spyder.plugin import pyls_document_symbols
DOC_URI = uris.from_fs_path(__file__)
DOC = """
# %%
-# -- Imports
+# ---- Imports
import os
import sys
-# ------
+# <codecell> Other cell
+# ----
def a():
+ #### Block comment on a
# %%% Cell inside a
for i in range(0, 10):
# %%%% Cell
@@ -39,11 +38,14 @@ def a():
# %%%
def b():
- # ----- Pass inside b
+ #---- Pass inside b
pass
-# %% Empty cell
-# --
+# In[25]
+####
+
+#%% Empty cell
+#----
"""
@@ -61,15 +63,19 @@ def test_cell_block_symbols(config, workspace):
document = Document(DOC_URI, workspace, DOC)
symbols = pyls_document_symbols(config, workspace, document)
expected = [
- ('Unnamed cell 1', 1, 17, 225),
+ ('Unnamed cell 1', 1, 22, 225),
('Imports', 2, 2, 224),
- ('Unnamed comment 1', 6, 6, 224),
- ('Cell inside a', 8, 12, 225),
- ('Cell', 10, 12, 225),
- ('Unnamed cell 2', 13, 17, 225),
- ('Pass inside b', 15, 15, 224),
- ('Empty cell', 18, 19, 225),
- ('Unnamed comment 2', 19, 19, 224)
+ ('Other cell', 6, 6, 225),
+ ('Unnamed comment 1', 7, 7, 224),
+ ('Block comment on a', 9, 9, 224),
+ ('Cell inside a', 10, 14, 225),
+ ('Cell', 12, 14, 225),
+ ('Unnamed cell 2', 15, 22, 225),
+ ('Pass inside b', 17, 17, 224),
+ ('25', 20, 20, 225),
+ ('Unnamed comment 2', 21, 21, 224),
+ ('Empty cell', 23, 24, 225),
+ ('Unnamed comment 3', 24, 24, 224)
]
test_results = []
for symbol in symbols:
@@ -90,13 +96,17 @@ def test_ungroup_cell_symbols(config, workspace):
expected = [
('Unnamed cell 1', 1, 1, 225),
('Imports', 2, 2, 224),
- ('Unnamed comment 1', 6, 6, 224),
- ('Cell inside a', 8, 8, 225),
- ('Cell', 10, 10, 225),
- ('Unnamed cell 2', 13, 13, 225),
- ('Pass inside b', 15, 15, 224),
- ('Empty cell', 18, 18, 225),
- ('Unnamed comment 2', 19, 19, 224)
+ ('Other cell', 6, 6, 225),
+ ('Unnamed comment 1', 7, 7, 224),
+ ('Block comment on a', 9, 9, 224),
+ ('Cell inside a', 10, 10, 225),
+ ('Cell', 12, 12, 225),
+ ('Unnamed cell 2', 15, 15, 225),
+ ('Pass inside b', 17, 17, 224),
+ ('25', 20, 20, 225),
+ ('Unnamed comment 2', 21, 21, 224),
+ ('Empty cell', 23, 23, 225),
+ ('Unnamed comment 3', 24, 24, 224)
]
test_results = []
for symbol in symbols:
@@ -115,11 +125,13 @@ def test_disable_block_comments(config, workspace):
config.plugin_settings = lambda _: {'enable_block_comments': False}
symbols = pyls_document_symbols(config, workspace, document)
expected = [
- ('Unnamed cell 1', 1, 17, 225),
- ('Cell inside a', 8, 12, 225),
- ('Cell', 10, 12, 225),
- ('Unnamed cell 2', 13, 17, 225),
- ('Empty cell', 18, 19, 225)
+ ('Unnamed cell 1', 1, 22, 225),
+ ('Other cell', 6, 6, 225),
+ ('Cell inside a', 10, 14, 225),
+ ('Cell', 12, 14, 225),
+ ('Unnamed cell 2', 15, 22, 225),
+ ('25', 20, 20, 225),
+ ('Empty cell', 23, 24, 225)
]
test_results = []
for symbol in symbols:
|
Some issues with special comments in the outline explorer
After PR spyder-ide/spyder#13885, a "special comment" is shown in the outline explorer, regardless of the number of consecutive `-` following the `#`.
Before the outline explorer migration to the pyls, a special comment was registered only when there was exactly 4 consecutive `-` following the `#`. I think this rule should be added back in the current implementation of this feature.
For example, the outline explorer is showing special comments for the horizontal separator that are sometimes present in the header of spyder's file.

## Versions
<!--- You can get this information from Help > About Spyder...
or (if Spyder won't launch) the "conda list" command
from the Anaconda Prompt/Terminal/command line. --->
* Spyder version: 4.2.0.dev0 b7e9cf9b1
* Python version: 3.7.6 64-bit
* Qt version: 5.12.5
* PyQt5 version: 5.12.3
* Operating System: Windows 10
|
0.0
|
117a52c8986659bcb0bc31707826ee1e08cb0bb4
|
[
"pyls_spyder/tests/test_plugin.py::test_cell_block_symbols",
"pyls_spyder/tests/test_plugin.py::test_ungroup_cell_symbols",
"pyls_spyder/tests/test_plugin.py::test_disable_block_comments"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_added_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-12 01:08:23+00:00
|
mit
| 5,690 |
|
spyder-ide__pyls-spyder-21
|
diff --git a/pyls_spyder/plugin.py b/pyls_spyder/plugin.py
index 676eab7..60947e8 100644
--- a/pyls_spyder/plugin.py
+++ b/pyls_spyder/plugin.py
@@ -40,10 +40,10 @@ CELL_REGEX = RegexEvaluator({
# Block comment regular expressions
# 1. Block comments declared with 4 dashes, i.e., # ---- Block comment
BLOCK_DASH = (
- 'BLOCK_DASH', re.compile(r'^[\t ]*# ?-{4}([^-\n\r]?.*)?$'))
+ 'BLOCK_DASH', re.compile(r'^[\t ]*# ?-{4}([^-\n\r].*)?$'))
# 2. Block comments declared with 3 consecutive hashes, i.e., #### Comment
BLOCK_HASH = (
- 'BLOCK_HASH', re.compile(r'^[\t ]*##{3}([^\#\n\r]?.*)?$'))
+ 'BLOCK_HASH', re.compile(r'^[\t ]*##{3}([^\#\n\r].*)?$'))
BLOCK_REGEX = RegexEvaluator(dict([BLOCK_DASH, BLOCK_HASH]))
@@ -133,7 +133,12 @@ def pyls_document_symbols(config: Config,
current_name) = peek_symbol(cell_stack)
cell_stack.insert(0, (line_num, cell_level, cell_name))
elif block_match is not None and enable_block_comments:
- block_name = block_match.group(1).strip()
+ block_name = block_match.group(1)
+ if block_name is None:
+ block_name = ''
+ else:
+ block_name = block_name.strip()
+
if block_name == '':
block_name = 'Unnamed comment {0}'.format(unnamed_block)
unnamed_block += 1
|
spyder-ide/pyls-spyder
|
b5c3ecbc54ee4715d61898d6c9663f449eca7d5d
|
diff --git a/pyls_spyder/tests/test_plugin.py b/pyls_spyder/tests/test_plugin.py
index b7d5c3a..98e2388 100644
--- a/pyls_spyder/tests/test_plugin.py
+++ b/pyls_spyder/tests/test_plugin.py
@@ -44,8 +44,11 @@ def b():
# In[25]
####
-#%% Empty cell
+#%% Invalid comments
#----
+# ---------- This should not work
+###### This either
+#%% Empty cell
"""
@@ -74,8 +77,9 @@ def test_cell_block_symbols(config, workspace):
('Pass inside b', 17, 17, 224),
('25', 20, 20, 225),
('Unnamed comment 2', 21, 21, 224),
- ('Empty cell', 23, 24, 225),
- ('Unnamed comment 3', 24, 24, 224)
+ ('Invalid comments', 23, 26, 225),
+ ('Unnamed comment 3', 24, 24, 224),
+ ('Empty cell', 27, 27, 225)
]
test_results = []
for symbol in symbols:
@@ -105,8 +109,9 @@ def test_ungroup_cell_symbols(config, workspace):
('Pass inside b', 17, 17, 224),
('25', 20, 20, 225),
('Unnamed comment 2', 21, 21, 224),
- ('Empty cell', 23, 23, 225),
- ('Unnamed comment 3', 24, 24, 224)
+ ('Invalid comments', 23, 23, 225),
+ ('Unnamed comment 3', 24, 24, 224),
+ ('Empty cell', 27, 27, 225)
]
test_results = []
for symbol in symbols:
@@ -131,7 +136,8 @@ def test_disable_block_comments(config, workspace):
('Cell', 12, 14, 225),
('Unnamed cell 2', 15, 22, 225),
('25', 20, 20, 225),
- ('Empty cell', 23, 24, 225)
+ ('Invalid comments', 23, 26, 225),
+ ('Empty cell', 27, 27, 225)
]
test_results = []
for symbol in symbols:
@@ -155,7 +161,8 @@ def test_cell_folding_regions(config, workspace):
(12, 14),
(15, 22),
(20, 22),
- (23, 24)
+ (23, 26),
+ (27, 27)
]
test_results = []
for region in regions:
|
Fix code blocks regular expression
It seems that the regular expression for code block comments that start with dash and number sign are not constrained by the actual number required (four in both cases)
|
0.0
|
b5c3ecbc54ee4715d61898d6c9663f449eca7d5d
|
[
"pyls_spyder/tests/test_plugin.py::test_cell_block_symbols",
"pyls_spyder/tests/test_plugin.py::test_ungroup_cell_symbols"
] |
[
"pyls_spyder/tests/test_plugin.py::test_disable_block_comments",
"pyls_spyder/tests/test_plugin.py::test_cell_folding_regions"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-16 03:54:30+00:00
|
mit
| 5,691 |
|
spyder-ide__qtsass-59
|
diff --git a/qtsass/api.py b/qtsass/api.py
index 7a65fe2..cdbfebf 100644
--- a/qtsass/api.py
+++ b/qtsass/api.py
@@ -22,7 +22,7 @@ import sass
# Local imports
from qtsass.conformers import qt_conform, scss_conform
-from qtsass.functions import qlineargradient, rgba
+from qtsass.functions import qlineargradient, qradialgradient, rgba
from qtsass.importers import qss_importer
@@ -35,7 +35,11 @@ else:
# yapf: enable
# Constants
-DEFAULT_CUSTOM_FUNCTIONS = {'qlineargradient': qlineargradient, 'rgba': rgba}
+DEFAULT_CUSTOM_FUNCTIONS = {
+ 'qlineargradient': qlineargradient,
+ 'qradialgradient': qradialgradient,
+ 'rgba': rgba
+}
DEFAULT_SOURCE_COMMENTS = False
# Logger setup
diff --git a/qtsass/conformers.py b/qtsass/conformers.py
index 2eaba07..d2df38f 100644
--- a/qtsass/conformers.py
+++ b/qtsass/conformers.py
@@ -18,8 +18,6 @@ import re
# yapf: enable
-_DEFAULT_COORDS = ('x1', 'y1', 'x2', 'y2')
-
class Conformer(object):
"""Base class for all text transformations."""
@@ -48,6 +46,8 @@ class NotConformer(Conformer):
class QLinearGradientConformer(Conformer):
"""Conform QSS qlineargradient function."""
+ _DEFAULT_COORDS = ('x1', 'y1', 'x2', 'y2')
+
qss_pattern = re.compile(
r'qlineargradient\('
r'((?:(?:\s+)?(?:x1|y1|x2|y2):(?:\s+)?[0-9A-Za-z$_\.-]+,?)+)' # coords
@@ -68,8 +68,8 @@ class QLinearGradientConformer(Conformer):
try:
key, value = key_values
key = key.strip()
- if key in _DEFAULT_COORDS:
- pos = _DEFAULT_COORDS.index(key)
+ if key in self._DEFAULT_COORDS:
+ pos = self._DEFAULT_COORDS.index(key)
if pos >= 0 and pos <= 3:
values[pos] = value.strip()
except ValueError:
@@ -130,6 +130,116 @@ class QLinearGradientConformer(Conformer):
return css
+class QRadialGradientConformer(Conformer):
+ """Conform QSS qradialgradient function."""
+
+ _DEFAULT_COORDS = ('cx', 'cy', 'radius', 'fx', 'fy')
+
+ qss_pattern = re.compile(
+ r'qradialgradient\('
+ # spread
+ r'((?:(?:\s+)?(?:spread):(?:\s+)?[0-9A-Za-z$_\.-]+,?)+)?'
+ # coords
+ r'((?:(?:\s+)?(?:cx|cy|radius|fx|fy):(?:\s+)?[0-9A-Za-z$_\.-]+,?)+)'
+ # stops
+ r'((?:(?:\s+)?stop:.*,?)+(?:\s+)?)?'
+ r'\)',
+ re.MULTILINE,
+ )
+
+ def _conform_spread_to_scss(self, group):
+ """
+ Take a qss str with xy coords and returns the values.
+
+ 'spread: pad|repeat|reflect'
+ """
+ value = 'pad'
+ for key_values in [part.split(':', 1) for part in group.split(',')]:
+ try:
+ key, value = key_values
+ key = key.strip()
+ if key == 'spread':
+ value = value.strip()
+ except ValueError:
+ pass
+ return value
+
+ def _conform_coords_to_scss(self, group):
+ """
+ Take a qss str with xy coords and returns the values.
+
+ 'cx: 0, cy: 0, radius: 0, fx: 0, fy: 0' => '0, 0, 0, 0, 0'
+ 'cy: 1' => '0, 1, 0, 0, 0'
+ """
+ values = ['0', '0', '0', '0', '0']
+ for key_values in [part.split(':', 1) for part in group.split(',')]:
+ try:
+ key, value = key_values
+ key = key.strip()
+ if key in self._DEFAULT_COORDS:
+ pos = self._DEFAULT_COORDS.index(key)
+ if pos >= 0:
+ values[pos] = value.strip()
+ except ValueError:
+ pass
+ return ', '.join(values)
+
+ def _conform_stops_to_scss(self, group):
+ """
+ Take a qss str with stops and returns the values.
+
+ 'stop: 0 red, stop: 1 blue' => '0 red, 1 blue'
+ """
+ new_group = []
+ split = [""]
+ bracket_level = 0
+ for char in group:
+ if not bracket_level and char == ",":
+ split.append("")
+ continue
+ elif char == "(":
+ bracket_level += 1
+ elif char == ")":
+ bracket_level -= 1
+ split[-1] += char
+
+ for part in split:
+ if part:
+ _, value = part.split(':', 1)
+ new_group.append(value.strip())
+ return ', '.join(new_group)
+
+ def to_scss(self, qss):
+ """
+ Conform qss qradialgradient to scss qradialgradient form.
+
+ Normalize all whitespace including the removal of newline chars.
+
+ qradialgradient(cx: 0, cy: 0, radius: 0,
+ fx: 0, fy: 0, stop: 0 red, stop: 1 blue)
+ =>
+ qradialgradient(0, 0, 0, 0, 0, (0 red, 1 blue))
+ """
+ conformed = qss
+
+ for spread, coords, stops in self.qss_pattern.findall(qss):
+ new_spread = "'" + self._conform_spread_to_scss(spread) + "', "
+ conformed = conformed.replace(spread, new_spread, 1)
+ new_coords = self._conform_coords_to_scss(coords)
+ conformed = conformed.replace(coords, new_coords, 1)
+ if not stops:
+ continue
+
+ new_stops = ', ({})'.format(self._conform_stops_to_scss(stops))
+ conformed = conformed.replace(stops, new_stops, 1)
+
+ return conformed
+
+ def to_qss(self, css):
+ """Transform to qss from css."""
+ return css
+
+
conformers = [c() for c in Conformer.__subclasses__() if c is not Conformer]
diff --git a/qtsass/functions.py b/qtsass/functions.py
index 89414cf..d4e0930 100644
--- a/qtsass/functions.py
+++ b/qtsass/functions.py
@@ -80,3 +80,30 @@ def qlineargradient(x1, y1, x2, y2, stops):
template = 'qlineargradient(x1: {}, y1: {}, x2: {}, y2: {}, {})'
return template.format(x1.value, y1.value, x2.value, y2.value,
', '.join(stops_str))
+
+
+def qradialgradient(spread, cx, cy, radius, fx, fy, stops):
+ """
+ Implement qss qradialgradient function for scss.
+
+ :type spread: string
+ :type cx: sass.SassNumber
+ :type cy: sass.SassNumber
+ :type radius: sass.SassNumber
+ :type fx: sass.SassNumber
+ :type fy: sass.SassNumber
+ :type stops: sass.SassList
+ :return:
+ """
+ stops_str = []
+ for stop in stops[0]:
+ pos, color = stop[0]
+ stops_str.append('stop: {} {}'.format(
+ pos.value,
+ rgba_from_color(color),
+ ))
+ template = ('qradialgradient('
+ 'spread: {}, cx: {}, cy: {}, radius: {}, fx: {}, fy: {}, {}'
+ ')')
+ return template.format(spread, cx.value, cy.value, radius.value, fx.value,
+ fy.value, ', '.join(stops_str))
|
spyder-ide/qtsass
|
a4b13fa69076d99bc3cd95bff783698ca9f0160c
|
diff --git a/tests/test_api.py b/tests/test_api.py
index 14fb31f..181e658 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -43,6 +43,19 @@ QWidget {
);
}
"""
+QRADIANTGRADIENTS_STR = """
+QWidget {
+ background: qradialgradient(
+ spread: repeat,
+ cx: 0,
+ cy: 0,
+ fx: 0,
+ fy: 1,
+ stop: 0.1 blue,
+ stop: 0.8 green
+ );
+}
+"""
QNOT_STR = """
QLineEdit:!editable {
background: white;
@@ -71,6 +84,7 @@ def test_compile_strings():
qtsass.compile(COLORS_STR)
qtsass.compile(QLINEARGRADIENTS_STR)
+ qtsass.compile(QRADIANTGRADIENTS_STR)
qtsass.compile(QNOT_STR)
diff --git a/tests/test_conformers.py b/tests/test_conformers.py
index 1739036..64c01a3 100644
--- a/tests/test_conformers.py
+++ b/tests/test_conformers.py
@@ -15,7 +15,11 @@ from textwrap import dedent
import unittest
# Local imports
-from qtsass.conformers import NotConformer, QLinearGradientConformer
+from qtsass.conformers import (
+ NotConformer,
+ QLinearGradientConformer,
+ QRadialGradientConformer,
+)
class TestNotConformer(unittest.TestCase):
@@ -155,5 +159,118 @@ class TestQLinearGradientConformer(unittest.TestCase):
self.css_float_coords_str)
+class TestQRadialGradientConformer(unittest.TestCase):
+
+ css_vars_str = "qradialgradient('$spread', $cx, $cy, $radius, $fx, $fy, (0 $red, 1 $blue))"
+ qss_vars_str = (
+ 'qradialgradient(spread:$spread, cx:$cx, cy:$cy, radius:$radius, fx:$fx, fy:$fy,'
+ 'stop: 0 $red, stop: 1 $blue)'
+ )
+
+ css_nostops_str = "qradialgradient('pad', 0, 0, 0, 0, 0)"
+ qss_nostops_str = 'qradialgradient(spread: pad, cx: 0, cy: 0, fx: 0, fy: 0)'
+
+ css_str = "qradialgradient('pad', 0, 0, 0, 0, 0, (0 red, 1 blue))"
+ qss_singleline_str = (
+ 'qradialgradient(spread: pad, cx: 0, cy: 0, fx: 0, fy: 0, '
+ 'stop: 0 red, stop: 1 blue)'
+ )
+ qss_multiline_str = dedent("""
+ qradialgradient(
+ spread: pad,
+ cx: 0,
+ cy: 0,
+ fx: 0,
+ fy: 0,
+ stop: 0 red,
+ stop: 1 blue
+ )
+ """).strip()
+ qss_weird_whitespace_str = (
+ 'qradialgradient( spread: pad, cx: 0, cy:0, fx: 0, fy:0, '
+ ' stop:0 red, stop: 1 blue )'
+ )
+
+ css_rgba_str = (
+ "qradialgradient('pad', 0, 0, 0, 0, 0, "
+ "(0 rgba(0, 1, 2, 30%), 0.99 rgba(7, 8, 9, 100%)))"
+ )
+ qss_rgba_str = (
+ 'qradialgradient(spread: pad, cx: 0, cy: 0, fx: 0, fy: 0, '
+ 'stop: 0 rgba(0, 1, 2, 30%), stop: 0.99 rgba(7, 8, 9, 100%))'
+ )
+
+ css_incomplete_coords_str = (
+ "qradialgradient('pad', 0, 1, 0, 0, 0, (0 red, 1 blue))"
+ )
+
+ qss_incomplete_coords_str = (
+ 'qradialgradient(spread:pad, cy:1, stop:0 red, stop: 1 blue)'
+ )
+
+ css_float_coords_str = (
+ "qradialgradient('pad', 0, 0.75, 0, 0, 0, (0 green, 1 pink))"
+ )
+
+ qss_float_coords_str = (
+ 'qradialgradient(spread: pad, cy:0.75, stop:0 green, stop: 1 pink)'
+ )
+
+ def test_does_not_affect_css_form(self):
+ """QRadialGradientConformer no affect on css qradialgradient func."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.css_str), self.css_str)
+ self.assertEqual(c.to_qss(self.css_str), self.css_str)
+
+ def test_conform_singleline_str(self):
+ """QRadialGradientConformer singleline qss to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_singleline_str), self.css_str)
+
+ def test_conform_multiline_str(self):
+ """QRadialGradientConformer multiline qss to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_multiline_str), self.css_str)
+
+ def test_conform_weird_whitespace_str(self):
+ """QRadialGradientConformer weird whitespace qss to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_weird_whitespace_str), self.css_str)
+
+ def test_conform_nostops_str(self):
+ """QRadialGradientConformer qss with no stops to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_nostops_str), self.css_nostops_str)
+
+ def test_conform_vars_str(self):
+ """QRadialGradientConformer qss with vars to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_vars_str), self.css_vars_str)
+
+ def test_conform_rgba_str(self):
+ """QRadialGradientConformer qss with rgba to scss."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_rgba_str), self.css_rgba_str)
+
+ def test_incomplete_coords(self):
+ """QRadialGradientConformer qss with not all 4 coordinates given."""
+
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_incomplete_coords_str),
+ self.css_incomplete_coords_str)
+
+ def test_float_coords(self):
+ c = QRadialGradientConformer()
+ self.assertEqual(c.to_scss(self.qss_float_coords_str),
+ self.css_float_coords_str)
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/tests/test_functions.py b/tests/test_functions.py
index bebbf8b..1821c3e 100644
--- a/tests/test_functions.py
+++ b/tests/test_functions.py
@@ -58,5 +58,21 @@ class TestQLinearGradientFunc(BaseCompileTest):
)
+class TestQRadialGradientFunc(BaseCompileTest):
+ def test_color(self):
+ self.assertEqual(
+ self.compile_scss('qradialgradient(pad, 1, 2, 1, 3, 4, (0 red, 1 blue))'),
+ 'qradialgradient(spread: pad, cx: 1.0, cy: 2.0, radius: 1.0, fx: 3.0, fy: 4.0, '
+ 'stop: 0.0 rgba(255, 0, 0, 100%), stop: 1.0 rgba(0, 0, 255, 100%))'
+ )
+
+ def test_rgba(self):
+ self.assertEqual(
+ self.compile_scss('qradialgradient(pad, 1, 2, 1, 3, 4, (0 red, 0.2 rgba(5, 6, 7, 0.8)))'),
+ 'qradialgradient(spread: pad, cx: 1.0, cy: 2.0, radius: 1.0, fx: 3.0, fy: 4.0, '
+ 'stop: 0.0 rgba(255, 0, 0, 100%), stop: 0.2 rgba(5, 6, 7, 80%))'
+ )
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
|
Unsupported qradialgradient
qradialgradient is not supported. Example of typical usage:
```
QRadioButton::indicator:checked
{
background-color: qradialgradient(
cx: 0.5, cy: 0.5,
fx: 0.5, fy: 0.5,
radius: 1.0,
stop: 0.25 #78879b,
stop: 0.3 #302F2F
);
}
```
|
0.0
|
a4b13fa69076d99bc3cd95bff783698ca9f0160c
|
[
"tests/test_api.py::test_compile_strings",
"tests/test_api.py::test_compile_import_raises",
"tests/test_api.py::test_compile_import_with_include_paths",
"tests/test_api.py::test_compile_raises_ValueError",
"tests/test_api.py::test_compile_custom_function",
"tests/test_api.py::test_compile_filename",
"tests/test_api.py::test_compile_filename_imports",
"tests/test_api.py::test_compile_dirname",
"tests/test_api.py::test_watch_raises_ValueError",
"tests/test_conformers.py::TestNotConformer::test_conform_to_qss",
"tests/test_conformers.py::TestNotConformer::test_conform_to_scss",
"tests/test_conformers.py::TestNotConformer::test_round_trip",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_multiline_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_nostops_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_rgba_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_singleline_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_vars_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_conform_weird_whitespace_str",
"tests/test_conformers.py::TestQLinearGradientConformer::test_does_not_affect_css_form",
"tests/test_conformers.py::TestQLinearGradientConformer::test_float_coords",
"tests/test_conformers.py::TestQLinearGradientConformer::test_incomplete_coords",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_multiline_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_nostops_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_rgba_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_singleline_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_vars_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_conform_weird_whitespace_str",
"tests/test_conformers.py::TestQRadialGradientConformer::test_does_not_affect_css_form",
"tests/test_conformers.py::TestQRadialGradientConformer::test_float_coords",
"tests/test_conformers.py::TestQRadialGradientConformer::test_incomplete_coords",
"tests/test_functions.py::TestRgbaFunc::test_rgba",
"tests/test_functions.py::TestRgbaFunc::test_rgba_8bit_int_alpha",
"tests/test_functions.py::TestRgbaFunc::test_rgba_percentage_alpha",
"tests/test_functions.py::TestQLinearGradientFunc::test_color",
"tests/test_functions.py::TestQLinearGradientFunc::test_rgba",
"tests/test_functions.py::TestQRadialGradientFunc::test_color",
"tests/test_functions.py::TestQRadialGradientFunc::test_rgba"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-12-06 10:15:10+00:00
|
mit
| 5,692 |
|
spyder-ide__spyder-kernels-404
|
diff --git a/spyder_kernels/console/kernel.py b/spyder_kernels/console/kernel.py
index 9444397..911e362 100644
--- a/spyder_kernels/console/kernel.py
+++ b/spyder_kernels/console/kernel.py
@@ -344,7 +344,7 @@ class SpyderKernel(IPythonKernel):
# Interrupting the eventloop is only implemented when a message is
# received on the shell channel, but this message is queued and
# won't be processed because an `execute` message is being
- # processed. Therefore we process the message here (comm channel)
+ # processed. Therefore we process the message here (control chan.)
# and request a dummy message to be sent on the shell channel to
# stop the eventloop. This will call back `_interrupt_eventloop`.
self.frontend_call().request_interrupt_eventloop()
@@ -535,7 +535,6 @@ class SpyderKernel(IPythonKernel):
try:
import matplotlib.pyplot as plt
plt.close('all')
- del plt
except:
pass
@@ -594,7 +593,7 @@ class SpyderKernel(IPythonKernel):
both locals() and globals() for current frame when debugging
"""
ns = {}
- if self.shell.is_debugging() and self.shell.pdb_session.prompt_waiting:
+ if self.shell.is_debugging() and self.shell.pdb_session.curframe:
# Stopped at a pdb prompt
ns.update(self.shell.user_ns)
ns.update(self.shell._pdb_locals)
diff --git a/spyder_kernels/console/start.py b/spyder_kernels/console/start.py
index 45c2530..baa7f92 100644
--- a/spyder_kernels/console/start.py
+++ b/spyder_kernels/console/start.py
@@ -270,11 +270,9 @@ def varexp(line):
import guiqwt.pyplot as pyplot
except:
import matplotlib.pyplot as pyplot
- __fig__ = pyplot.figure();
- __items__ = getattr(pyplot, funcname[2:])(
- ip.kernel._get_current_namespace()[name])
+ pyplot.figure();
+ getattr(pyplot, funcname[2:])(ip.kernel._get_current_namespace()[name])
pyplot.show()
- del __fig__, __items__
def main():
diff --git a/spyder_kernels/customize/spyderpdb.py b/spyder_kernels/customize/spyderpdb.py
index b14a01c..838e20c 100755
--- a/spyder_kernels/customize/spyderpdb.py
+++ b/spyder_kernels/customize/spyderpdb.py
@@ -105,9 +105,6 @@ class SpyderPdb(ipyPdb, object): # Inherits `object` to call super() in PY2
# Keep track of remote filename
self.remote_filename = None
- # State of the prompt
- self.prompt_waiting = False
-
# Line received from the frontend
self._cmd_input_line = None
@@ -263,8 +260,12 @@ class SpyderPdb(ipyPdb, object): # Inherits `object` to call super() in PY2
if out is not None:
sys.stdout.flush()
sys.stderr.flush()
- frontend_request(blocking=False).show_pdb_output(
- repr(out))
+ try:
+ frontend_request(blocking=False).show_pdb_output(
+ repr(out))
+ except (CommError, TimeoutError):
+ # Fallback
+ print("pdb out> ", repr(out))
finally:
if execute_events:
@@ -360,7 +361,10 @@ class SpyderPdb(ipyPdb, object): # Inherits `object` to call super() in PY2
Take a number as argument as an (optional) number of context line to
print"""
super(SpyderPdb, self).do_where(arg)
- frontend_request(blocking=False).do_where()
+ try:
+ frontend_request(blocking=False).do_where()
+ except (CommError, TimeoutError):
+ logger.debug("Could not send where request to the frontend.")
do_w = do_where
@@ -660,11 +664,9 @@ class SpyderPdb(ipyPdb, object): # Inherits `object` to call super() in PY2
line = self.cmdqueue.pop(0)
else:
try:
- self.prompt_waiting = True
line = self.cmd_input(self.prompt)
except EOFError:
line = 'EOF'
- self.prompt_waiting = False
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
|
spyder-ide/spyder-kernels
|
28a06758e4c970b86f542ae075b52726948a5c2d
|
diff --git a/.github/workflows/linux-tests.yml b/.github/workflows/linux-tests.yml
index 63ee8b8..a358e80 100644
--- a/.github/workflows/linux-tests.yml
+++ b/.github/workflows/linux-tests.yml
@@ -22,7 +22,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- PYTHON_VERSION: ['2.7', '3.7', '3.8', '3.9']
+ PYTHON_VERSION: ['3.7', '3.8', '3.9']
timeout-minutes: 20
steps:
- name: Checkout branch
diff --git a/.github/workflows/macos-tests.yml b/.github/workflows/macos-tests.yml
index 0e63b69..799bf83 100644
--- a/.github/workflows/macos-tests.yml
+++ b/.github/workflows/macos-tests.yml
@@ -21,7 +21,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- PYTHON_VERSION: ['2.7', '3.7', '3.8', '3.9']
+ PYTHON_VERSION: ['3.7', '3.8', '3.9']
timeout-minutes: 25
steps:
- name: Checkout branch
diff --git a/spyder_kernels/console/tests/test_console_kernel.py b/spyder_kernels/console/tests/test_console_kernel.py
index 0c95fd6..b488bf5 100644
--- a/spyder_kernels/console/tests/test_console_kernel.py
+++ b/spyder_kernels/console/tests/test_console_kernel.py
@@ -831,7 +831,6 @@ def test_do_complete(kernel):
# test pdb
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.completenames = lambda *ignore: ['baba']
kernel.shell.pdb_session = pdb_obj
match = kernel.do_complete('ba', 2)
@@ -890,7 +889,6 @@ def test_comprehensions_with_locals_in_pdb(kernel):
"""
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.curframe_locals = pdb_obj.curframe.f_locals
kernel.shell.pdb_session = pdb_obj
@@ -917,7 +915,6 @@ def test_comprehensions_with_locals_in_pdb_2(kernel):
"""
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.curframe_locals = pdb_obj.curframe.f_locals
kernel.shell.pdb_session = pdb_obj
@@ -944,7 +941,6 @@ def test_namespaces_in_pdb(kernel):
kernel.shell.user_ns["test"] = 0
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.curframe_locals = pdb_obj.curframe.f_locals
kernel.shell.pdb_session = pdb_obj
@@ -1026,7 +1022,6 @@ def test_functions_with_locals_in_pdb_2(kernel):
baba = 1
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.curframe_locals = pdb_obj.curframe.f_locals
kernel.shell.pdb_session = pdb_obj
@@ -1064,7 +1059,6 @@ def test_locals_globals_in_pdb(kernel):
a = 1
pdb_obj = SpyderPdb()
pdb_obj.curframe = inspect.currentframe()
- pdb_obj.prompt_waiting = True
pdb_obj.curframe_locals = pdb_obj.curframe.f_locals
kernel.shell.pdb_session = pdb_obj
@@ -1143,5 +1137,49 @@ def test_get_interactive_backend(backend):
assert value == '0'
+@flaky(max_runs=3)
[email protected](
+ sys.version_info[0] < 3,
+ reason="Fails with python 2")
+def test_debug_namespace(tmpdir):
+ """
+ Test that the kernel uses the proper namespace while debugging.
+ """
+ # Command to start the kernel
+ cmd = "from spyder_kernels.console import start; start.main()"
+
+ with setup_kernel(cmd) as client:
+ # Write code to a file
+ d = tmpdir.join("pdb-ns-test.py")
+ d.write('def func():\n bb = "hello"\n breakpoint()\nfunc()')
+
+ # Run code file `d`
+ msg_id = client.execute("runfile(r'{}')".format(to_text_string(d)))
+
+ # make sure that 'bb' returns 'hello'
+ client.get_stdin_msg(timeout=TIMEOUT)
+ client.input('bb')
+
+ t0 = time.time()
+ while True:
+ assert time.time() - t0 < 5
+ msg = client.get_iopub_msg(timeout=TIMEOUT)
+ if msg.get('msg_type') == 'stream':
+ if 'hello' in msg["content"].get("text"):
+ break
+
+ # make sure that get_value('bb') returns 'hello'
+ client.get_stdin_msg(timeout=TIMEOUT)
+ client.input("get_ipython().kernel.get_value('bb')")
+
+ t0 = time.time()
+ while True:
+ assert time.time() - t0 < 5
+ msg = client.get_iopub_msg(timeout=TIMEOUT)
+ if msg.get('msg_type') == 'stream':
+ if 'hello' in msg["content"].get("text"):
+ break
+
+
if __name__ == "__main__":
pytest.main()
|
Python 2 tests are broken in Conda slots
```
Traceback (most recent call last):
File "/usr/share/miniconda3/envs/test/bin/pytest", line 11, in <module>
sys.exit(main())
TypeError: 'NoneType' object is not callable
```
|
0.0
|
28a06758e4c970b86f542ae075b52726948a5c2d
|
[
"spyder_kernels/console/tests/test_console_kernel.py::test_comprehensions_with_locals_in_pdb",
"spyder_kernels/console/tests/test_console_kernel.py::test_comprehensions_with_locals_in_pdb_2",
"spyder_kernels/console/tests/test_console_kernel.py::test_namespaces_in_pdb",
"spyder_kernels/console/tests/test_console_kernel.py::test_functions_with_locals_in_pdb",
"spyder_kernels/console/tests/test_console_kernel.py::test_functions_with_locals_in_pdb_2",
"spyder_kernels/console/tests/test_console_kernel.py::test_locals_globals_in_pdb",
"spyder_kernels/console/tests/test_console_kernel.py::test_debug_namespace"
] |
[
"spyder_kernels/console/tests/test_console_kernel.py::test_magics",
"spyder_kernels/console/tests/test_console_kernel.py::test_get_namespace_view",
"spyder_kernels/console/tests/test_console_kernel.py::test_get_var_properties",
"spyder_kernels/console/tests/test_console_kernel.py::test_get_value",
"spyder_kernels/console/tests/test_console_kernel.py::test_set_value",
"spyder_kernels/console/tests/test_console_kernel.py::test_remove_value",
"spyder_kernels/console/tests/test_console_kernel.py::test_copy_value",
"spyder_kernels/console/tests/test_console_kernel.py::test_load_npz_data[load0]",
"spyder_kernels/console/tests/test_console_kernel.py::test_load_npz_data[load1]",
"spyder_kernels/console/tests/test_console_kernel.py::test_load_data",
"spyder_kernels/console/tests/test_console_kernel.py::test_save_namespace",
"spyder_kernels/console/tests/test_console_kernel.py::test_is_defined",
"spyder_kernels/console/tests/test_console_kernel.py::test_get_doc",
"spyder_kernels/console/tests/test_console_kernel.py::test_get_source",
"spyder_kernels/console/tests/test_console_kernel.py::test_output_from_c_libraries",
"spyder_kernels/console/tests/test_console_kernel.py::test_cwd_in_sys_path",
"spyder_kernels/console/tests/test_console_kernel.py::test_multiprocessing",
"spyder_kernels/console/tests/test_console_kernel.py::test_multiprocessing_2",
"spyder_kernels/console/tests/test_console_kernel.py::test_dask_multiprocessing",
"spyder_kernels/console/tests/test_console_kernel.py::test_runfile",
"spyder_kernels/console/tests/test_console_kernel.py::test_np_threshold",
"spyder_kernels/console/tests/test_console_kernel.py::test_matplotlib_inline",
"spyder_kernels/console/tests/test_console_kernel.py::test_do_complete",
"spyder_kernels/console/tests/test_console_kernel.py::test_callables_and_modules[True-True]",
"spyder_kernels/console/tests/test_console_kernel.py::test_callables_and_modules[True-False]",
"spyder_kernels/console/tests/test_console_kernel.py::test_callables_and_modules[False-True]",
"spyder_kernels/console/tests/test_console_kernel.py::test_callables_and_modules[False-False]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-30 11:23:48+00:00
|
mit
| 5,693 |
|
spyder-ide__spyder-kernels-86
|
diff --git a/spyder_kernels/customize/spydercustomize.py b/spyder_kernels/customize/spydercustomize.py
index 09247ed..64aa18f 100644
--- a/spyder_kernels/customize/spydercustomize.py
+++ b/spyder_kernels/customize/spydercustomize.py
@@ -534,8 +534,13 @@ class UserModuleReloader(object):
def __init__(self, namelist=None, pathlist=None):
if namelist is None:
namelist = []
- spy_modules = ['sitecustomize', 'spyder', 'spyderplugins']
+
+ # Spyder modules
+ spy_modules = ['spyder_kernels']
+
+ # Matplotlib modules
mpl_modules = ['matplotlib', 'tkinter', 'Tkinter']
+
# Add other, necessary modules to the UMR blacklist
# astropy: see issue 6962
# pytorch: see issue 7041
@@ -550,12 +555,19 @@ class UserModuleReloader(object):
if pathlist is None:
pathlist = []
- self.pathlist = pathlist
+ self.pathlist = self.create_pathlist(pathlist)
+
+ # List of previously loaded modules
self.previous_modules = list(sys.modules.keys())
- @property
- def skip_paths(self):
- """Python library paths to be skipped from module reloading."""
+ # List of module names to reload
+ self.modnames_to_reload = []
+
+ def create_pathlist(self, initial_pathlist):
+ """
+ Add to pathlist Python library paths to be skipped from module
+ reloading.
+ """
try:
paths = sysconfig.get_paths()
lib_paths = [paths['stdlib'],
@@ -563,22 +575,28 @@ class UserModuleReloader(object):
paths['scripts'],
paths['data']]
- return lib_paths
+ return initial_pathlist + lib_paths
except Exception:
- return []
+ return initial_pathlist
- def is_module_blacklisted(self, modname, modpath):
+ def is_module_reloadable(self, module, modname):
+ """Decide if a module is reloadable or not."""
if HAS_CYTHON:
# Don't return cached inline compiled .PYX files
return True
- for path in [sys.prefix]+self.pathlist:
- if modpath.startswith(path):
- return True
else:
- return set(modname.split('.')) & set(self.namelist)
+ if (self.is_module_in_pathlist(module) or
+ self.is_module_in_namelist(modname)):
+ return False
+ else:
+ return True
+
+ def is_module_in_namelist(self, modname):
+ """Decide if a module can be reloaded or not according to its name."""
+ return set(modname.split('.')) & set(self.namelist)
- def is_module_reloadable(self, module):
- """Decide if a module can be reloaded or not."""
+ def is_module_in_pathlist(self, module):
+ """Decide if a module can be reloaded or not according to its path."""
modpath = getattr(module, '__file__', None)
# Skip module according to different criteria
@@ -586,12 +604,12 @@ class UserModuleReloader(object):
# *module* is a C module that is statically linked into the
# interpreter. There is no way to know its path, so we
# choose to ignore it.
- return False
- elif any([p in modpath for p in self.skip_paths]):
+ return True
+ elif any([p in modpath for p in self.pathlist]):
# We don't want to reload modules that belong to the
# standard library or installed to site-packages,
# just modules created by the user.
- return False
+ return True
elif not os.name == 'nt':
# Module paths containing the strings below can be ihherited
# from the default Linux installation or Homebrew in a
@@ -601,39 +619,49 @@ class UserModuleReloader(object):
r'^/usr/.*/dist-packages/.*',
r'^/Library/.*'
]
+
if [p for p in patterns if re.search(p, modpath)]:
- return False
- else:
return True
+ else:
+ return False
else:
- return True
+ return False
def run(self, verbose=False):
"""
- Del user modules to force Python to deeply reload them
+ Delete user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
"""
- log = []
+ self.modnames_to_reload = []
for modname, module in list(sys.modules.items()):
if modname not in self.previous_modules:
# Decide if a module can be reloaded or not
- if not self.is_module_reloadable(module):
- continue
-
- # Reload module
- if not self.is_module_blacklisted(modname, modpath):
- log.append(modname)
+ if self.is_module_reloadable(module, modname):
+ self.modnames_to_reload.append(modname)
del sys.modules[modname]
+ else:
+ continue
# Report reloaded modules
- if verbose and log:
+ if verbose and self.modnames_to_reload:
+ modnames = self.modnames_to_reload
_print("\x1b[4;33m%s\x1b[24m%s\x1b[0m"\
- % ("Reloaded modules", ": "+", ".join(log)))
+ % ("Reloaded modules", ": "+", ".join(modnames)))
-__umr__ = None
+
+if os.environ.get("SPY_UMR_ENABLED", "").lower() == "true":
+ namelist = os.environ.get("SPY_UMR_NAMELIST", None)
+ if namelist is not None:
+ try:
+ namelist = namelist.split(',')
+ except Exception:
+ namelist = None
+ __umr__ = UserModuleReloader(namelist=namelist)
+else:
+ __umr__ = None
#==============================================================================
@@ -715,16 +743,10 @@ def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False):
# UnicodeError, TypeError --> eventually raised in Python 2
# AttributeError --> systematically raised in Python 3
pass
- global __umr__
- if os.environ.get("SPY_UMR_ENABLED", "").lower() == "true":
- if __umr__ is None:
- namelist = os.environ.get("SPY_UMR_NAMELIST", None)
- if namelist is not None:
- namelist = namelist.split(',')
- __umr__ = UserModuleReloader(namelist=namelist)
- else:
- verbose = os.environ.get("SPY_UMR_VERBOSE", "").lower() == "true"
- __umr__.run(verbose=verbose)
+
+ if __umr__ is not None:
+ verbose = os.environ.get("SPY_UMR_VERBOSE", "").lower() == "true"
+ __umr__.run(verbose=verbose)
if args is not None and not isinstance(args, basestring):
raise TypeError("expected a character buffer object")
if namespace is None:
|
spyder-ide/spyder-kernels
|
855acc7006fa1a61c03ffda0e379a532a174b540
|
diff --git a/spyder_kernels/customize/tests/test_spydercustomize.py b/spyder_kernels/customize/tests/test_spydercustomize.py
index e478889..771d089 100644
--- a/spyder_kernels/customize/tests/test_spydercustomize.py
+++ b/spyder_kernels/customize/tests/test_spydercustomize.py
@@ -19,29 +19,61 @@ from spyder_kernels.customize.spydercustomize import UserModuleReloader
from spyder_kernels.py3compat import to_text_string
-def test_umr_skip_libmodules(tmpdir):
- """Test that UMR skips library modules and reloads user modules."""
- umr = UserModuleReloader()
-
- # Don't reload stdlib modules
- import xml
- assert umr.is_module_reloadable(xml) == False
-
- # Don't reload third-party modules
- import numpy
- assert umr.is_module_reloadable(numpy) == False
-
- # Reload user modules
[email protected]
+def user_module(tmpdir):
+ """Create a simple module in tmpdir as an example of a user module."""
sys.path.append(to_text_string(tmpdir))
modfile = tmpdir.mkdir('foo').join('bar.py')
code = """
- def square(x):
- return x**2
+def square(x):
+ return x**2
"""
modfile.write(code)
init_file = tmpdir.join('foo').join('__init__.py')
init_file.write('#')
+
+def test_umr_run(user_module):
+ """Test that UMR's run method is working correctly."""
+ umr = UserModuleReloader()
+
+ from foo.bar import square
+ umr.run(verbose=True)
+ umr.modnames_to_reload == ['foo', 'foo.bar']
+
+
+def test_umr_previous_modules(user_module):
+ """Test that UMR's previos_modules is working as expected."""
+ umr = UserModuleReloader()
+
+ import foo
+ assert 'IPython' in umr.previous_modules
+ assert 'foo' not in umr.previous_modules
+
+
+def test_umr_namelist():
+ """Test that the UMR skips modules according to its name."""
+ umr = UserModuleReloader()
+
+ assert umr.is_module_in_namelist('tensorflow')
+ assert umr.is_module_in_namelist('pytorch')
+ assert umr.is_module_in_namelist('spyder_kernels')
+ assert not umr.is_module_in_namelist('foo')
+
+
+def test_umr_pathlist(user_module):
+ """Test that the UMR skips modules according to its path."""
+ umr = UserModuleReloader()
+
+ # Don't reload stdlib modules
+ import xml
+ assert umr.is_module_in_pathlist(xml)
+
+ # Don't reload third-party modules
+ import numpy
+ assert umr.is_module_in_pathlist(numpy)
+
+ # Reload user modules
import foo
- assert umr.is_module_reloadable(foo)
+ assert umr.is_module_in_pathlist(foo) == False
|
NameError: name 'modpath' is not defined
Commit 31694ab74d9c5494a2c6054d2aaeee05cfc9ec15 introduced a bug when running a file a second time.
I'm using the latest `spyder-kernels` on master with the latest `spyder` also on master.
Windows 10, Python 3.7.1 64-bit
```python
Traceback (most recent call last):
File "<ipython-input-3-ec616f24c2fa>", line 1, in <module>
runfile('C:/Users/User/OneDrive/INRS/2017 - Projet INRS PACC/Analyses Baro/calcul_fft.py', wdir='C:/Users/User/OneDrive/INRS/2017 - Projet INRS PACC/Analyses Baro')
File "C:\Users\User\spyder-kernels\spyder_kernels\customize\spydercustomize.py", line 732, in runfile
run_umr()
File "C:\Users\User\spyder-kernels\spyder_kernels\customize\spydercustomize.py", line 716, in run_umr
__umr__.run(verbose=verbose)
File "C:\Users\User\spyder-kernels\spyder_kernels\customize\spydercustomize.py", line 627, in run
if not self.is_module_blacklisted(modname, modpath):
NameError: name 'modpath' is not defined
```
|
0.0
|
855acc7006fa1a61c03ffda0e379a532a174b540
|
[
"spyder_kernels/customize/tests/test_spydercustomize.py::test_umr_run",
"spyder_kernels/customize/tests/test_spydercustomize.py::test_umr_previous_modules",
"spyder_kernels/customize/tests/test_spydercustomize.py::test_umr_namelist"
] |
[] |
{
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-06 17:05:39+00:00
|
mit
| 5,694 |
|
sralloza__vcm-107
|
diff --git a/README.md b/README.md
index 733f006..27ff1f0 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
<h2 align="center">Virtual Campus Manager</h2>
<p align="center">
-<a href="https://github.com/sralloza/vcm/actions"><img alt="build" src="https://github.com/sralloza/vcm/workflows/Python application/badge.svg?branch=test-coverage"></a>
-<a href="https://codecov.io/gh/sralloza/vcm/branch/test-coverage"><img alt="coverage" src="https://codecov.io/github/sralloza/vcm/coverage.svg?branch=test-coverage"></a>
+<a href="https://github.com/sralloza/vcm/actions"><img alt="build" src="https://github.com/sralloza/vcm/workflows/Python application/badge.svg"></a>
+<a href="https://codecov.io/gh/sralloza/vcm/branch/test-coverage"><img alt="coverage" src="https://codecov.io/github/sralloza/vcm/coverage.svg"></a>
<a href="https://github.com/sralloza/vcm/blob/master/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
</p>
diff --git a/vcm/core/workers.py b/vcm/core/workers.py
index d394e74..12fdfbc 100644
--- a/vcm/core/workers.py
+++ b/vcm/core/workers.py
@@ -7,6 +7,7 @@ import sys
from threading import Event, Thread
from threading import enumerate as enumerate_threads
from time import time
+from typing import List
from colorama import Fore
@@ -252,21 +253,21 @@ class Killer(Worker):
open_http_status_server()
-def start_workers(queue, nthreads=20, no_killer=False):
+def start_workers(queue, nthreads=20, killer=True) -> List[Worker]:
"""Starts the wokers.
Args:
queue (Queue): queue to manage the workers's tasks.
nthreads (int): number of trheads to start.
- no_killer (bool): if true, killer thread will not be started.
+ killer (bool): if True, killer thread will be started.
Returns:
-
+ List[Worker]: list of started threads.
"""
thread_list = []
- if no_killer is False:
+ if killer is True:
killer = Killer(queue)
killer.start()
thread_list.append(killer)
diff --git a/vcm/downloader/__init__.py b/vcm/downloader/__init__.py
index 6bd000a..22b187f 100644
--- a/vcm/downloader/__init__.py
+++ b/vcm/downloader/__init__.py
@@ -72,13 +72,13 @@ def find_subjects(queue, discover_only=False):
@timing(name="VCM downloader")
-def download(nthreads=20, no_killer=False, status_server=True, discover_only=False):
+def download(nthreads=20, killer=True, status_server=True, discover_only=False):
"""
Args:
nthreads (int, optional): number of threads to use. Defaults to 20.
- no_killer (bool, optional): if True, an extra thread will be launched
- to detect key pressings, shuch as K for kill the app. Defaults to False.
+ killer (bool, optional): if True, an extra thread will be launched
+ to detect key pressings, shuch as K for kill the app. Defaults to True.
status_server (bool, optional): if true, a http server will be opened
in port 80 to show the status of each thread. Defaults to True.
discover_only (bool, optional): if true, it will only discover the subjects,
@@ -87,9 +87,9 @@ def download(nthreads=20, no_killer=False, status_server=True, discover_only=Fal
logger = logging.getLogger(__name__)
logger.info(
- "Launching notify(nthreads=%r, no_killer=%s, status_server=%s, discover_only=%s)",
+ "Launching notify(nthreads=%r, killer=%s, status_server=%s, discover_only=%s)",
nthreads,
- no_killer,
+ killer,
status_server,
discover_only,
)
@@ -98,7 +98,7 @@ def download(nthreads=20, no_killer=False, status_server=True, discover_only=Fal
init_colorama()
queue = Queue()
- threads = start_workers(queue, nthreads, no_killer=no_killer)
+ threads = start_workers(queue, nthreads, killer=killer)
if status_server:
runserver(queue, threads)
diff --git a/vcm/main.py b/vcm/main.py
index 0d4b710..3588562 100644
--- a/vcm/main.py
+++ b/vcm/main.py
@@ -175,7 +175,7 @@ def execute_discover(opt): # pylint: disable=W0613
"""
Printer.silence()
- return download(nthreads=1, no_killer=True, status_server=False, discover_only=True)
+ return download(nthreads=1, killer=False, status_server=False, discover_only=True)
def execute_download(opt):
@@ -190,7 +190,7 @@ def execute_download(opt):
return download(
nthreads=opt.nthreads,
- no_killer=opt.no_killer,
+ killer=not opt.no_killer,
status_server=not opt.no_status_server,
)
|
sralloza/vcm
|
574c2f11f28b9dd1719c70cb6252d37eff230410
|
diff --git a/tests/test_main.py b/tests/test_main.py
index d03bd3e..e1fa18b 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -443,7 +443,7 @@ def test_execute_discover(silence_m, download_m):
silence_m.assert_called_once_with()
download_m.assert_called_once_with(
- nthreads=1, no_killer=True, status_server=False, discover_only=True
+ nthreads=1, killer=False, status_server=False, discover_only=True
)
@@ -466,17 +466,17 @@ class TestExecuteDownload:
return request.param
@pytest.fixture(params=[True, False])
- def no_killer(self, request):
+ def killer(self, request):
return request.param
@pytest.fixture(params=[1, 5, 10, 15, 20])
def nthreads(self, request):
return request.param
- def test_execute_download(self, debug, no_killer, nthreads, server):
+ def test_execute_download(self, debug, killer, nthreads, server):
opt = Namespace(
debug=debug,
- no_killer=no_killer,
+ no_killer=not killer,
nthreads=nthreads,
no_status_server=not server,
)
@@ -488,7 +488,7 @@ class TestExecuteDownload:
self.ohss_m.assert_not_called()
self.download_m.assert_called_once_with(
- nthreads=nthreads, no_killer=no_killer, status_server=server
+ nthreads=nthreads, killer=killer, status_server=server
)
|
download function argument should be named `killer`, not `no_killer`
|
0.0
|
574c2f11f28b9dd1719c70cb6252d37eff230410
|
[
"tests/test_main.py::test_execute_discover",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-1-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-1-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-5-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-5-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-10-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-10-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-15-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-15-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-20-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-True-20-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-1-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-1-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-5-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-5-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-10-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-10-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-15-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-15-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-20-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[True-False-20-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-1-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-1-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-5-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-5-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-10-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-10-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-15-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-15-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-20-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-True-20-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-1-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-1-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-5-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-5-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-10-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-10-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-15-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-15-False]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-20-True]",
"tests/test_main.py::TestExecuteDownload::test_execute_download[False-False-20-False]"
] |
[
"tests/test_main.py::TestCommand::test_inherintance",
"tests/test_main.py::TestCommand::test_length",
"tests/test_main.py::TestCommand::test_attributes",
"tests/test_main.py::TestCommand::test_types",
"tests/test_main.py::TestCommand::test_to_str",
"tests/test_main.py::test_parser",
"tests/test_main.py::TestParseArgs::TestPositionalArguments::test_no_args",
"tests/test_main.py::TestParseArgs::TestPositionalArguments::test_nss",
"tests/test_main.py::TestParseArgs::TestPositionalArguments::test_version",
"tests/test_main.py::TestParseArgs::TestPositionalArguments::test_check_updates",
"tests/test_main.py::TestParseArgs::TestDownload::test_no_arguments",
"tests/test_main.py::TestParseArgs::TestDownload::test_nthreads_ok",
"tests/test_main.py::TestParseArgs::TestDownload::test_nthreads_error",
"tests/test_main.py::TestParseArgs::TestDownload::test_no_killer",
"tests/test_main.py::TestParseArgs::TestDownload::test_debug",
"tests/test_main.py::TestParseArgs::TestDownload::test_quiet",
"tests/test_main.py::TestParseArgs::TestNotify::test_no_arguments",
"tests/test_main.py::TestParseArgs::TestNotify::test_nthreads_ok",
"tests/test_main.py::TestParseArgs::TestNotify::test_nthreads_error",
"tests/test_main.py::TestParseArgs::TestNotify::test_no_icons",
"tests/test_main.py::TestParseArgs::TestSettings::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::test_list",
"tests/test_main.py::TestParseArgs::TestSettings::TestSet::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestSet::test_no_value",
"tests/test_main.py::TestParseArgs::TestSettings::TestSet::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::TestShow::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestShow::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::TestExclude::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestExclude::test_type_error",
"tests/test_main.py::TestParseArgs::TestSettings::TestExclude::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::TestInclude::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestInclude::test_type_error",
"tests/test_main.py::TestParseArgs::TestSettings::TestInclude::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::TestIndex::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestIndex::test_type_error",
"tests/test_main.py::TestParseArgs::TestSettings::TestIndex::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::TestUnIndex::test_no_args",
"tests/test_main.py::TestParseArgs::TestSettings::TestUnIndex::test_type_error",
"tests/test_main.py::TestParseArgs::TestSettings::TestUnIndex::test_ok",
"tests/test_main.py::TestParseArgs::TestSettings::test_keys",
"tests/test_main.py::TestParseArgs::TestSettings::test_check",
"tests/test_main.py::TestParseArgs::test_discover",
"tests/test_main.py::TestParseArgs::test_version_command",
"tests/test_main.py::test_parser_error",
"tests/test_main.py::test_get_command[Command.notify]",
"tests/test_main.py::test_get_command[Command.download]",
"tests/test_main.py::test_get_command[Command.settings]",
"tests/test_main.py::test_get_command[Command.discover]",
"tests/test_main.py::test_get_command[Command.version]",
"tests/test_main.py::test_get_command[None]",
"tests/test_main.py::test_get_command[invalid]",
"tests/test_main.py::test_show_version",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_execute",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_list",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_check",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_exclude",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_include",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_index",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_un_index",
"tests/test_main.py::TestNonKeyBasedSettingsSubcommand::test_keys",
"tests/test_main.py::TestParseSettingsKey::test_ok[cc1.m1]",
"tests/test_main.py::TestParseSettingsKey::test_ok[cc2.m2]",
"tests/test_main.py::TestParseSettingsKey::test_ok[cc2.m3]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_1[a.b.c.d.]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_1[aaaa]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_1[aa-bb]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_2[cc103.asdf]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_2[invalid.34]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_2[mec.a]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_3[cc1.m2]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_3[cc1.m3]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_3[cc2.m1]",
"tests/test_main.py::TestParseSettingsKey::test_invalid_key_3[cc2.m4]",
"tests/test_main.py::TestExecuteSettings::test_key_based_settings[set]",
"tests/test_main.py::TestExecuteSettings::test_key_based_settings[show]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[list]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[check]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[exclude]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[include]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[index]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[un_index]",
"tests/test_main.py::TestExecuteSettings::test_not_key_based_settings[keys]",
"tests/test_main.py::TestMain::test_version_argument",
"tests/test_main.py::TestMain::test_check_updates",
"tests/test_main.py::TestMain::test_download[True]",
"tests/test_main.py::TestMain::test_download[False]",
"tests/test_main.py::TestMain::test_notify",
"tests/test_main.py::TestMain::test_discover",
"tests/test_main.py::TestMain::test_settings",
"tests/test_main.py::test_instructions_dict"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-01 15:57:50+00:00
|
mit
| 5,695 |
|
srsudar__eg-88
|
diff --git a/eg/config.py b/eg/config.py
index f448d28..661057a 100644
--- a/eg/config.py
+++ b/eg/config.py
@@ -173,12 +173,16 @@ def get_egrc_config(cli_egrc_path):
if config_path == '':
# Try for the xdg config.
- xdg_home_dir = os.getenv('XDG_CONFIG_HOME')
- if xdg_home_dir:
- xdg_config_path = os.path.join(xdg_home_dir, 'eg', 'egrc')
- xdg_config_path = get_expanded_path(xdg_config_path)
- if os.path.isfile(xdg_config_path):
- config_path = xdg_config_path
+ # The freedesktop.org spec says '$HOME/.config' should be used if the
+ # environment variable is not set or is empty. os.getenv() will be falsey
+ # if it is either not set (None) or an empty string.
+ default_xdg_dir = os.path.join('~', '.config')
+ xdg_home_dir = os.getenv('XDG_CONFIG_HOME') or default_xdg_dir
+
+ xdg_config_path = os.path.join(xdg_home_dir, 'eg', 'egrc')
+ xdg_config_path = get_expanded_path(xdg_config_path)
+ if os.path.isfile(xdg_config_path):
+ config_path = xdg_config_path
if config_path == '':
# Fall back to our home directory.
|
srsudar/eg
|
72f507e689816d58b1664aeeea08e394f23f61a9
|
diff --git a/test/config_test.py b/test/config_test.py
index 4277230..c7ea4cb 100644
--- a/test/config_test.py
+++ b/test/config_test.py
@@ -200,6 +200,50 @@ def test_get_egrc_config_uses_home_dir_default_no_xdg_dir():
)
+def test_get_egrc_config_uses_default_xdg_dir_if_env_var_not_set():
+ """
+ If the XDG environment variable isn't set, but the file exists at the
+ default XDG location, it should be used. Note that here we don't have
+ 'egrc', not as a hidden file by default.
+
+ See: https://github.com/srsudar/eg/issues/87
+ """
+ expected = 'mock config from default position'
+
+ _assert_about_get_egrc_config(
+ cli_path=None,
+ cli_config_exists=False,
+ winning_config_path=os.path.join(
+ '~', '.config', 'eg', 'egrc_expanded'),
+ home_config_exists=True,
+ expected_config=expected,
+ xdg_dir_variable=None,
+ xdg_config_exists=True,
+ )
+
+
+def test_get_egrc_config_uses_default_xdg_dir_if_env_var_empty():
+ """
+ If the XDG environment variable is empty, but the file exists at the default
+ XDG location, it should be used. Note that here we don't have 'egrc', not as
+ a hidden file by default.
+
+ See: https://github.com/srsudar/eg/issues/87
+ """
+ expected = 'mock config from default position'
+
+ _assert_about_get_egrc_config(
+ cli_path=None,
+ cli_config_exists=False,
+ winning_config_path=os.path.join(
+ '~', '.config', 'eg', 'egrc_expanded'),
+ home_config_exists=True,
+ expected_config=expected,
+ xdg_dir_variable='',
+ xdg_config_exists=True,
+ )
+
+
def test_get_egrc_config_uses_home_dir_default_xdg_dir_file_not_present():
"""
Fallback to the home directory config if XDG directory is set but the XDG
@@ -217,7 +261,7 @@ def test_get_egrc_config_uses_home_dir_default_xdg_dir_file_not_present():
xdg_config_exists=False,
)
-def test_get_egrc_config_uses_xdg_dir_default_if_present():
+def test_get_egrc_config_uses_xdg_dir_default_if_both_present():
"""
The XDG config should win over the home directory.
"""
@@ -278,8 +322,13 @@ def _assert_about_get_egrc_config(
return cli_config_exists
if file_name == os.path.join('~', '.egrc_expanded'):
return home_config_exists
- if file_name == os.path.join(xdg_dir_variable, 'eg', 'egrc_expanded'):
- # ${XDG_DIR_HOME}/eg/egrc
+ if (xdg_dir_variable and
+ file_name == os.path.join(xdg_dir_variable, 'eg', 'egrc_expanded')):
+ # ${XDG_CONFIG_HOME}/eg/egrc
+ return xdg_config_exists
+ if file_name == os.path.join('~', '.config', 'eg', 'egrc_expanded'):
+ # This is the default location of XDG_CONFIG_HOME, which we may fall
+ # back to under some test cases.
return xdg_config_exists
return False
mock_isfile.side_effect = isfile_side_effect
|
No recognize config path: $HOME/.config/eg/egrc
Version: 1.2.0
Installed from pip
I follow the [information](https://github.com/srsudar/eg#configuration-and-extension) on README of the repository. For custom config file I create a file called `egrc` on the next path: `skabit/.config/eg`, but nothing happens. In this file I only add a custom directory with my examples:
```
[eg-config]
# Lines starting with # are treated as comments
custom-dir = ~/docu/cheats
```
|
0.0
|
72f507e689816d58b1664aeeea08e394f23f61a9
|
[
"test/config_test.py::test_get_egrc_config_uses_default_xdg_dir_if_env_var_not_set",
"test/config_test.py::test_get_egrc_config_uses_default_xdg_dir_if_env_var_empty"
] |
[
"test/config_test.py::test_get_egrc_config_uses_home_dir_default_xdg_dir_file_not_present",
"test/config_test.py::test_get_resolved_config_falls_back_to_defaults",
"test/config_test.py::test_get_priority_respect_false",
"test/config_test.py::test_get_config_tuple_from_egrc_all_none_when_not_present",
"test/config_test.py::test_default_color_config",
"test/config_test.py::test_get_priority_first",
"test/config_test.py::test_parse_bool_true_for_truthy_values",
"test/config_test.py::test_get_config_tuple_from_egrc_when_present",
"test/config_test.py::test_get_resolved_config_calls_expand_paths",
"test/config_test.py::test_merge_color_configs_mixed",
"test/config_test.py::test_parse_substitution_error_if_not_list",
"test/config_test.py::test_parse_substitution_error_if_wrong_length",
"test/config_test.py::test_get_resolved_config_defaults_to_egrc",
"test/config_test.py::test_parse_substitution_error_if_third_element_not_bool",
"test/config_test.py::test_get_egrc_config_uses_home_dir_default_no_xdg_dir",
"test/config_test.py::test_get_substitution_from_config_finds_multiple_substitutions",
"test/config_test.py::test_config_returns_egrc_values_if_present",
"test/config_test.py::test_get_resolved_config_uses_custom_egrc_path",
"test/config_test.py::test_parse_substitution_from_list_without_is_multiline",
"test/config_test.py::test_get_egrc_returns_empty_if_no_egrc",
"test/config_test.py::test_get_priority_third",
"test/config_test.py::test_merge_color_configs_take_all_first",
"test/config_test.py::test_merge_color_configs_first_all_none",
"test/config_test.py::test_get_substitution_from_config_finds_single_substitution",
"test/config_test.py::test_get_egrc_config_uses_xdg_dir_default_if_both_present",
"test/config_test.py::test_parse_substitution_from_list_with_is_multiline",
"test/config_test.py::test_get_resolved_config_prioritizes_cli",
"test/config_test.py::test_get_priority_second",
"test/config_test.py::test_inform_if_paths_invalid_selectively_informs",
"test/config_test.py::test_get_egrc_config_reads_from_command_line",
"test/config_test.py::test_parse_bool_false_for_non_truthy_values"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-01-08 04:58:14+00:00
|
mit
| 5,696 |
|
sscpac__statick-157
|
diff --git a/statick_tool/plugins/tool/pyflakes_tool_plugin.py b/statick_tool/plugins/tool/pyflakes_tool_plugin.py
index 35f29e6..2eab8cb 100644
--- a/statick_tool/plugins/tool/pyflakes_tool_plugin.py
+++ b/statick_tool/plugins/tool/pyflakes_tool_plugin.py
@@ -55,18 +55,48 @@ class PyflakesToolPlugin(ToolPlugin):
issues = self.parse_output(total_output)
return issues
- def parse_output(self, total_output):
+ def parse_output(self, total_output): # pylint: disable=too-many-locals
"""Parse tool output and report issues."""
- pyflakes_re = r"(.+):(\d+):\s(.+)"
- parse = re.compile(pyflakes_re)
+ tool_re_first = r"(.+):(\d+):(\d+):\s(.+)"
+ parse_first = re.compile(tool_re_first)
+ tool_re_second = r"(.+):(\d+):\s(.+)"
+ parse_second = re.compile(tool_re_second)
+ tool_re_third = r"\s(.+)"
+ parse_third = re.compile(tool_re_third)
issues = []
+ filename = ''
+ line_number = 0
+ issue_type = ''
+ message = ''
for output in total_output:
+ first_line = True
+ found_match = False
for line in output.splitlines():
- match = parse.match(line)
- if match:
- issues.append(Issue(match.group(1), match.group(2),
- self.get_name(), self.get_name(),
- "5", match.group(3), None))
+ if first_line:
+ match = parse_first.match(line)
+ first_line = False
+ if match:
+ found_match = True
+ filename = match.group(1)
+ line_number = match.group(2)
+ issue_type = match.group(4)
+ else:
+ match = parse_second.match(line)
+ if match:
+ found_match = True
+ filename = match.group(1)
+ line_number = match.group(2)
+ issue_type = match.group(3)
+ else:
+ match = parse_third.match(line)
+ first_line = True
+ if match:
+ found_match = True
+ message = match.group(1)
+ if found_match:
+ issues.append(Issue(filename, line_number,
+ self.get_name(), issue_type,
+ "5", message, None))
return issues
|
sscpac/statick
|
7e56cf7aa79e2b6fa3af28e2a2194008d2d9562b
|
diff --git a/tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py b/tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py
index d0b148f..5c1dd05 100644
--- a/tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py
+++ b/tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py
@@ -63,15 +63,15 @@ def test_pyflakes_tool_plugin_scan_valid():
def test_pyflakes_tool_plugin_parse_valid():
"""Verify that we can parse the normal output of pyflakes."""
pftp = setup_pyflakes_tool_plugin()
- output = "pyflakes_test.py:4: 'json' imported but unused"
+ output = "pyflakes_test.py:39:34: invalid syntax\nprint 'No files in %s' " \
+ "% (source_dir)"
issues = pftp.parse_output([output])
assert len(issues) == 1
assert issues[0].filename == 'pyflakes_test.py'
- assert issues[0].line_number == '4'
+ assert issues[0].line_number == '39'
assert issues[0].tool == 'pyflakes'
- assert issues[0].issue_type == 'pyflakes'
+ assert issues[0].issue_type == 'invalid syntax'
assert issues[0].severity == '5'
- assert issues[0].message == "'json' imported but unused"
def test_pyflakes_tool_plugin_parse_invalid():
|
Support Python 3.8
According to [PEP-569](https://www.python.org/dev/peps/pep-0569/), Python 3.8 will be released on October 21, 2019. When that happens we should add it to the tox configuration.
|
0.0
|
7e56cf7aa79e2b6fa3af28e2a2194008d2d9562b
|
[
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_parse_valid"
] |
[
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_found",
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_scan_valid",
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_parse_invalid",
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_scan_calledprocesserror",
"tests/plugins/tool/pyflakes_tool_plugin/test_pyflakes_tool_plugin.py::test_pyflakes_tool_plugin_scan_oserror"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-17 22:31:14+00:00
|
cc0-1.0
| 5,697 |
|
sscpac__statick-436
|
diff --git a/statick_tool/plugins/tool/cccc_tool_plugin.py b/statick_tool/plugins/tool/cccc_tool_plugin.py
index 67b57aa..be3192e 100644
--- a/statick_tool/plugins/tool/cccc_tool_plugin.py
+++ b/statick_tool/plugins/tool/cccc_tool_plugin.py
@@ -193,7 +193,7 @@ class CCCCToolPlugin(ToolPlugin):
config[row[".ADA"]] = {
"warn": row["ada.95"],
"error": row[""],
- "name": row[None][3], # type: ignore
+ "name": row[None][3],
"key": row[".ADA"],
}
diff --git a/statick_tool/statick.py b/statick_tool/statick.py
index 14e31d6..dedf01e 100644
--- a/statick_tool/statick.py
+++ b/statick_tool/statick.py
@@ -151,6 +151,13 @@ class Statick:
args.add_argument(
"--config", dest="config", type=str, help="Name of config yaml file"
)
+ args.add_argument(
+ "--level",
+ dest="level",
+ type=str,
+ help="Scan level to use from config file. \
+ Overrides any levels specified by the profile.",
+ )
args.add_argument(
"--profile", dest="profile", type=str, help="Name of profile yaml file"
)
@@ -219,6 +226,9 @@ class Statick:
"""Get level to scan package at."""
path = os.path.abspath(path)
+ if args.level is not None:
+ return str(args.level)
+
profile_filename = "profile.yaml"
if args.profile is not None:
profile_filename = args.profile
|
sscpac/statick
|
33f736f75604a20246d459589e3ccad51c1cfe93
|
diff --git a/tests/statick/test_statick.py b/tests/statick/test_statick.py
index 178c359..9548e5c 100644
--- a/tests/statick/test_statick.py
+++ b/tests/statick/test_statick.py
@@ -92,6 +92,7 @@ def test_get_level(init_statick):
args.parser.add_argument(
"--profile", dest="profile", type=str, default="profile-test.yaml"
)
+ args.parser.add_argument("--level", dest="level", type=str)
level = init_statick.get_level("some_package", args.get_args([]))
assert level == "default_value"
@@ -106,10 +107,30 @@ def test_get_level_non_default(init_statick):
args.parser.add_argument(
"--profile", dest="profile", type=str, default="profile-test.yaml"
)
+ args.parser.add_argument("--level", dest="level", type=str)
level = init_statick.get_level("package", args.get_args([]))
assert level == "package_specific"
+def test_get_level_cli(init_statick):
+ """
+ Test searching for a level when a level was specified on the command line.
+
+ Expected result: Some level is returned
+ """
+ args = Args("Statick tool")
+ args.parser.add_argument(
+ "--profile", dest="profile", type=str, default="profile-test.yaml"
+ )
+ args.parser.add_argument(
+ "--level", dest="level", type=str, default="custom"
+ )
+ level = init_statick.get_level("package", args.get_args([]))
+ assert level == "custom"
+ level = init_statick.get_level("package_specific", args.get_args([]))
+ assert level == "custom"
+
+
def test_get_level_nonexistent_file(init_statick):
"""
Test searching for a level which doesn't have a corresponding file.
@@ -120,6 +141,7 @@ def test_get_level_nonexistent_file(init_statick):
args.parser.add_argument(
"--profile", dest="profile", type=str, default="nonexistent.yaml"
)
+ args.parser.add_argument("--level", dest="level", type=str)
level = init_statick.get_level("some_package", args.get_args([]))
assert level is None
@@ -136,6 +158,20 @@ def test_get_level_ioerror(mocked_profile_constructor, init_statick):
args.parser.add_argument(
"--profile", dest="profile", type=str, default="profile-test.yaml"
)
+ args.parser.add_argument("--level", dest="level", type=str)
+ level = init_statick.get_level("some_package", args.get_args([]))
+ assert level is None
+
+
[email protected]("statick_tool.statick.Profile")
+def test_get_level_valueerror(mocked_profile_constructor, init_statick):
+ """Test the behavior when Profile throws a ValueError."""
+ mocked_profile_constructor.side_effect = ValueError("error")
+ args = Args("Statick tool")
+ args.parser.add_argument(
+ "--profile", dest="profile", type=str, default="profile-test.yaml"
+ )
+ args.parser.add_argument("--level", dest="level", type=str)
level = init_statick.get_level("some_package", args.get_args([]))
assert level is None
@@ -180,18 +216,6 @@ def test_custom_config_file(init_statick):
assert has_level
[email protected]("statick_tool.statick.Profile")
-def test_get_level_valueerror(mocked_profile_constructor, init_statick):
- """Test the behavior when Profile throws a ValueError."""
- mocked_profile_constructor.side_effect = ValueError("error")
- args = Args("Statick tool")
- args.parser.add_argument(
- "--profile", dest="profile", type=str, default="profile-test.yaml"
- )
- level = init_statick.get_level("some_package", args.get_args([]))
- assert level is None
-
-
@mock.patch("statick_tool.statick.Config")
def test_get_config_valueerror(mocked_config_constructor, init_statick):
"""Test the behavior when Config throws a ValueError."""
|
Support level flag
Right now a new profile file has to be created to specify the desired level to run Statick. We should add support for setting a `--level` flag that overrides the level specified in the profile file.
|
0.0
|
33f736f75604a20246d459589e3ccad51c1cfe93
|
[
"tests/statick/test_statick.py::test_get_level_cli"
] |
[
"tests/statick/test_statick.py::test_run_invalid_level",
"tests/statick/test_statick.py::test_print_exit_status_success",
"tests/statick/test_statick.py::test_get_exceptions_valueerror",
"tests/statick/test_statick.py::test_get_level_ioerror",
"tests/statick/test_statick.py::test_run_invalid_reporting_plugins",
"tests/statick/test_statick.py::test_custom_config_file",
"tests/statick/test_statick.py::test_custom_exceptions_file",
"tests/statick/test_statick.py::test_get_level_nonexistent_file",
"tests/statick/test_statick.py::test_run_workspace_output_is_not_a_directory",
"tests/statick/test_statick.py::test_run_invalid_discovery_plugin",
"tests/statick/test_statick.py::test_run_workspace_invalid_reporting_plugins",
"tests/statick/test_statick.py::test_run_invalid_tool_plugin",
"tests/statick/test_statick.py::test_run_workspace_invalid_level",
"tests/statick/test_statick.py::test_run_file_cmd_does_not_exist",
"tests/statick/test_statick.py::test_run_workspace_one_proc",
"tests/statick/test_statick.py::test_get_level",
"tests/statick/test_statick.py::test_print_logging_level",
"tests/statick/test_statick.py::test_run_workspace_packages_file",
"tests/statick/test_statick.py::test_run_package_is_ignored",
"tests/statick/test_statick.py::test_exceptions_no_file",
"tests/statick/test_statick.py::test_run_discovery_dependency",
"tests/statick/test_statick.py::test_get_config_oserror",
"tests/statick/test_statick.py::test_run_missing_path",
"tests/statick/test_statick.py::test_get_level_valueerror",
"tests/statick/test_statick.py::test_run_workspace_package_is_ignored",
"tests/statick/test_statick.py::test_run_output_is_not_directory",
"tests/statick/test_statick.py::test_run_workspace_no_reporting_plugins",
"tests/statick/test_statick.py::test_print_exit_status_errors",
"tests/statick/test_statick.py::test_run_workspace_no_packages_file",
"tests/statick/test_statick.py::test_scan_package",
"tests/statick/test_statick.py::test_gather_args",
"tests/statick/test_statick.py::test_get_config_valueerror",
"tests/statick/test_statick.py::test_get_level_non_default",
"tests/statick/test_statick.py::test_run_workspace_no_config",
"tests/statick/test_statick.py::test_print_no_issues",
"tests/statick/test_statick.py::test_run_workspace_list_packages",
"tests/statick/test_statick.py::test_run_missing_config",
"tests/statick/test_statick.py::test_run",
"tests/statick/test_statick.py::test_get_exceptions_oserror",
"tests/statick/test_statick.py::test_run_mkdir_oserror",
"tests/statick/test_statick.py::test_run_force_tool_list",
"tests/statick/test_statick.py::test_run_no_reporting_plugins",
"tests/statick/test_statick.py::test_run_workspace",
"tests/statick/test_statick.py::test_print_logging_level_invalid",
"tests/statick/test_statick.py::test_run_called_process_error",
"tests/statick/test_statick.py::test_run_workspace_max_proc"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-14 01:12:47+00:00
|
cc0-1.0
| 5,698 |
|
sscpac__statick-83
|
diff --git a/statick_tool/statick.py b/statick_tool/statick.py
index 1ca89f6..c0ab701 100644
--- a/statick_tool/statick.py
+++ b/statick_tool/statick.py
@@ -72,6 +72,8 @@ class Statick(object):
type=str, help="Force only the given list of tools to run")
args.add_argument('--version', action='version',
version='%(prog)s {version}'.format(version=__version__))
+ args.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str, help="Suffix to use when searching for CERT mapping files")
for _, plugin in list(self.discovery_plugins.items()):
plugin.gather_args(args)
diff --git a/statick_tool/tool_plugin.py b/statick_tool/tool_plugin.py
index c8f3b76..28839e3 100644
--- a/statick_tool/tool_plugin.py
+++ b/statick_tool/tool_plugin.py
@@ -36,8 +36,16 @@ class ToolPlugin(IPlugin):
def load_mapping(self):
"""Load a mapping between warnings and identifiers."""
- file_name = "plugin_mapping/%s.txt" % (self.get_name())
+ file_name = "plugin_mapping/{}.txt".format(self.get_name())
full_path = self.plugin_context.resources.get_file(file_name)
+ if self.plugin_context.args.mapping_file_suffix is not None:
+ # If the user specified a suffix, try to get the suffixed version of the file
+ suffixed_file_name = "plugin_mapping/{}-{}.txt".format(self.get_name(), self.plugin_context.args.mapping_file_suffix)
+ suffixed_full_path = self.plugin_context.resources.get_file(suffixed_file_name)
+ if suffixed_full_path is not None:
+ # If there actually is a file with that suffix, use it (else use the un-suffixed version)
+ full_path = suffixed_full_path
+
if full_path is None:
return {}
warning_mapping = {}
|
sscpac/statick
|
bab7c29993776db8f95a010f3260fc0bbc7a4569
|
diff --git a/tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py b/tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py
index 0724e8e..18006bc 100644
--- a/tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py
+++ b/tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py
@@ -19,6 +19,8 @@ def setup_bandit_tool_plugin():
arg_parser.add_argument("--show-tool-output", dest="show_tool_output",
action="store_true", help="Show tool output")
arg_parser.add_argument("--bandit-bin", dest="bandit_bin")
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str)
resources = Resources([os.path.join(os.path.dirname(statick_tool.__file__),
'plugins')])
diff --git a/tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py b/tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py
index b2dea60..6ac3733 100644
--- a/tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py
+++ b/tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py
@@ -21,6 +21,8 @@ def setup_perlcritic_tool_plugin():
arg_parser.add_argument("--show-tool-output", dest="show_tool_output",
action="store_true", help="Show tool output")
arg_parser.add_argument("--perlcritic-bin", dest="perlcritic_bin")
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str)
resources = Resources([os.path.join(os.path.dirname(statick_tool.__file__),
'plugins')])
diff --git a/tests/tool_plugin/good_config/rsc/plugin_mapping/None-experimental.txt b/tests/tool_plugin/good_config/rsc/plugin_mapping/None-experimental.txt
new file mode 100644
index 0000000..d595bf5
--- /dev/null
+++ b/tests/tool_plugin/good_config/rsc/plugin_mapping/None-experimental.txt
@@ -0,0 +1,1 @@
+b:TST2-NO
diff --git a/tests/tool_plugin/test_tool_plugin.py b/tests/tool_plugin/test_tool_plugin.py
index 10588cb..cdf2fb3 100644
--- a/tests/tool_plugin/test_tool_plugin.py
+++ b/tests/tool_plugin/test_tool_plugin.py
@@ -17,6 +17,8 @@ from statick_tool.tool_plugin import ToolPlugin
def test_tool_plugin_load_mapping_valid():
"""Test that we can load the warnings mapping."""
arg_parser = argparse.ArgumentParser()
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str)
resources = Resources([os.path.join(os.path.dirname(__file__), 'good_config')])
plugin_context = PluginContext(arg_parser.parse_args([]), resources, None)
tp = ToolPlugin()
@@ -29,6 +31,8 @@ def test_tool_plugin_load_mapping_valid():
def test_tool_plugin_load_mapping_invalid():
"""Test that we correctly skip invalid entries."""
arg_parser = argparse.ArgumentParser()
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str)
resources = Resources([os.path.join(os.path.dirname(__file__), 'bad_config')])
plugin_context = PluginContext(arg_parser.parse_args([]), resources, None)
tp = ToolPlugin()
@@ -40,6 +44,8 @@ def test_tool_plugin_load_mapping_invalid():
def test_tool_plugin_load_mapping_missing():
"""Test that we return an empty dict for missing files."""
arg_parser = argparse.ArgumentParser()
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str)
resources = Resources([os.path.join(os.path.dirname(__file__), 'missing_config')])
plugin_context = PluginContext(arg_parser.parse_args([]), resources, None)
tp = ToolPlugin()
@@ -48,6 +54,34 @@ def test_tool_plugin_load_mapping_missing():
assert not mapping
+def test_tool_plugin_load_mapping_suffixed():
+ """Test that we can load the warnings mapping with a suffix."""
+ arg_parser = argparse.ArgumentParser()
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str, default='experimental')
+ resources = Resources([os.path.join(os.path.dirname(__file__), 'good_config')])
+ plugin_context = PluginContext(arg_parser.parse_args([]), resources, None)
+ tp = ToolPlugin()
+ tp.set_plugin_context(plugin_context)
+ mapping = tp.load_mapping()
+ assert len(mapping) == 1
+ assert mapping == {'b': 'TST2-NO'}
+
+
+def test_tool_plugin_load_mapping_suffixed_fallback():
+ """Test that we fall back to the non-suffixed file if we can't find a mapping file with an appropriate suffix."""
+ arg_parser = argparse.ArgumentParser()
+ arg_parser.add_argument('--mapping-file-suffix', dest="mapping_file_suffix",
+ type=str, default='gibberish')
+ resources = Resources([os.path.join(os.path.dirname(__file__), 'good_config')])
+ plugin_context = PluginContext(arg_parser.parse_args([]), resources, None)
+ tp = ToolPlugin()
+ tp.set_plugin_context(plugin_context)
+ mapping = tp.load_mapping()
+ assert len(mapping) == 1
+ assert mapping == {'a': 'TST1-NO'}
+
+
def test_tool_plugin_get_user_flags_invalid_level():
"""Test that we return an empty list for invalid levels."""
arg_parser = argparse.ArgumentParser()
|
Add support for changing the issue file that is looked up
The idea is that there could be multiple mapping files (the use case here is that there are the "official" mapping files, based on the CMU-SEI published list, but we would like to add "unofficial" mappings which are not blessed by CMU-SEI). I'm thinking that the most straightforward approach is to support adding a suffix (e.g. findbugs-experimental.txt) and try to look that up if it exists. Shouldn't be too complicated.
|
0.0
|
bab7c29993776db8f95a010f3260fc0bbc7a4569
|
[
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_load_mapping_suffixed"
] |
[
"tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py::test_bandit_tool_plugin_found",
"tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py::test_bandit_tool_plugin_scan_valid",
"tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py::test_bandit_tool_plugin_parse_valid",
"tests/plugins/tool/bandit_tool_plugin/test_bandit_tool_plugin.py::test_bandit_tool_plugin_parse_invalid",
"tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py::test_perlcritic_tool_plugin_found",
"tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py::test_perlcritic_tool_plugin_parse_valid",
"tests/plugins/tool/perlcritic_tool_plugin/test_perlcritic_tool_plugin.py::test_perlcritic_tool_plugin_parse_invalid",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_load_mapping_valid",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_load_mapping_invalid",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_load_mapping_missing",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_load_mapping_suffixed_fallback",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_get_user_flags_invalid_level",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_get_user_flags_invalid_tool",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_get_user_flags_no_config",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_get_user_flags_valid_flags",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_valid",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_no_exe_flag",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_nonexistent",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_extension_nopathext",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_noextension_nopathext",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_extension_pathext",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_noextension_pathext",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_is_valid_executable_wrongextension_pathext",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_command_exists_fullpath",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_command_exists_shortpath_valid",
"tests/tool_plugin/test_tool_plugin.py::test_tool_plugin_command_exists_shortpath_invalid"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-20 14:39:40+00:00
|
cc0-1.0
| 5,699 |
|
stan-dev__cmdstanpy-216
|
diff --git a/cmdstanpy/__init__.py b/cmdstanpy/__init__.py
index 9f1dbbb..45dc8e6 100644
--- a/cmdstanpy/__init__.py
+++ b/cmdstanpy/__init__.py
@@ -5,7 +5,7 @@ import atexit
import shutil
import tempfile
-STANSUMMARY_STATS = [
+_STANSUMMARY_STATS = [
'Mean',
'MCSE',
'StdDev',
@@ -17,20 +17,24 @@ STANSUMMARY_STATS = [
'R_hat',
]
-TMPDIR = tempfile.mkdtemp()
+_TMPDIR = tempfile.mkdtemp()
-def cleanup_tmpdir():
- """Force deletion of TMPDIR."""
- print('deleting tmpfiles dir: {}'.format(TMPDIR))
- shutil.rmtree(TMPDIR, ignore_errors=True)
+def _cleanup_tmpdir():
+ """Force deletion of _TMPDIR."""
+ print('deleting tmpfiles dir: {}'.format(_TMPDIR))
+ shutil.rmtree(_TMPDIR, ignore_errors=True)
print('done')
-atexit.register(cleanup_tmpdir)
+atexit.register(_cleanup_tmpdir)
from .utils import set_cmdstan_path, cmdstan_path, set_make_env, install_cmdstan # noqa
from .stanfit import CmdStanMCMC, CmdStanMLE, CmdStanGQ, CmdStanVB # noqa
from .model import CmdStanModel # noqa
from ._version import __version__ # noqa
+
+__all__ = ['set_cmdstan_path', 'cmdstan_path', 'set_make_env',
+ 'install_cmdstan', 'CmdStanMCMC', 'CmdStanMLE',
+ 'CmdStanGQ', 'CmdStanVB', 'CmdStanModel']
diff --git a/cmdstanpy/stanfit.py b/cmdstanpy/stanfit.py
index 9ca97d5..33cb70e 100644
--- a/cmdstanpy/stanfit.py
+++ b/cmdstanpy/stanfit.py
@@ -11,7 +11,7 @@ from time import time
import numpy as np
import pandas as pd
-from cmdstanpy import TMPDIR
+from cmdstanpy import _TMPDIR
from cmdstanpy.utils import (
check_sampler_csv,
scan_optimize_csv,
@@ -54,7 +54,7 @@ class RunSet:
if args.output_dir is not None:
output_dir = args.output_dir
else:
- output_dir = TMPDIR
+ output_dir = _TMPDIR
self._csv_files = []
self._diagnostic_files = [None for _ in range(chains)]
@@ -77,7 +77,7 @@ class RunSet:
if args.save_diagnostics:
if args.output_dir is None:
diag_file = create_named_text_file(
- dir=TMPDIR,
+ dir=_TMPDIR,
prefix='{}-diagnostic-{}-'.format(file_basename, i + 1),
suffix='.csv',
)
@@ -202,7 +202,7 @@ class RunSet:
)
path, filename = os.path.split(self._csv_files[i])
- if path == TMPDIR: # cleanup tmpstr in filename
+ if path == _TMPDIR: # cleanup tmpstr in filename
root, ext = os.path.splitext(filename)
rlist = root.split('-')
root = '-'.join(rlist[:-1])
@@ -431,7 +431,7 @@ class CmdStanMCMC:
self.runset._args.model_name, self.runset.chains
)
tmp_csv_path = create_named_text_file(
- dir=TMPDIR, prefix=tmp_csv_file, suffix='.csv'
+ dir=_TMPDIR, prefix=tmp_csv_file, suffix='.csv'
)
cmd = [
cmd_path,
diff --git a/cmdstanpy/utils.py b/cmdstanpy/utils.py
index 5f80dac..e7dd555 100644
--- a/cmdstanpy/utils.py
+++ b/cmdstanpy/utils.py
@@ -24,7 +24,7 @@ import numpy as np
import pandas as pd
-from cmdstanpy import TMPDIR
+from cmdstanpy import _TMPDIR
EXTENSION = '.exe' if platform.system() == 'Windows' else ''
@@ -66,7 +66,7 @@ class MaybeDictToFilePath():
for obj in objs:
if isinstance(obj, dict):
data_file = create_named_text_file(
- dir=TMPDIR, prefix='', suffix='.json'
+ dir=_TMPDIR, prefix='', suffix='.json'
)
self._logger.debug('input tempfile: %s', data_file)
if any(
@@ -192,6 +192,7 @@ def cmdstan_path() -> str:
'run command line script "install_cmdstan"'
)
cmdstan = os.path.join(cmdstan_dir, latest_cmdstan)
+ os.environ['CMDSTAN'] = cmdstan
validate_cmdstan_path(cmdstan)
return cmdstan
|
stan-dev/cmdstanpy
|
301f94026d6c1c60a3510641f1cfee11560bd5f9
|
diff --git a/test/test_cmdstan_args.py b/test/test_cmdstan_args.py
index c709378..cf6f111 100644
--- a/test/test_cmdstan_args.py
+++ b/test/test_cmdstan_args.py
@@ -4,7 +4,7 @@ import os
import platform
import unittest
-from cmdstanpy import TMPDIR
+from cmdstanpy import _TMPDIR
from cmdstanpy.cmdstan_args import (
Method,
SamplerArgs,
@@ -496,7 +496,7 @@ class CmdStanArgsTest(unittest.TestCase):
# TODO: read-only dir test for Windows - set ACLs, not mode
if platform.system() == 'Darwin' or platform.system() == 'Linux':
with self.assertRaises(ValueError):
- read_only = os.path.join(TMPDIR, 'read_only')
+ read_only = os.path.join(_TMPDIR, 'read_only')
os.mkdir(read_only, mode=0o444)
CmdStanArgs(
model_name='bernoulli',
diff --git a/test/test_utils.py b/test/test_utils.py
index d319577..0b72a0f 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -10,7 +10,7 @@ import random
import numpy as np
-from cmdstanpy import TMPDIR
+from cmdstanpy import _TMPDIR
from cmdstanpy.utils import (
cmdstan_path,
set_cmdstan_path,
@@ -34,19 +34,44 @@ DATAFILES_PATH = os.path.join(HERE, 'data')
class CmdStanPathTest(unittest.TestCase):
def test_default_path(self):
- abs_rel_path = os.path.expanduser(
- os.path.join('~', '.cmdstanpy', 'cmdstan')
- )
- self.assertTrue(cmdstan_path().startswith(abs_rel_path))
+ cur_value = None
+ if 'CMDSTAN' in os.environ:
+ cur_value = os.environ['CMDSTAN']
+ try:
+ if 'CMDSTAN' in os.environ:
+ self.assertEqual(cmdstan_path(), os.environ['CMDSTAN'])
+ path = os.environ['CMDSTAN']
+ del os.environ['CMDSTAN']
+ self.assertFalse('CMDSTAN' in os.environ)
+ set_cmdstan_path(path)
+ self.assertEqual(cmdstan_path(), path)
+ self.assertTrue('CMDSTAN' in os.environ)
+ else:
+ install_dir = os.path.expanduser(
+ os.path.join('~', '.cmdstanpy')
+ )
+ install_version = os.path.expanduser(
+ os.path.join(install_dir, get_latest_cmdstan(install_dir))
+ )
+ self.assertTrue(
+ os.path.samefile(cmdstan_path(), install_version)
+ )
+ self.assertTrue('CMDSTAN' in os.environ)
+ finally:
+ if cur_value is not None:
+ os.environ['CMDSTAN'] = cur_value
+ else:
+ if 'CMDSTAN' in os.environ:
+ del os.environ['CMDSTAN']
def test_non_spaces_location(self):
- good_path = os.path.join(TMPDIR, 'good_dir')
+ good_path = os.path.join(_TMPDIR, 'good_dir')
with TemporaryCopiedFile(good_path) as (pth, is_changed):
self.assertEqual(pth, good_path)
self.assertFalse(is_changed)
# prepare files for test
- bad_path = os.path.join(TMPDIR, 'bad dir')
+ bad_path = os.path.join(_TMPDIR, 'bad dir')
os.makedirs(bad_path, exist_ok=True)
stan = os.path.join(DATAFILES_PATH, 'bernoulli.stan')
stan_bad = os.path.join(bad_path, 'bad name.stan')
@@ -70,12 +95,16 @@ class CmdStanPathTest(unittest.TestCase):
shutil.rmtree(bad_path, ignore_errors=True)
def test_set_path(self):
- install_dir = os.path.expanduser(os.path.join('~', '.cmdstanpy'))
- install_version = os.path.expanduser(
- os.path.join(install_dir, get_latest_cmdstan(install_dir))
- )
- set_cmdstan_path(install_version)
- self.assertEqual(install_version, cmdstan_path())
+ if 'CMDSTAN' in os.environ:
+ self.assertEqual(cmdstan_path(), os.environ['CMDSTAN'])
+ else:
+ install_dir = os.path.expanduser(os.path.join('~', '.cmdstanpy'))
+ install_version = os.path.expanduser(
+ os.path.join(install_dir, get_latest_cmdstan(install_dir))
+ )
+ set_cmdstan_path(install_version)
+ self.assertEqual(install_version, cmdstan_path())
+ self.assertEqual(install_version, os.environ['CMDSTAN'])
def test_validate_path(self):
install_dir = os.path.expanduser(os.path.join('~', '.cmdstanpy'))
@@ -119,32 +148,32 @@ class CmdStanPathTest(unittest.TestCase):
def test_jsondump(self):
dict_list = {'a': [1.0, 2.0, 3.0]}
- file_list = os.path.join(TMPDIR, 'list.json')
+ file_list = os.path.join(_TMPDIR, 'list.json')
jsondump(file_list, dict_list)
with open(file_list) as fd:
self.assertEqual(json.load(fd), dict_list)
dict_vec = {'a': np.repeat(3, 4)}
- file_vec = os.path.join(TMPDIR, 'vec.json')
+ file_vec = os.path.join(_TMPDIR, 'vec.json')
jsondump(file_vec, dict_vec)
with open(file_vec) as fd:
self.assertEqual(json.load(fd), dict_vec)
dict_zero_vec = {'a': []}
- file_zero_vec = os.path.join(TMPDIR, 'empty_vec.json')
+ file_zero_vec = os.path.join(_TMPDIR, 'empty_vec.json')
jsondump(file_zero_vec, dict_zero_vec)
with open(file_zero_vec) as fd:
self.assertEqual(json.load(fd), dict_zero_vec)
dict_zero_matrix = {'a': [[], [], []]}
- file_zero_matrix = os.path.join(TMPDIR, 'empty_matrix.json')
+ file_zero_matrix = os.path.join(_TMPDIR, 'empty_matrix.json')
jsondump(file_zero_matrix, dict_zero_matrix)
with open(file_zero_matrix) as fd:
self.assertEqual(json.load(fd), dict_zero_matrix)
arr = np.zeros(shape=(5, 0))
dict_zero_matrix = {'a': arr}
- file_zero_matrix = os.path.join(TMPDIR, 'empty_matrix.json')
+ file_zero_matrix = os.path.join(_TMPDIR, 'empty_matrix.json')
jsondump(file_zero_matrix, dict_zero_matrix)
with open(file_zero_matrix) as fd:
self.assertEqual(json.load(fd), dict_zero_matrix)
@@ -282,7 +311,7 @@ class WindowsShortPath(unittest.TestCase):
def test_windows_short_path_directory(self):
if platform.system() != 'Windows':
return
- original_path = os.path.join(TMPDIR, 'new path')
+ original_path = os.path.join(_TMPDIR, 'new path')
os.makedirs(original_path, exist_ok=True)
assert os.path.exists(original_path)
assert ' ' in original_path
@@ -294,7 +323,7 @@ class WindowsShortPath(unittest.TestCase):
def test_windows_short_path_file(self):
if platform.system() != 'Windows':
return
- original_path = os.path.join(TMPDIR, 'new path', 'my_file.csv')
+ original_path = os.path.join(_TMPDIR, 'new path', 'my_file.csv')
os.makedirs(os.path.split(original_path)[0], exist_ok=True)
assert os.path.exists(os.path.split(original_path)[0])
assert ' ' in original_path
@@ -309,7 +338,7 @@ class WindowsShortPath(unittest.TestCase):
"""Test that the function doesn't touch filename."""
if platform.system() != 'Windows':
return
- original_path = os.path.join(TMPDIR, 'new path', 'my file.csv')
+ original_path = os.path.join(_TMPDIR, 'new path', 'my file.csv')
os.makedirs(os.path.split(original_path)[0], exist_ok=True)
assert os.path.exists(os.path.split(original_path)[0])
assert ' ' in original_path
|
Setting CMDSTAN environment variable causes test to fail
#### Summary:
cmdstanpy properly finds cmdstan when `CMDSTAN` environment is set, but one test does fail.
#### Description:
There is a test to see that cmdstan is located at `~/.cmdstanpy/cmdstan-<version>`, but a user can change the location of cmdstan by setting `CMDSTAN` environment variable.
https://github.com/stan-dev/cmdstanpy/blob/f20c9bb9002387dfc662fe84d98d24f9df1850e8/test/test_utils.py#L35-L40
#### Current Version:
master
|
0.0
|
301f94026d6c1c60a3510641f1cfee11560bd5f9
|
[
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm",
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm_init_alpha",
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm_iter",
"test/test_cmdstan_args.py::SamplerArgsTest::test_adapt",
"test/test_cmdstan_args.py::SamplerArgsTest::test_args_chains",
"test/test_cmdstan_args.py::SamplerArgsTest::test_args_min",
"test/test_cmdstan_args.py::SamplerArgsTest::test_bad",
"test/test_cmdstan_args.py::SamplerArgsTest::test_fixed_param",
"test/test_cmdstan_args.py::SamplerArgsTest::test_good",
"test/test_cmdstan_args.py::SamplerArgsTest::test_metric",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_args_good",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_args_inits",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_compose",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_no_chains",
"test/test_cmdstan_args.py::GenerateQuantitesTest::test_args_fitted_params",
"test/test_cmdstan_args.py::VariationalTest::test_args_bad",
"test/test_cmdstan_args.py::VariationalTest::test_args_variational",
"test/test_utils.py::CmdStanPathTest::test_dict_to_file",
"test/test_utils.py::CmdStanPathTest::test_jsondump",
"test/test_utils.py::CmdStanPathTest::test_non_spaces_location",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_1",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_2",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_3",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_4",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_metric_1",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_metric_2",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_metric_3",
"test/test_utils.py::ReadStanCsvTest::test_check_sampler_csv_metric_4",
"test/test_utils.py::ReadMetricTest::test_metric_json_bad",
"test/test_utils.py::ReadMetricTest::test_metric_json_matrix",
"test/test_utils.py::ReadMetricTest::test_metric_json_vec",
"test/test_utils.py::ReadMetricTest::test_metric_missing",
"test/test_utils.py::ReadMetricTest::test_metric_rdump_bad_1",
"test/test_utils.py::ReadMetricTest::test_metric_rdump_bad_2",
"test/test_utils.py::ReadMetricTest::test_metric_rdump_matrix",
"test/test_utils.py::ReadMetricTest::test_metric_rdump_vec",
"test/test_utils.py::WindowsShortPath::test_windows_short_path_directory",
"test/test_utils.py::WindowsShortPath::test_windows_short_path_file",
"test/test_utils.py::WindowsShortPath::test_windows_short_path_file_with_space",
"test/test_utils.py::RloadTest::test_parse_rdump_value",
"test/test_utils.py::RloadTest::test_rload_bad_data_1",
"test/test_utils.py::RloadTest::test_rload_bad_data_2",
"test/test_utils.py::RloadTest::test_rload_bad_data_3",
"test/test_utils.py::RloadTest::test_rload_data",
"test/test_utils.py::RloadTest::test_rload_jags_data",
"test/test_utils.py::RloadTest::test_rload_metric",
"test/test_utils.py::RloadTest::test_rload_wrong_data",
"test/test_utils.py::RloadTest::test_roundtrip_metric"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-10 00:11:16+00:00
|
bsd-3-clause
| 5,700 |
|
stan-dev__cmdstanpy-619
|
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index f386381..a064ea2 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -10,5 +10,5 @@ Describe the issue as clearly as possible.
Provide any additional information here.
#### Current Version:
-Please include the output of `cmdstanpy.show_versions()`, or
+Please include the output of `import cmdstanpy; cmdstanpy.show_versions()`, or
at least the cmdstan and cmdstanpy versions used.
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 23f8522..5812b91 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -60,7 +60,7 @@ jobs:
pip install codecov
- name: Run flake8, pylint, mypy
- if: matrix.python-version == '3.10'
+ if: matrix.python-version == '3.10.6'
run: |
flake8 cmdstanpy test
pylint -v cmdstanpy test
diff --git a/cmdstanpy/cmdstan_args.py b/cmdstanpy/cmdstan_args.py
index 9bbec6c..2fc7526 100644
--- a/cmdstanpy/cmdstan_args.py
+++ b/cmdstanpy/cmdstan_args.py
@@ -396,7 +396,7 @@ class OptimizeArgs:
history_size: Optional[int] = None,
) -> None:
- self.algorithm = algorithm
+ self.algorithm = algorithm or ""
self.init_alpha = init_alpha
self.iter = iter
self.save_iterations = save_iterations
@@ -414,10 +414,7 @@ class OptimizeArgs:
"""
Check arguments correctness and consistency.
"""
- if (
- self.algorithm is not None
- and self.algorithm not in self.OPTIMIZE_ALGOS
- ):
+ if self.algorithm and self.algorithm not in self.OPTIMIZE_ALGOS:
raise ValueError(
'Please specify optimizer algorithms as one of [{}]'.format(
', '.join(self.OPTIMIZE_ALGOS)
@@ -425,9 +422,9 @@ class OptimizeArgs:
)
if self.init_alpha is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'init_alpha must not be set when algorithm is Newton'
+ 'init_alpha requires that algorithm be set to bfgs or lbfgs'
)
if isinstance(self.init_alpha, float):
if self.init_alpha <= 0:
@@ -443,9 +440,9 @@ class OptimizeArgs:
raise ValueError('iter must be type of int')
if self.tol_obj is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'tol_obj must not be set when algorithm is Newton'
+ 'tol_obj requires that algorithm be set to bfgs or lbfgs'
)
if isinstance(self.tol_obj, float):
if self.tol_obj <= 0:
@@ -454,9 +451,10 @@ class OptimizeArgs:
raise ValueError('tol_obj must be type of float')
if self.tol_rel_obj is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'tol_rel_obj must not be set when algorithm is Newton'
+ 'tol_rel_obj requires that algorithm be set to bfgs'
+ ' or lbfgs'
)
if isinstance(self.tol_rel_obj, float):
if self.tol_rel_obj <= 0:
@@ -465,9 +463,9 @@ class OptimizeArgs:
raise ValueError('tol_rel_obj must be type of float')
if self.tol_grad is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'tol_grad must not be set when algorithm is Newton'
+ 'tol_grad requires that algorithm be set to bfgs or lbfgs'
)
if isinstance(self.tol_grad, float):
if self.tol_grad <= 0:
@@ -476,9 +474,10 @@ class OptimizeArgs:
raise ValueError('tol_grad must be type of float')
if self.tol_rel_grad is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'tol_rel_grad must not be set when algorithm is Newton'
+ 'tol_rel_grad requires that algorithm be set to bfgs'
+ ' or lbfgs'
)
if isinstance(self.tol_rel_grad, float):
if self.tol_rel_grad <= 0:
@@ -487,9 +486,9 @@ class OptimizeArgs:
raise ValueError('tol_rel_grad must be type of float')
if self.tol_param is not None:
- if self.algorithm == 'Newton':
+ if self.algorithm.lower() not in {'lbfgs', 'bfgs'}:
raise ValueError(
- 'tol_param must not be set when algorithm is Newton'
+ 'tol_param requires that algorithm be set to bfgs or lbfgs'
)
if isinstance(self.tol_param, float):
if self.tol_param <= 0:
@@ -498,10 +497,9 @@ class OptimizeArgs:
raise ValueError('tol_param must be type of float')
if self.history_size is not None:
- if self.algorithm == 'Newton' or self.algorithm == 'BFGS':
+ if self.algorithm.lower() != 'lbfgs':
raise ValueError(
- 'history_size must not be set when algorithm is '
- 'Newton or BFGS'
+ 'history_size requires that algorithm be set to lbfgs'
)
if isinstance(self.history_size, int):
if self.history_size < 0:
diff --git a/cmdstanpy/model.py b/cmdstanpy/model.py
index 723bc7e..81e8464 100644
--- a/cmdstanpy/model.py
+++ b/cmdstanpy/model.py
@@ -210,12 +210,6 @@ class CmdStanModel:
if compile and self._exe_file is None:
self.compile(force=str(compile).lower() == 'force')
- if self._exe_file is None:
- raise ValueError(
- 'Unable to compile Stan model file: {}.'.format(
- self._stan_file
- )
- )
def __repr__(self) -> str:
repr = 'CmdStanModel: name={}'.format(self._name)
@@ -531,45 +525,26 @@ class CmdStanModel:
get_logger().info(
'compiled model executable: %s', self._exe_file
)
- if compilation_failed or 'Warning' in console:
+ if 'Warning' in console:
lines = console.split('\n')
warnings = [x for x in lines if x.startswith('Warning')]
- syntax_errors = [
- x for x in lines if x.startswith('Syntax error')
- ]
- semantic_errors = [
- x for x in lines if x.startswith('Semantic error')
- ]
- exceptions = [
- x
- for x in lines
- if 'Uncaught exception' in x or 'fatal error' in x
- ]
- if (
- len(syntax_errors) > 0
- or len(semantic_errors) > 0
- or len(exceptions) > 0
- ):
- get_logger().error('Stan program failed to compile:')
- get_logger().warning(console)
- elif len(warnings) > 0:
- get_logger().warning(
- 'Stan compiler has produced %d warnings:',
- len(warnings),
- )
- get_logger().warning(console)
- elif (
- 'PCH file' in console
- or 'model_header.hpp.gch' in console
- or 'precompiled header' in console
- ):
+ get_logger().warning(
+ 'Stan compiler has produced %d warnings:',
+ len(warnings),
+ )
+ get_logger().warning(console)
+ if compilation_failed:
+ if 'PCH' in console or 'precompiled header' in console:
get_logger().warning(
"CmdStan's precompiled header (PCH) files "
"may need to be rebuilt."
- "If your model failed to compile please run "
- "cmdstanpy.rebuild_cmdstan().\nIf the "
- "issue persists please open a bug report"
+ "Please run cmdstanpy.rebuild_cmdstan().\n"
+ "If the issue persists please open a bug report"
)
+ raise ValueError(
+ f"Failed to compile Stan model '{self._stan_file}'. "
+ f"Console:\n{console}"
+ )
def optimize(
self,
@@ -726,7 +701,9 @@ class CmdStanModel:
self._run_cmdstan(runset, dummy_chain_id, show_console=show_console)
if not runset._check_retcodes():
- msg = 'Error during optimization: {}'.format(runset.get_err_msgs())
+ msg = "Error during optimization! Command '{}' failed: {}".format(
+ ' '.join(runset.cmd(0)), runset.get_err_msgs()
+ )
if 'Line search failed' in msg and not require_converged:
get_logger().warning(msg)
else:
|
stan-dev/cmdstanpy
|
1c761ff7a1c0e597f6d67d28645432533276016e
|
diff --git a/test/test_cmdstan_args.py b/test/test_cmdstan_args.py
index ea2c4c2..39cc5ce 100644
--- a/test/test_cmdstan_args.py
+++ b/test/test_cmdstan_args.py
@@ -34,11 +34,14 @@ class OptimizeArgsTest(unittest.TestCase):
self.assertIn('algorithm=newton', ' '.join(cmd))
def test_args_algorithm_init_alpha(self):
- args = OptimizeArgs(init_alpha=2e-4)
+ args = OptimizeArgs(algorithm='bfgs', init_alpha=2e-4)
args.validate()
cmd = args.compose(None, cmd=['output'])
self.assertIn('init_alpha=0.0002', ' '.join(cmd))
+ args = OptimizeArgs(init_alpha=2e-4)
+ with self.assertRaises(ValueError):
+ args.validate()
args = OptimizeArgs(init_alpha=-1.0)
with self.assertRaises(ValueError):
args.validate()
diff --git a/test/test_model.py b/test/test_model.py
index 7144a6d..4c3e2cc 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -299,13 +299,8 @@ class CmdStanModelTest(CustomTestCase):
def test_model_syntax_error(self):
stan = os.path.join(DATAFILES_PATH, 'bad_syntax.stan')
- with LogCapture(level=logging.WARNING) as log:
- logging.getLogger()
- with self.assertRaises(ValueError):
- CmdStanModel(stan_file=stan)
- log.check_present(
- ('cmdstanpy', 'WARNING', StringComparison(r'(?s).*Syntax error.*'))
- )
+ with self.assertRaisesRegex(ValueError, r'.*Syntax error.*'):
+ CmdStanModel(stan_file=stan)
def test_repr(self):
model = CmdStanModel(stan_file=BERN_STAN)
diff --git a/test/test_optimize.py b/test/test_optimize.py
index ff62b50..3792234 100644
--- a/test/test_optimize.py
+++ b/test/test_optimize.py
@@ -432,9 +432,7 @@ class OptimizeTest(unittest.TestCase):
jdata = os.path.join(DATAFILES_PATH, 'bernoulli.data.json')
jinit = os.path.join(DATAFILES_PATH, 'bernoulli.init.json')
- with self.assertRaisesRegex(
- ValueError, 'must not be set when algorithm is Newton'
- ):
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
model.optimize(
data=jdata,
seed=1239812093,
@@ -443,9 +441,7 @@ class OptimizeTest(unittest.TestCase):
tol_obj=1,
)
- with self.assertRaisesRegex(
- ValueError, 'must not be set when algorithm is Newton'
- ):
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
model.optimize(
data=jdata,
seed=1239812093,
@@ -454,9 +450,7 @@ class OptimizeTest(unittest.TestCase):
tol_rel_obj=1,
)
- with self.assertRaisesRegex(
- ValueError, 'must not be set when algorithm is Newton'
- ):
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
model.optimize(
data=jdata,
seed=1239812093,
@@ -465,9 +459,7 @@ class OptimizeTest(unittest.TestCase):
tol_grad=1,
)
- with self.assertRaisesRegex(
- ValueError, 'must not be set when algorithm is Newton'
- ):
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
model.optimize(
data=jdata,
seed=1239812093,
@@ -476,9 +468,15 @@ class OptimizeTest(unittest.TestCase):
tol_rel_grad=1,
)
- with self.assertRaisesRegex(
- ValueError, 'must not be set when algorithm is Newton'
- ):
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
+ model.optimize(
+ data=jdata,
+ seed=1239812093,
+ inits=jinit,
+ tol_rel_grad=1,
+ )
+
+ with self.assertRaisesRegex(ValueError, 'bfgs or lbfgs'):
model.optimize(
data=jdata,
seed=1239812093,
@@ -489,7 +487,7 @@ class OptimizeTest(unittest.TestCase):
with self.assertRaisesRegex(
ValueError,
- 'history_size must not be set when algorithm is Newton or BFGS',
+ 'lbfgs',
):
model.optimize(
data=jdata,
@@ -501,7 +499,7 @@ class OptimizeTest(unittest.TestCase):
with self.assertRaisesRegex(
ValueError,
- 'history_size must not be set when algorithm is Newton or BFGS',
+ 'lbfgs',
):
model.optimize(
data=jdata,
@@ -511,6 +509,17 @@ class OptimizeTest(unittest.TestCase):
history_size=1,
)
+ with self.assertRaisesRegex(
+ ValueError,
+ 'lbfgs',
+ ):
+ model.optimize(
+ data=jdata,
+ seed=1239812093,
+ inits=jinit,
+ history_size=1,
+ )
+
def test_optimize_good_dict(self):
exe = os.path.join(DATAFILES_PATH, 'bernoulli' + EXTENSION)
stan = os.path.join(DATAFILES_PATH, 'bernoulli.stan')
|
Optimize fail to parse the tol_grad argument
Hi
I was trying to use `optimize` to acquire the map estimation of a model but when I set the tol_grad parameter:
```python
map_estimate = model.optimize(
data=args,
algorithm='lbfgs',
tol_grad=1e-20
)
```
a RuntimeError got raised:
```
tol_grad=1e-20 is either mistyped or misplaced.
Perhaps you meant one of the following valid configurations?
method=optimize optimize algorithm=bfgs bfgs tol_grad=<double>
method=optimize optimize algorithm=lbfgs lbfgs tol_grad=<double>
```
|
0.0
|
1c761ff7a1c0e597f6d67d28645432533276016e
|
[
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm_init_alpha"
] |
[
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm",
"test/test_cmdstan_args.py::OptimizeArgsTest::test_args_algorithm_iter",
"test/test_cmdstan_args.py::SamplerArgsTest::test_adapt",
"test/test_cmdstan_args.py::SamplerArgsTest::test_args_chains",
"test/test_cmdstan_args.py::SamplerArgsTest::test_args_min",
"test/test_cmdstan_args.py::SamplerArgsTest::test_bad",
"test/test_cmdstan_args.py::SamplerArgsTest::test_fixed_param",
"test/test_cmdstan_args.py::SamplerArgsTest::test_good",
"test/test_cmdstan_args.py::SamplerArgsTest::test_metric",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_args_good",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_args_inits",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_compose",
"test/test_cmdstan_args.py::CmdStanArgsTest::test_no_chains",
"test/test_cmdstan_args.py::GenerateQuantitesTest::test_args_fitted_params",
"test/test_cmdstan_args.py::VariationalTest::test_args_bad",
"test/test_cmdstan_args.py::VariationalTest::test_args_variational",
"test/test_model.py::CmdStanModelTest::test_cpp_options",
"test/test_model.py::CmdStanModelTest::test_model_file_does_not_exist",
"test/test_model.py::CmdStanModelTest::test_model_none",
"test/test_model.py::CmdStanModelTest::test_stanc_options",
"test/test_optimize.py::CmdStanMLETest::test_instantiate_from_csvfiles",
"test/test_optimize.py::CmdStanMLETest::test_instantiate_from_csvfiles_save_iterations"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-20 19:04:04+00:00
|
bsd-3-clause
| 5,701 |
|
stan-dev__cmdstanpy-663
|
diff --git a/cmdstanpy/cmdstan_args.py b/cmdstanpy/cmdstan_args.py
index 2fc7526..49b96a2 100644
--- a/cmdstanpy/cmdstan_args.py
+++ b/cmdstanpy/cmdstan_args.py
@@ -81,7 +81,7 @@ class SamplerArgs:
* if file(s) for metric are supplied, check contents.
* length of per-chain lists equals specified # of chains
"""
- if not isinstance(chains, int) or chains < 1:
+ if not isinstance(chains, (int, np.integer)) or chains < 1:
raise ValueError(
'Sampler expects number of chains to be greater than 0.'
)
@@ -110,7 +110,9 @@ class SamplerArgs:
raise ValueError(msg)
if self.iter_warmup is not None:
- if self.iter_warmup < 0 or not isinstance(self.iter_warmup, int):
+ if self.iter_warmup < 0 or not isinstance(
+ self.iter_warmup, (int, np.integer)
+ ):
raise ValueError(
'Value for iter_warmup must be a non-negative integer,'
' found {}.'.format(self.iter_warmup)
@@ -122,28 +124,30 @@ class SamplerArgs:
)
if self.iter_sampling is not None:
if self.iter_sampling < 0 or not isinstance(
- self.iter_sampling, int
+ self.iter_sampling, (int, np.integer)
):
raise ValueError(
'Argument "iter_sampling" must be a non-negative integer,'
' found {}.'.format(self.iter_sampling)
)
if self.thin is not None:
- if self.thin < 1 or not isinstance(self.thin, int):
+ if self.thin < 1 or not isinstance(self.thin, (int, np.integer)):
raise ValueError(
'Argument "thin" must be a positive integer,'
'found {}.'.format(self.thin)
)
if self.max_treedepth is not None:
if self.max_treedepth < 1 or not isinstance(
- self.max_treedepth, int
+ self.max_treedepth, (int, np.integer)
):
raise ValueError(
'Argument "max_treedepth" must be a positive integer,'
' found {}.'.format(self.max_treedepth)
)
if self.step_size is not None:
- if isinstance(self.step_size, (float, int)):
+ if isinstance(
+ self.step_size, (float, int, np.integer, np.floating)
+ ):
if self.step_size <= 0:
raise ValueError(
'Argument "step_size" must be > 0, '
@@ -178,7 +182,7 @@ class SamplerArgs:
else:
self.metric_type = 'dense_e'
self.metric_file = self.metric
- elif isinstance(self.metric, Dict):
+ elif isinstance(self.metric, dict):
if 'inv_metric' not in self.metric:
raise ValueError(
'Entry "inv_metric" not found in metric dict.'
@@ -289,7 +293,7 @@ class SamplerArgs:
)
if self.adapt_init_phase is not None:
if self.adapt_init_phase < 0 or not isinstance(
- self.adapt_init_phase, int
+ self.adapt_init_phase, (int, np.integer)
):
raise ValueError(
'Argument "adapt_init_phase" must be a non-negative '
@@ -297,7 +301,7 @@ class SamplerArgs:
)
if self.adapt_metric_window is not None:
if self.adapt_metric_window < 0 or not isinstance(
- self.adapt_metric_window, int
+ self.adapt_metric_window, (int, np.integer)
):
raise ValueError(
'Argument "adapt_metric_window" must be a non-negative '
@@ -305,7 +309,7 @@ class SamplerArgs:
)
if self.adapt_step_size is not None:
if self.adapt_step_size < 0 or not isinstance(
- self.adapt_step_size, int
+ self.adapt_step_size, (int, np.integer)
):
raise ValueError(
'Argument "adapt_step_size" must be a non-negative integer,'
@@ -426,14 +430,14 @@ class OptimizeArgs:
raise ValueError(
'init_alpha requires that algorithm be set to bfgs or lbfgs'
)
- if isinstance(self.init_alpha, float):
+ if isinstance(self.init_alpha, (float, np.floating)):
if self.init_alpha <= 0:
raise ValueError('init_alpha must be greater than 0')
else:
raise ValueError('init_alpha must be type of float')
if self.iter is not None:
- if isinstance(self.iter, int):
+ if isinstance(self.iter, (int, np.integer)):
if self.iter < 0:
raise ValueError('iter must be greater than 0')
else:
@@ -444,7 +448,7 @@ class OptimizeArgs:
raise ValueError(
'tol_obj requires that algorithm be set to bfgs or lbfgs'
)
- if isinstance(self.tol_obj, float):
+ if isinstance(self.tol_obj, (float, np.floating)):
if self.tol_obj <= 0:
raise ValueError('tol_obj must be greater than 0')
else:
@@ -456,7 +460,7 @@ class OptimizeArgs:
'tol_rel_obj requires that algorithm be set to bfgs'
' or lbfgs'
)
- if isinstance(self.tol_rel_obj, float):
+ if isinstance(self.tol_rel_obj, (float, np.floating)):
if self.tol_rel_obj <= 0:
raise ValueError('tol_rel_obj must be greater than 0')
else:
@@ -467,7 +471,7 @@ class OptimizeArgs:
raise ValueError(
'tol_grad requires that algorithm be set to bfgs or lbfgs'
)
- if isinstance(self.tol_grad, float):
+ if isinstance(self.tol_grad, (float, np.floating)):
if self.tol_grad <= 0:
raise ValueError('tol_grad must be greater than 0')
else:
@@ -479,7 +483,7 @@ class OptimizeArgs:
'tol_rel_grad requires that algorithm be set to bfgs'
' or lbfgs'
)
- if isinstance(self.tol_rel_grad, float):
+ if isinstance(self.tol_rel_grad, (float, np.floating)):
if self.tol_rel_grad <= 0:
raise ValueError('tol_rel_grad must be greater than 0')
else:
@@ -490,7 +494,7 @@ class OptimizeArgs:
raise ValueError(
'tol_param requires that algorithm be set to bfgs or lbfgs'
)
- if isinstance(self.tol_param, float):
+ if isinstance(self.tol_param, (float, np.floating)):
if self.tol_param <= 0:
raise ValueError('tol_param must be greater than 0')
else:
@@ -501,7 +505,7 @@ class OptimizeArgs:
raise ValueError(
'history_size requires that algorithm be set to lbfgs'
)
- if isinstance(self.history_size, int):
+ if isinstance(self.history_size, (int, np.integer)):
if self.history_size < 0:
raise ValueError('history_size must be greater than 0')
else:
@@ -610,52 +614,62 @@ class VariationalArgs:
)
)
if self.iter is not None:
- if self.iter < 1 or not isinstance(self.iter, int):
+ if self.iter < 1 or not isinstance(self.iter, (int, np.integer)):
raise ValueError(
'iter must be a positive integer,'
' found {}'.format(self.iter)
)
if self.grad_samples is not None:
- if self.grad_samples < 1 or not isinstance(self.grad_samples, int):
+ if self.grad_samples < 1 or not isinstance(
+ self.grad_samples, (int, np.integer)
+ ):
raise ValueError(
'grad_samples must be a positive integer,'
' found {}'.format(self.grad_samples)
)
if self.elbo_samples is not None:
- if self.elbo_samples < 1 or not isinstance(self.elbo_samples, int):
+ if self.elbo_samples < 1 or not isinstance(
+ self.elbo_samples, (int, np.integer)
+ ):
raise ValueError(
'elbo_samples must be a positive integer,'
' found {}'.format(self.elbo_samples)
)
if self.eta is not None:
- if self.eta < 0 or not isinstance(self.eta, (int, float)):
+ if self.eta < 0 or not isinstance(
+ self.eta, (int, float, np.integer, np.floating)
+ ):
raise ValueError(
'eta must be a non-negative number,'
' found {}'.format(self.eta)
)
if self.adapt_iter is not None:
- if self.adapt_iter < 1 or not isinstance(self.adapt_iter, int):
+ if self.adapt_iter < 1 or not isinstance(
+ self.adapt_iter, (int, np.integer)
+ ):
raise ValueError(
'adapt_iter must be a positive integer,'
' found {}'.format(self.adapt_iter)
)
if self.tol_rel_obj is not None:
if self.tol_rel_obj <= 0 or not isinstance(
- self.tol_rel_obj, (int, float)
+ self.tol_rel_obj, (int, float, np.integer, np.floating)
):
raise ValueError(
'tol_rel_obj must be a positive number,'
' found {}'.format(self.tol_rel_obj)
)
if self.eval_elbo is not None:
- if self.eval_elbo < 1 or not isinstance(self.eval_elbo, int):
+ if self.eval_elbo < 1 or not isinstance(
+ self.eval_elbo, (int, np.integer)
+ ):
raise ValueError(
'eval_elbo must be a positive integer,'
' found {}'.format(self.eval_elbo)
)
if self.output_samples is not None:
if self.output_samples < 1 or not isinstance(
- self.output_samples, int
+ self.output_samples, (int, np.integer)
):
raise ValueError(
'output_samples must be a positive integer,'
@@ -792,7 +806,10 @@ class CmdStanArgs:
' cannot write to dir: {}.'.format(self.output_dir)
) from exc
if self.refresh is not None:
- if not isinstance(self.refresh, int) or self.refresh < 1:
+ if (
+ not isinstance(self.refresh, (int, np.integer))
+ or self.refresh < 1
+ ):
raise ValueError(
'Argument "refresh" must be a positive integer value, '
'found {}.'.format(self.refresh)
@@ -800,7 +817,7 @@ class CmdStanArgs:
if self.sig_figs is not None:
if (
- not isinstance(self.sig_figs, int)
+ not isinstance(self.sig_figs, (int, np.integer))
or self.sig_figs < 1
or self.sig_figs > 18
):
@@ -822,13 +839,13 @@ class CmdStanArgs:
rng = RandomState()
self.seed = rng.randint(1, 99999 + 1)
else:
- if not isinstance(self.seed, (int, list)):
+ if not isinstance(self.seed, (int, list, np.integer)):
raise ValueError(
'Argument "seed" must be an integer between '
'0 and 2**32-1, found {}.'.format(self.seed)
)
- if isinstance(self.seed, int):
- if self.seed < 0 or self.seed > 2 ** 32 - 1:
+ if isinstance(self.seed, (int, np.integer)):
+ if self.seed < 0 or self.seed > 2**32 - 1:
raise ValueError(
'Argument "seed" must be an integer between '
'0 and 2**32-1, found {}.'.format(self.seed)
@@ -847,7 +864,7 @@ class CmdStanArgs:
)
)
for seed in self.seed:
- if seed < 0 or seed > 2 ** 32 - 1:
+ if seed < 0 or seed > 2**32 - 1:
raise ValueError(
'Argument "seed" must be an integer value'
' between 0 and 2**32-1,'
@@ -861,7 +878,7 @@ class CmdStanArgs:
raise ValueError('Argument "data" must be string or dict')
if self.inits is not None:
- if isinstance(self.inits, (float, int)):
+ if isinstance(self.inits, (float, int, np.floating, np.integer)):
if self.inits < 0:
raise ValueError(
'Argument "inits" must be > 0, found {}'.format(
diff --git a/cmdstanpy/compiler_opts.py b/cmdstanpy/compiler_opts.py
index 4729827..cab5d49 100644
--- a/cmdstanpy/compiler_opts.py
+++ b/cmdstanpy/compiler_opts.py
@@ -297,7 +297,10 @@ class CompilerOptions:
def compose(self) -> List[str]:
"""Format makefile options as list of strings."""
- opts = ['STANCFLAGS+=' + flag for flag in self.compose_stanc()]
+ opts = [
+ 'STANCFLAGS+=' + flag.replace(" ", "\\ ")
+ for flag in self.compose_stanc()
+ ]
if self._cpp_options is not None and len(self._cpp_options) > 0:
for key, val in self._cpp_options.items():
opts.append(f'{key}={val}')
|
stan-dev/cmdstanpy
|
087a765dbd52d71291a9988790e6587e833e230d
|
diff --git a/test/test_cmdstan_args.py b/test/test_cmdstan_args.py
index 8c6364d..049c592 100644
--- a/test/test_cmdstan_args.py
+++ b/test/test_cmdstan_args.py
@@ -6,6 +6,7 @@ import platform
from test import check_present
from time import time
+import numpy as np
import pytest
from cmdstanpy import _TMPDIR, cmdstan_path
@@ -349,6 +350,23 @@ def test_args_good() -> None:
cmd = cmdstan_args.compose_command(idx=0, csv_file='bern-output-1.csv')
assert 'id=7 random seed=' in ' '.join(cmd)
+ # integer type
+ rng = np.random.default_rng(42)
+ seed = rng.integers(low=0, high=int(1e7))
+ assert not isinstance(seed, int)
+ assert isinstance(seed, np.integer)
+
+ cmdstan_args = CmdStanArgs(
+ model_name='bernoulli',
+ model_exe=exe,
+ chain_ids=[7, 11, 18, 29],
+ data=jdata,
+ seed=seed,
+ method_args=sampler_args,
+ )
+ cmd = cmdstan_args.compose_command(idx=0, csv_file='bern-output-1.csv')
+ assert f'id=7 random seed={seed}' in ' '.join(cmd)
+
dirname = 'tmp' + str(time())
if os.path.exists(dirname):
os.rmdir(dirname)
diff --git a/test/test_model.py b/test/test_model.py
index 700e6ed..7127a8e 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -451,6 +451,35 @@ def test_model_compile_space() -> None:
assert exe_time == os.path.getmtime(model2.exe_file)
+def test_model_includes_space() -> None:
+ """Test model with include file in path with spaces."""
+ stan = os.path.join(DATAFILES_PATH, 'bernoulli_include.stan')
+ stan_divide = os.path.join(DATAFILES_PATH, 'divide_real_by_two.stan')
+
+ with tempfile.TemporaryDirectory(
+ prefix="cmdstanpy_testfolder_"
+ ) as tmp_path:
+ path_with_space = os.path.join(tmp_path, "space in path")
+ os.makedirs(path_with_space, exist_ok=True)
+ bern_stan_new = os.path.join(path_with_space, os.path.split(stan)[1])
+ stan_divide_new = os.path.join(
+ path_with_space, os.path.split(stan_divide)[1]
+ )
+ shutil.copyfile(stan, bern_stan_new)
+ shutil.copyfile(stan_divide, stan_divide_new)
+
+ model = CmdStanModel(
+ stan_file=bern_stan_new,
+ stanc_options={'include-paths': path_with_space},
+ )
+ assert "space in path" in str(model.exe_file)
+
+ assert "space in path" in model.src_info()['included_files'][0]
+ assert (
+ "divide_real_by_two.stan" in model.src_info()['included_files'][0]
+ )
+
+
def test_model_includes_explicit() -> None:
if os.path.exists(BERN_EXE):
os.remove(BERN_EXE)
|
Seed argument doesn't accept np.int types
#### Summary:
ValueError: Argument "seed" must be an integer between 0 and 2**32-1, found 76113.
I believe that 76113 < 2**32-1 (= 4294967295)
Any help?
#### Current Version:
cmdstan 2.29.0
cmdstanpy 1.0.8
|
0.0
|
087a765dbd52d71291a9988790e6587e833e230d
|
[
"test/test_cmdstan_args.py::test_args_good"
] |
[
"test/test_cmdstan_args.py::test_args_algorithm",
"test/test_cmdstan_args.py::test_args_algorithm_init_alpha",
"test/test_cmdstan_args.py::test_args_algorithm_iter",
"test/test_cmdstan_args.py::test_args_min",
"test/test_cmdstan_args.py::test_args_chains",
"test/test_cmdstan_args.py::test_good",
"test/test_cmdstan_args.py::test_bad",
"test/test_cmdstan_args.py::test_adapt",
"test/test_cmdstan_args.py::test_metric",
"test/test_cmdstan_args.py::test_fixed_param",
"test/test_cmdstan_args.py::test_compose",
"test/test_cmdstan_args.py::test_no_chains",
"test/test_cmdstan_args.py::test_args_inits",
"test/test_cmdstan_args.py::test_args_fitted_params",
"test/test_cmdstan_args.py::test_args_variational",
"test/test_cmdstan_args.py::test_variational_args_bad",
"test/test_model.py::test_stanc_options",
"test/test_model.py::test_cpp_options",
"test/test_model.py::test_model_none",
"test/test_model.py::test_model_file_does_not_exist",
"test/test_model.py::test_model_syntax_error_without_compile"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-24 17:31:08+00:00
|
bsd-3-clause
| 5,702 |
|
stan-dev__pystan-215
|
diff --git a/doc/index.rst b/doc/index.rst
index e28170e..74b80c7 100644
--- a/doc/index.rst
+++ b/doc/index.rst
@@ -79,4 +79,5 @@ Documentation
installation
upgrading
reference
+ plugins
contributing
diff --git a/doc/plugins.rst b/doc/plugins.rst
new file mode 100644
index 0000000..66edb22
--- /dev/null
+++ b/doc/plugins.rst
@@ -0,0 +1,60 @@
+=========
+ Plugins
+=========
+
+This is a guide to installing and creating plugins for PyStan.
+
+Installing Plugins
+==================
+
+In order to use a plugin, you need to install it. Plugins are published on PyPI and can be installed with ``pip``.
+
+Plugins are automatically enabled as soon as they are installed.
+
+Creating Plugins
+================
+
+Plugin developers should create a class which subclasses :py:class:`stan.plugins.PluginBase`. This
+class must be referenced in their package's entry points section.
+
+For example, if the class is ``mymodule.PrintParameterNames`` then the
+setuptools configuration would look like the following::
+
+ entry_points = {
+ "stan.plugins": [
+ "names = mymodule:PrintParameterNames"
+ ]
+ }
+
+The equivalent configuration in poetry would be::
+
+ [tool.poetry.plugins."stan.plugins"]
+ names = mymodule:PrintParameterNames
+
+You can define multiple plugins in the entry points section. Note that the
+plugin name (here, `names`) is required but is unused.
+
+All :py:class:`stan.plugins.PluginBase` subclasses implement methods which define behavior associated with *events*.
+Currently, there is only one event supported, ``post_fit``.
+
+on_post_fit
+-----------
+
+This method defines what happens when sampling has finished and a
+:py:class:`stan.fit.Fit` object is about to be returned to the user. The
+method takes a :py:class:`stan.fit.Fit` instance as an argument. The method
+returns the instance. In a plugin, this method will typically analyze the data contained in
+the instance. A plugin might also use this method to modify the instance, adding an
+additional method or changing the behavior or an existing method.
+
+**Arguments:**
+
+- ``fit``: :py:class:`stan.fit.Fit` instance
+
+For example, if you wanted to print the names of parameters you would define a plugin as follows::
+
+ class PrintParameterNames(stan.plugins.PluginBase):
+ def on_post_fit(self, fit):
+ for key in fit:
+ print(key)
+ return fit
diff --git a/doc/reference.rst b/doc/reference.rst
index a472350..97be599 100644
--- a/doc/reference.rst
+++ b/doc/reference.rst
@@ -10,3 +10,6 @@ API Reference
.. automodule:: stan.model
:members: Model
+
+.. automodule:: stan.plugins
+ :members: PluginBase
diff --git a/stan/model.py b/stan/model.py
index fdd0c64..c8101d8 100644
--- a/stan/model.py
+++ b/stan/model.py
@@ -17,6 +17,7 @@ from clikit.ui.components import ProgressBar
import stan.common
import stan.fit
+import stan.plugins
def _make_json_serializable(data: dict) -> dict:
@@ -223,7 +224,7 @@ class Model:
progress_bar.finish()
io.error_line("\n<info>Done.</info>")
- return stan.fit.Fit(
+ fit = stan.fit.Fit(
stan_outputs,
num_chains,
self.param_names,
@@ -235,6 +236,11 @@ class Model:
save_warmup,
)
+ for entry_point in stan.plugins.get_plugins():
+ Plugin = entry_point.load()
+ fit = Plugin().on_post_fit(fit)
+ return fit
+
try:
return asyncio.run(go())
except KeyboardInterrupt:
diff --git a/stan/plugins.py b/stan/plugins.py
new file mode 100644
index 0000000..27715f3
--- /dev/null
+++ b/stan/plugins.py
@@ -0,0 +1,44 @@
+import abc
+from typing import Generator
+
+import pkg_resources
+
+import stan.fit
+
+
+def get_plugins() -> Generator[pkg_resources.EntryPoint, None, None]:
+ """Iterate over available plugins."""
+ return pkg_resources.iter_entry_points(group="stan.plugins")
+
+
+class PluginBase(abc.ABC):
+ """Base class for PyStan plugins.
+
+ Plugin developers should create a class which subclasses `PluginBase`.
+ This class must be referenced in their package's entry points section.
+
+ """
+
+ # Implementation note: this plugin system is simple because there are only
+ # a couple of places a plugin developer might want to change behavior. For
+ # a more full-featured plugin system, see Stevedore
+ # (<https://docs.openstack.org/stevedore>). This plugin system follows
+ # (approximately) the pattern stevedore labels `ExtensionManager`.
+
+ def on_post_fit(self, fit: stan.fit.Fit) -> stan.fit.Fit:
+ """Called with Fit instance when sampling has finished.
+
+ The plugin can report information about the samples
+ contained in the Fit object. It may also add to or
+ modify the Fit instance.
+
+ If the plugin only analyzes the contents of `fit`,
+ it must return the `fit`.
+
+ Argument:
+ fit: Fit instance.
+
+ Returns:
+ The Fit instance.
+ """
+ return fit
|
stan-dev/pystan
|
eabb3c8e5f1981d5d02691dec347d8e1a16c1a3b
|
diff --git a/tests/test_plugins.py b/tests/test_plugins.py
new file mode 100644
index 0000000..f5e525e
--- /dev/null
+++ b/tests/test_plugins.py
@@ -0,0 +1,78 @@
+import pkg_resources
+import pytest
+
+import stan
+import stan.plugins
+
+program_code = "parameters {real y;} model {y ~ normal(0,1);}"
+
+
+class DummyPlugin(stan.plugins.PluginBase):
+ def on_post_fit(self, fit):
+ """Do nothing other than print a string."""
+ print("In DummyPlugin `on_post_fit`.")
+ return fit
+
+
+class MockEntryPoint:
+ @staticmethod
+ def load():
+ return DummyPlugin
+
+
+def mock_iter_entry_points(group):
+ return iter([MockEntryPoint])
+
+
[email protected](scope="module")
+def normal_posterior():
+ return stan.build(program_code)
+
+
+def test_get_plugins(monkeypatch):
+
+ monkeypatch.setattr(pkg_resources, "iter_entry_points", mock_iter_entry_points)
+
+ entry_points = stan.plugins.get_plugins()
+ Plugin = next(entry_points).load()
+ assert isinstance(Plugin(), stan.plugins.PluginBase)
+
+
+def test_dummy_plugin(monkeypatch, capsys, normal_posterior):
+
+ monkeypatch.setattr(pkg_resources, "iter_entry_points", mock_iter_entry_points)
+
+ fit = normal_posterior.sample(stepsize=0.001)
+ assert fit is not None and "y" in fit
+
+ captured = capsys.readouterr()
+ assert "In DummyPlugin" in captured.out
+
+
+class OtherDummyPlugin(stan.plugins.PluginBase):
+ def on_post_fit(self, fit):
+ """Do nothing other than print a string."""
+ print("In OtherDummyPlugin `on_post_fit`.")
+ return fit
+
+
+class OtherMockEntryPoint:
+ @staticmethod
+ def load():
+ return OtherDummyPlugin
+
+
+def test_two_plugins(monkeypatch, capsys, normal_posterior):
+ """Make sure that both plugins are used."""
+
+ def mock_iter_entry_points(group):
+ return iter([MockEntryPoint, OtherMockEntryPoint])
+
+ monkeypatch.setattr(pkg_resources, "iter_entry_points", mock_iter_entry_points)
+
+ fit = normal_posterior.sample(stepsize=0.001)
+ assert fit is not None and "y" in fit
+
+ captured = capsys.readouterr()
+ assert "In DummyPlugin" in captured.out
+ assert "In OtherDummyPlugin" in captured.out
|
Plugin interface is missing
Functionality not provided by the stan::services function (e.g., hmc_nuts_diag_e_adapt) will not be provided by pystan 3. Such functionality can, however, be provided by a plugin. Everyone makes a plugin framework available these days. pytest is a good example. pystan needs to add one.
Mentioned in the beta 1 announcement: https://discourse.mc-stan.org/t/finalizing-the-interface-guidelines-design-doc/16482
|
0.0
|
eabb3c8e5f1981d5d02691dec347d8e1a16c1a3b
|
[
"tests/test_plugins.py::test_get_plugins",
"tests/test_plugins.py::test_dummy_plugin",
"tests/test_plugins.py::test_two_plugins"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-19 12:10:37+00:00
|
isc
| 5,703 |
|
stan-dev__pystan-257
|
diff --git a/doc/plugins.rst b/doc/plugins.rst
index b4716f3..e2d803e 100644
--- a/doc/plugins.rst
+++ b/doc/plugins.rst
@@ -37,10 +37,10 @@ You can define multiple plugins in the entry points section. Note that the
plugin name (here, `names`) is required but is unused.
All :py:class:`stan.plugins.PluginBase` subclasses implement methods which define behavior associated with *events*.
-Currently, there is only one event supported, ``post_fit``.
+There is only one event supported, ``post_sample``.
-on_post_fit
------------
+on_post_sample
+--------------
This method defines what happens when sampling has finished and a
:py:class:`stan.fit.Fit` object is about to be returned to the user. The
@@ -56,7 +56,11 @@ additional method or changing the behavior or an existing method.
For example, if you wanted to print the names of parameters you would define a plugin as follows::
class PrintParameterNames(stan.plugins.PluginBase):
- def on_post_fit(self, fit):
+ def on_post_sample(self, fit, **kwargs):
for key in fit:
print(key)
return fit
+
+Note that `on_post_sample` accepts additional keyword arguments (``**kwargs``). Accepting
+keyword arguments like this will allow your plugin to be compatible with future versions of the package.
+Future versions of the package could, in principle, add additional arguments to `on_post_sample`.
diff --git a/stan/model.py b/stan/model.py
index ebed1cb..de8cd92 100644
--- a/stan/model.py
+++ b/stan/model.py
@@ -271,7 +271,7 @@ class Model:
for entry_point in stan.plugins.get_plugins():
Plugin = entry_point.load()
- fit = Plugin().on_post_fit(fit)
+ fit = Plugin().on_post_sample(fit)
return fit
try:
diff --git a/stan/plugins.py b/stan/plugins.py
index 27715f3..0a59d43 100644
--- a/stan/plugins.py
+++ b/stan/plugins.py
@@ -25,7 +25,7 @@ class PluginBase(abc.ABC):
# (<https://docs.openstack.org/stevedore>). This plugin system follows
# (approximately) the pattern stevedore labels `ExtensionManager`.
- def on_post_fit(self, fit: stan.fit.Fit) -> stan.fit.Fit:
+ def on_post_sample(self, fit: stan.fit.Fit) -> stan.fit.Fit:
"""Called with Fit instance when sampling has finished.
The plugin can report information about the samples
|
stan-dev/pystan
|
08dc3da6713ad9e8419df3ac2d1f11eb6cc293db
|
diff --git a/tests/test_plugins.py b/tests/test_plugins.py
index f5e525e..628296c 100644
--- a/tests/test_plugins.py
+++ b/tests/test_plugins.py
@@ -8,9 +8,9 @@ program_code = "parameters {real y;} model {y ~ normal(0,1);}"
class DummyPlugin(stan.plugins.PluginBase):
- def on_post_fit(self, fit):
+ def on_post_sample(self, fit, **kwargs):
"""Do nothing other than print a string."""
- print("In DummyPlugin `on_post_fit`.")
+ print("In DummyPlugin `on_post_sample`.")
return fit
@@ -50,9 +50,9 @@ def test_dummy_plugin(monkeypatch, capsys, normal_posterior):
class OtherDummyPlugin(stan.plugins.PluginBase):
- def on_post_fit(self, fit):
+ def on_post_sample(self, fit, **kwargs):
"""Do nothing other than print a string."""
- print("In OtherDummyPlugin `on_post_fit`.")
+ print("In OtherDummyPlugin `on_post_sample`.")
return fit
|
Plugin hook name should be `on_post_sample`
I'm not sure what I was thinking when I called the hook `on_post_fit`. We don't use `fit` as a verb anywhere.
I think we should just change this. There are, to my knowledge, zero plugins which will have to adapt to the change.
|
0.0
|
08dc3da6713ad9e8419df3ac2d1f11eb6cc293db
|
[
"tests/test_plugins.py::test_dummy_plugin",
"tests/test_plugins.py::test_two_plugins"
] |
[
"tests/test_plugins.py::test_get_plugins"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-29 18:13:17+00:00
|
isc
| 5,704 |
|
stan-dev__pystan-327
|
diff --git a/stan/model.py b/stan/model.py
index 90fc774..8e064a3 100644
--- a/stan/model.py
+++ b/stan/model.py
@@ -24,6 +24,9 @@ class DataJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
+ # unofficially support np.int64, np.int32, etc.
+ if hasattr(obj, "dtype") and np.issubdtype(obj.dtype, np.integer):
+ return int(obj)
return json.JSONEncoder.default(self, obj)
|
stan-dev/pystan
|
3cb19f67b2d103c31bde81f353be21b3f9d15f5d
|
diff --git a/tests/test_numpy_data.py b/tests/test_numpy_data.py
new file mode 100644
index 0000000..b6d91ab
--- /dev/null
+++ b/tests/test_numpy_data.py
@@ -0,0 +1,33 @@
+import numpy as np
+import pytest
+
+import stan
+
+program_code = """
+ data {
+ int<lower=0> N;
+ int<lower=0,upper=1> y[N];
+ }
+ parameters {
+ real<lower=0,upper=1> theta;
+ }
+ model {
+ for (n in 1:N)
+ y[n] ~ bernoulli(theta);
+ }
+ """
+
+
+def test_unsupported_type():
+ data = {"N": np.float32(10), "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
+ with pytest.raises(TypeError, match="Object of type float32 is not JSON serializable"):
+ stan.build(program_code, data=data, random_seed=1)
+
+
+def test_numpy_integer_types():
+ data = {"N": np.int64(10), "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
+ assert stan.build(program_code, data=data, random_seed=1) is not None
+ data = {"N": np.int32(10), "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
+ assert stan.build(program_code, data=data, random_seed=1) is not None
+ data = {"N": np.int16(10), "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
+ assert stan.build(program_code, data=data, random_seed=1) is not None
|
numpy int32 and int64 should be silently converted to Python int before sending to Stan
At least two users have complained about this. The following behavior makes me very sympathetic:
```
import numpy as np
x = np.ones(3)
x.sum().astype(int).dtype # int64!
```
See https://discourse.mc-stan.org/t/typeerror-object-of-type-int64-is-not-json-serializable/24497 for one of the issue reports.
The conversion itself isn't problematic. Python's int type has no problem dealing with a 64-bit integer.
|
0.0
|
3cb19f67b2d103c31bde81f353be21b3f9d15f5d
|
[
"tests/test_numpy_data.py::test_numpy_integer_types"
] |
[
"tests/test_numpy_data.py::test_unsupported_type"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-26 17:19:59+00:00
|
isc
| 5,705 |
|
stan-dev__pystan-367
|
diff --git a/stan/fit.py b/stan/fit.py
index 69db205..98fcb8a 100644
--- a/stan/fit.py
+++ b/stan/fit.py
@@ -1,5 +1,6 @@
import collections
import json
+from math import ceil
from typing import Generator, Tuple, cast
import numpy as np
@@ -41,6 +42,8 @@ class Fit(collections.abc.Mapping):
constrained_param_names,
)
self.num_warmup, self.num_samples = num_warmup, num_samples
+ if not isinstance(num_thin, int):
+ raise ValueError(f"{type(num_thin)} object cannot be interpreted as an integer: num_thin={num_thin}")
self.num_thin, self.save_warmup = num_thin, save_warmup
# `self.sample_and_sampler_param_names` collects the sample and sampler param names.
@@ -51,7 +54,9 @@ class Fit(collections.abc.Mapping):
num_flat_params = sum(np.product(dims_ or 1) for dims_ in dims) # if dims == [] then it is a scalar
assert num_flat_params == len(constrained_param_names)
- num_samples_saved = (self.num_samples + self.num_warmup * self.save_warmup) // self.num_thin
+ num_samples_saved = ceil(self.num_samples / self.num_thin) + ceil(
+ (self.num_warmup * self.save_warmup) / self.num_thin
+ )
# self._draws holds all the draws. We cannot allocate it before looking at the draws
# because we do not know how many sampler-specific parameters are present. Later in this
@@ -124,7 +129,7 @@ class Fit(collections.abc.Mapping):
param_indexes = self._parameter_indexes(param)
param_dim = [] if param in self.sample_and_sampler_param_names else self.dims[self.param_names.index(param)]
# fmt: off
- num_samples_saved = (self.num_samples + self.num_warmup * self.save_warmup) // self.num_thin
+ num_samples_saved = ceil(self.num_samples / self.num_thin) + ceil((self.num_warmup * self.save_warmup) / self.num_thin)
assert self._draws.shape == (len(self.sample_and_sampler_param_names) + len(self.constrained_param_names), num_samples_saved, self.num_chains)
# fmt: on
if not len(param_indexes):
|
stan-dev/pystan
|
6c99da9c00e44f5b59ae30379378e0e5f9a01fa7
|
diff --git a/tests/test_basic_bernoulli.py b/tests/test_basic_bernoulli.py
index 735ae90..c467531 100644
--- a/tests/test_basic_bernoulli.py
+++ b/tests/test_basic_bernoulli.py
@@ -42,8 +42,8 @@ def test_bernoulli_fixed_param(posterior):
def test_bernoulli_sampling_invalid_argument(posterior):
- with pytest.raises(TypeError, match=r"'float' object cannot be interpreted as an integer"):
- posterior.sample(num_thin=2.0)
+ with pytest.raises(ValueError, match="<class 'float'> object cannot be interpreted as an integer"):
+ posterior.sample(num_thin=2.5)
def test_bernoulli_sampling(fit):
diff --git a/tests/test_normal.py b/tests/test_normal.py
index 07bcbb4..5520b6a 100644
--- a/tests/test_normal.py
+++ b/tests/test_normal.py
@@ -1,3 +1,5 @@
+from math import ceil
+
import stan
@@ -41,7 +43,7 @@ def test_normal_sample_args():
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
posterior = stan.build(program_code, random_seed=1)
assert posterior is not None
- fit = posterior.sample(num_samples=350, num_thin=2)
+ fit = posterior.sample(num_samples=350, num_warmup=350, num_thin=3, save_warmup=True)
df = fit.to_frame()
- assert len(df["y"]) == 350 * 4 // 2
+ assert len(df["y"]) == ceil(350 / 3) * 2 * 4
assert -5 < df["y"].mean() < 5
|
Error in formula for `num_samples_save` in `fit.py`
#### Describe the bug
Currently defined formula is right only on even number of samples.
num_samples_saved = (self.num_samples + self.num_warmup * self.save_warmup) // self.num_thin
In `stan` C++ the samples are created with a `for` -loop in [`stan/services/util/generate_transitions.hpp`](https://github.com/stan-dev/stan/blob/develop/src/stan/services/util/generate_transitions.hpp) for both `num_warmup` and `num_samples` as `num_iterations`
```
for (int m = 0; m < num_iterations; ++m) {
...
if (save && ((m % num_thin) == 0)) {
...
}
}
```
the correct formula is
from math import ceil
...
num_samples_saved = ceil(self.num_samples / self.num_thin) + ceil((self.num_warmup * self.save_warmup) / self.num_thin)
#### Steps/Code to Reproduce
```python
import stan
schools_code = """
data {
int<lower=0> J; // number of schools
real y[J]; // estimated treatment effects
real<lower=0> sigma[J]; // standard error of effect estimates
}
parameters {
real mu; // population treatment effect
real<lower=0> tau; // standard deviation in treatment effects
vector[J] eta; // unscaled deviation from mu by school
}
transformed parameters {
vector[J] theta = mu + tau * eta; // school treatment effects
}
model {
target += normal_lpdf(eta | 0, 1); // prior log-density
target += normal_lpdf(y | theta, sigma); // log-likelihood
}
"""
schools_data = {"J": 8,
"y": [28, 8, -3, 7, -1, 1, 18, 12],
"sigma": [15, 10, 16, 11, 9, 11, 10, 18]}
posterior = stan.build(schools_code, data=schools_data)
fit = posterior.sample(num_chains=1, num_samples=100, num_warmup=100, num_thin=3, save_warmup=True)
eta = fit["eta"] # array with shape (8, 68) <- original formula gives (8, 66) and raises IndexError
```
|
0.0
|
6c99da9c00e44f5b59ae30379378e0e5f9a01fa7
|
[
"tests/test_basic_bernoulli.py::test_bernoulli_sampling_invalid_argument"
] |
[
"tests/test_basic_bernoulli.py::test_bernoulli_sampling_thin",
"tests/test_basic_bernoulli.py::test_bernoulli_fixed_param",
"tests/test_basic_bernoulli.py::test_bernoulli_sampling",
"tests/test_basic_bernoulli.py::test_bernoulli_get_item",
"tests/test_basic_bernoulli.py::test_bernoulli_random_seed",
"tests/test_basic_bernoulli.py::test_bernoulli_random_seed_same",
"tests/test_basic_bernoulli.py::test_bernoulli_random_seed_different",
"tests/test_basic_bernoulli.py::test_bernoulli_different_chains",
"tests/test_normal.py::test_normal_build"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-07 20:53:09+00:00
|
isc
| 5,706 |
|
steemit__hivemind-180
|
diff --git a/hive/utils/post.py b/hive/utils/post.py
index a1e5a14..562b518 100644
--- a/hive/utils/post.py
+++ b/hive/utils/post.py
@@ -19,10 +19,13 @@ def post_basic(post):
pass
thumb_url = ''
- if md and 'image' in md and md['image']:
- thumb_url = safe_img_url(first(md['image'])) or ''
- if thumb_url:
- md['image'] = [thumb_url]
+ if md and 'image' in md:
+ if md['image']:
+ if not isinstance(md['image'], list):
+ md['image'] = [md['image']]
+ md['image'] = list(filter(None, map(safe_img_url, md['image'])))
+ if md['image']:
+ thumb_url = md['image'][0]
else:
del md['image']
|
steemit/hivemind
|
dcb177937578b59bd6471e654654532e58adc170
|
diff --git a/tests/utils/test_utils_post.py b/tests/utils/test_utils_post.py
index 21b0dca..58332e9 100644
--- a/tests/utils/test_utils_post.py
+++ b/tests/utils/test_utils_post.py
@@ -62,7 +62,7 @@ POST_1 = {
"curator_payout_value": "0.000 SBD",
"depth": 0,
"id": 4437869,
- "json_metadata": "{\"tags\":[\"spam\"],\"image\":[\"https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg\"],\"app\":\"steemit/0.1\",\"format\":\"markdown\"}",
+ "json_metadata": "{\"tags\":[\"spam\"],\"image\":[\"ddd\", \"https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg\",\"https://example.com/image.jpg\"],\"app\":\"steemit/0.1\",\"format\":\"markdown\"}",
"last_payout": "2017-06-27T15:53:51",
"last_update": "2017-06-20T15:53:51",
"max_accepted_payout": "1000000.000 SBD",
@@ -91,7 +91,7 @@ POST_1 = {
def test_post_basic():
ret = post_basic(POST_1)
- expect = {'json_metadata': {'tags': ['spam'], 'image': ['https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg'], 'app': 'steemit/0.1', 'format': 'markdown'},
+ expect = {'json_metadata': {'tags': ['spam'], 'image': ['https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg', 'https://example.com/image.jpg'], 'app': 'steemit/0.1', 'format': 'markdown'},
'image': 'https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg',
'tags': {'spam'},
'is_nsfw': False,
|
serve full json_metadata
Currently hivemind serves a filtered version of json_metadata; for compatibility it should just continue serve full json for now, as per the steemd API it replaces.
|
0.0
|
dcb177937578b59bd6471e654654532e58adc170
|
[
"tests/utils/test_utils_post.py::test_post_basic"
] |
[
"tests/utils/test_utils_post.py::test_post_legacy",
"tests/utils/test_utils_post.py::test_post_payout",
"tests/utils/test_utils_post.py::test_post_stats"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-01-25 17:29:55+00:00
|
mit
| 5,707 |
|
steemit__hivemind-188
|
diff --git a/hive/indexer/cached_post.py b/hive/indexer/cached_post.py
index 53a6ad0..f731b41 100644
--- a/hive/indexer/cached_post.py
+++ b/hive/indexer/cached_post.py
@@ -470,17 +470,18 @@ class CachedPost:
@classmethod
def _tag_sqls(cls, pid, tags, diff=True):
"""Generate SQL "deltas" for a post_id's associated tags."""
+ next_tags = set(tags)
curr_tags = set()
if diff:
sql = "SELECT tag FROM hive_post_tags WHERE post_id = :id"
curr_tags = set(DB.query_col(sql, id=pid))
- to_rem = (curr_tags - tags)
+ to_rem = (curr_tags - next_tags)
if to_rem:
sql = "DELETE FROM hive_post_tags WHERE post_id = :id AND tag IN :tags"
yield (sql, dict(id=pid, tags=tuple(to_rem)))
- to_add = (tags - curr_tags)
+ to_add = (next_tags - curr_tags)
if to_add:
params = _keyify(to_add)
vals = ["(:id, :%s)" % key for key in params.keys()]
diff --git a/hive/utils/post.py b/hive/utils/post.py
index 562b518..87e5dfe 100644
--- a/hive/utils/post.py
+++ b/hive/utils/post.py
@@ -3,7 +3,7 @@
import math
import ujson as json
-from funcy.seqs import first
+from funcy.seqs import first, distinct
from hive.utils.normalize import sbd_amount, rep_log10, safe_img_url, parse_time, utc_timestamp
@@ -33,8 +33,9 @@ def post_basic(post):
tags = [post['category']]
if md and 'tags' in md and isinstance(md['tags'], list):
tags = tags + md['tags']
- tags = set(list(map(lambda tag: (str(tag) or '').strip('# ').lower()[:32], tags))[0:5])
- tags.discard('')
+ tags = map(lambda tag: (str(tag) or '').strip('# ').lower()[:32], tags)
+ tags = filter(None, tags)
+ tags = list(distinct(tags))[:5]
is_nsfw = 'nsfw' in tags
body = post['body']
|
steemit/hivemind
|
a96b77f9a4cc0f07e2eb1376c9d5a61016f9bbc2
|
diff --git a/tests/utils/test_utils_post.py b/tests/utils/test_utils_post.py
index 58332e9..8c61014 100644
--- a/tests/utils/test_utils_post.py
+++ b/tests/utils/test_utils_post.py
@@ -89,11 +89,59 @@ POST_1 = {
"vote_rshares": 0
}
+POST_2 = {
+ "abs_rshares": 0,
+ "active": "2017-06-20T15:53:51",
+ "active_votes": [],
+ "allow_curation_rewards": True,
+ "allow_replies": True,
+ "allow_votes": True,
+ "author": "test-safari",
+ "author_reputation": "468237543674",
+ "author_rewards": 23,
+ "beneficiaries": [],
+ "body": "https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg",
+ "body_length": 0,
+ "cashout_time": "1969-12-31T23:59:59",
+ "category": "steemit",
+ "children": 0,
+ "children_abs_rshares": 0,
+ "created": "2017-06-20T15:53:51",
+ "curator_payout_value": "0.000 SBD",
+ "depth": 0,
+ "id": 4437869,
+ "json_metadata": "{\"tags\":[\"steemit\",\"steem\",\"\",\"abc\",\"bcd\",\"cde\"]}",
+ "last_payout": "2017-06-27T15:53:51",
+ "last_update": "2017-06-20T15:53:51",
+ "max_accepted_payout": "1000000.000 SBD",
+ "max_cashout_time": "1969-12-31T23:59:59",
+ "net_rshares": 0,
+ "net_votes": 4,
+ "parent_author": "",
+ "parent_permlink": "spam",
+ "pending_payout_value": "0.000 SBD",
+ "percent_steem_dollars": 10000,
+ "permlink": "june-spam",
+ "promoted": "0.000 SBD",
+ "reblogged_by": [],
+ "replies": [],
+ "reward_weight": 10000,
+ "root_author": "test-safari",
+ "root_permlink": "june-spam",
+ "root_title": "June Spam",
+ "title": "June Spam",
+ "total_payout_value": "0.044 SBD",
+ "total_pending_payout_value": "0.000 STEEM",
+ "total_vote_weight": 0,
+ "url": "/spam/@test-safari/june-spam",
+ "vote_rshares": 0
+}
+
def test_post_basic():
ret = post_basic(POST_1)
expect = {'json_metadata': {'tags': ['spam'], 'image': ['https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg', 'https://example.com/image.jpg'], 'app': 'steemit/0.1', 'format': 'markdown'},
'image': 'https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg',
- 'tags': {'spam'},
+ 'tags': ['spam'],
'is_nsfw': False,
'body': 'https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg',
'preview': 'https://pbs.twimg.com/media/DBgNm3jXoAAioyE.jpg',
@@ -103,6 +151,11 @@ def test_post_basic():
'is_full_power': False}
assert ret == expect
+def test_post_basic_tags():
+ tags = post_basic(POST_2)['tags']
+ expected = ['steemit', 'steem', 'abc', 'bcd', 'cde']
+ assert tags == expected, "got %s" % tags
+
def test_post_legacy():
ret = post_legacy(POST_1)
expect = {'allow_curation_rewards': True,
|
only first 4 tags are indexed
The symptoms described in this post have been confirmed; PR incoming.
https://steemit.com/steemit/@free-reign/5th-tag-doesn-t-seem-to-be-getting-posts-like-the-other-4-anymore
|
0.0
|
a96b77f9a4cc0f07e2eb1376c9d5a61016f9bbc2
|
[
"tests/utils/test_utils_post.py::test_post_basic",
"tests/utils/test_utils_post.py::test_post_basic_tags"
] |
[
"tests/utils/test_utils_post.py::test_post_legacy",
"tests/utils/test_utils_post.py::test_post_payout",
"tests/utils/test_utils_post.py::test_post_stats"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-04 17:30:42+00:00
|
mit
| 5,708 |
|
steemit__hivemind-255
|
diff --git a/hive/indexer/accounts.py b/hive/indexer/accounts.py
index 3c8de1b..485320c 100644
--- a/hive/indexer/accounts.py
+++ b/hive/indexer/accounts.py
@@ -186,6 +186,7 @@ class Accounts:
# pull out valid profile md and delete the key
profile = safe_profile_metadata(account)
del account['json_metadata']
+ del account['posting_json_metadata']
active_at = max(account['created'],
account['last_account_update'],
diff --git a/hive/utils/account.py b/hive/utils/account.py
index fe1302d..caf3830 100644
--- a/hive/utils/account.py
+++ b/hive/utils/account.py
@@ -6,12 +6,19 @@ from hive.utils.normalize import trunc
def safe_profile_metadata(account):
"""Given an account, return sanitized profile data."""
prof = {}
+
try:
- prof = json.loads(account['json_metadata'])['profile']
- if not isinstance(prof, dict):
- prof = {}
+ # read from posting_json_metadata, if version==2
+ prof = json.loads(account['posting_json_metadata'])['profile']
+ assert isinstance(prof, dict)
+ assert 'version' in prof and prof['version'] == 2
except Exception:
- pass
+ try:
+ # fallback to json_metadata
+ prof = json.loads(account['json_metadata'])['profile']
+ assert isinstance(prof, dict)
+ except Exception:
+ prof = {}
name = str(prof['name']) if 'name' in prof else None
about = str(prof['about']) if 'about' in prof else None
|
steemit/hivemind
|
a50ffb074b422956f9ccf79fb49eb0a8969b494e
|
diff --git a/tests/utils/test_utils_account.py b/tests/utils/test_utils_account.py
index b112e11..deb0db1 100644
--- a/tests/utils/test_utils_account.py
+++ b/tests/utils/test_utils_account.py
@@ -11,8 +11,9 @@ def test_valid_account():
website='http://www.davincilife.com/',
cover_image='https://steemitimages.com/0x0/https://pbs.twimg.com/profile_banners/816255358066946050/1483447009/1500x500',
profile_image='https://www.parhlo.com/wp-content/uploads/2016/01/tmp617041537745813506.jpg',
+ version=2,
)
- account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile))}
+ account = {'name': 'foo', 'posting_json_metadata': json.dumps(dict(profile=raw_profile))}
safe_profile = safe_profile_metadata(account)
for key, safe_value in safe_profile.items():
@@ -26,7 +27,11 @@ def test_invalid_account():
cover_image='example.com/avatar.jpg',
profile_image='https://example.com/valid-url-but-longer-than-1024-chars' + 'x' * 1024,
)
- account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile))}
+ ignore_prof = dict(
+ name='Ignore me -- missing version:2!',
+ )
+ account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile)),
+ 'posting_json_metadata': json.dumps(dict(profile=ignore_prof))}
safe_profile = safe_profile_metadata(account)
assert safe_profile['name'] == 'NameIsTooBigByOne...'
|
Support for account_update2 / posting_json_metadata
I broadcasted posting_json_metadata using the new account_update2 operation (https://steemd.com/@tftest1), but unlike when broadcasting json_metadata, this does not change the information that are indexed in hive_accounts
|
0.0
|
a50ffb074b422956f9ccf79fb49eb0a8969b494e
|
[
"tests/utils/test_utils_account.py::test_valid_account"
] |
[
"tests/utils/test_utils_account.py::test_invalid_account"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-27 17:04:29+00:00
|
mit
| 5,709 |
|
stefankoegl__python-json-patch-112
|
diff --git a/jsonpatch.py b/jsonpatch.py
index ca22e34..7d5489a 100644
--- a/jsonpatch.py
+++ b/jsonpatch.py
@@ -334,12 +334,18 @@ class PatchOperation(object):
def __init__(self, operation):
+ if not operation.__contains__('path'):
+ raise InvalidJsonPatch("Operation must have a 'path' member")
+
if isinstance(operation['path'], JsonPointer):
self.location = operation['path'].path
self.pointer = operation['path']
else:
self.location = operation['path']
- self.pointer = JsonPointer(self.location)
+ try:
+ self.pointer = JsonPointer(self.location)
+ except TypeError as ex:
+ raise InvalidJsonPatch("Invalid 'path'")
self.operation = operation
@@ -473,6 +479,9 @@ class ReplaceOperation(PatchOperation):
if part is None:
return value
+ if part == "-":
+ raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation")
+
if isinstance(subobj, MutableSequence):
if part >= len(subobj) or part < 0:
raise JsonPatchConflict("can't replace outside of list")
|
stefankoegl/python-json-patch
|
9e4d423c22bedad6ffc260541ae587114dfed70a
|
diff --git a/tests.py b/tests.py
index cde90b0..0abf4d2 100755
--- a/tests.py
+++ b/tests.py
@@ -219,6 +219,17 @@ class ApplyPatchTestCase(unittest.TestCase):
])
self.assertEqual(res['foo'], [1, 2, 3, 4])
+ def test_add_missing_path(self):
+ obj = {'bar': 'qux'}
+ self.assertRaises(jsonpatch.InvalidJsonPatch,
+ jsonpatch.apply_patch,
+ obj, [{'op': 'test', 'value': 'bar'}])
+
+ def test_path_with_null_value(self):
+ obj = {'bar': 'qux'}
+ self.assertRaises(jsonpatch.InvalidJsonPatch,
+ jsonpatch.apply_patch,
+ obj, '[{"op": "add", "path": null, "value": "bar"}]')
class EqualityTestCase(unittest.TestCase):
|
Some case Failed when run ext_test
Hi @stefankoegl , when I run the external tests [json-patch-tests](https://github.com/json-patch/json-patch-tests), some case failed, I think some of them are bugs, others are due to unreasonable assertions.
here is the list:
- 1: pass only when changing **add** to **replace** -- **not sure if it is a bug**
```
{ "comment": "replace array document with object document?",
"doc": [],
"patch": [{"op": "add", "path": "", "value": {}}],
"expected": {} }
```
- 2: failed with `KeyError: 'path'` before entering the assertion -- **unreasonable assertion**
```
{ "comment": "missing 'path' parameter",
"doc": {},
"patch": [ { "op": "add", "value": "bar" } ],
"error": "missing 'path' parameter" }
```
- 3: failed with `TypeError: expected string or bytes-like object` before entering the assertion -- **unreasonable assertion**
```
{ "comment": "'path' parameter with null value",
"doc": {},
"patch": [ { "op": "add", "path": null, "value": "bar" } ],
"error": "null is not valid value for 'path'" }
```
-4: index leading with zero should failed but success -- **bug**
```
{ "comment": "test with bad array number that has leading zeros",
"doc": ["foo", "bar"],
"patch": [{"op": "test", "path": "/00", "value": "foo"}],
"error": "test op should reject the array value, it has leading zeros" },
{ "comment": "test with bad array number that has leading zeros",
"doc": ["foo", "bar"],
"patch": [{"op": "test", "path": "/01", "value": "bar"}],
"error": "test op should reject the array value, it has leading zeros" }
```
|
0.0
|
9e4d423c22bedad6ffc260541ae587114dfed70a
|
[
"tests.py::ApplyPatchTestCase::test_add_missing_path",
"tests.py::ApplyPatchTestCase::test_path_with_null_value"
] |
[
"tests.py::ApplyPatchTestCase::test_add_array_item",
"tests.py::ApplyPatchTestCase::test_add_object_key",
"tests.py::ApplyPatchTestCase::test_add_replace_whole_document",
"tests.py::ApplyPatchTestCase::test_append",
"tests.py::ApplyPatchTestCase::test_apply_patch_from_string",
"tests.py::ApplyPatchTestCase::test_apply_patch_to_copy",
"tests.py::ApplyPatchTestCase::test_apply_patch_to_same_instance",
"tests.py::ApplyPatchTestCase::test_copy_array_item",
"tests.py::ApplyPatchTestCase::test_copy_mutable",
"tests.py::ApplyPatchTestCase::test_copy_object_key",
"tests.py::ApplyPatchTestCase::test_copy_object_keyerror",
"tests.py::ApplyPatchTestCase::test_js_file",
"tests.py::ApplyPatchTestCase::test_move_array_item",
"tests.py::ApplyPatchTestCase::test_move_array_item_into_other_item",
"tests.py::ApplyPatchTestCase::test_move_object_key",
"tests.py::ApplyPatchTestCase::test_move_object_keyerror",
"tests.py::ApplyPatchTestCase::test_remove_array_item",
"tests.py::ApplyPatchTestCase::test_remove_object_key",
"tests.py::ApplyPatchTestCase::test_replace_array_item",
"tests.py::ApplyPatchTestCase::test_replace_object_key",
"tests.py::ApplyPatchTestCase::test_replace_whole_document",
"tests.py::ApplyPatchTestCase::test_success_if_raise_no_error",
"tests.py::ApplyPatchTestCase::test_success_if_replaced_dict",
"tests.py::ApplyPatchTestCase::test_test_error",
"tests.py::ApplyPatchTestCase::test_test_not_existing",
"tests.py::ApplyPatchTestCase::test_test_noval_existing",
"tests.py::ApplyPatchTestCase::test_test_noval_not_existing",
"tests.py::ApplyPatchTestCase::test_test_noval_not_existing_nested",
"tests.py::ApplyPatchTestCase::test_test_success",
"tests.py::ApplyPatchTestCase::test_test_whole_obj",
"tests.py::ApplyPatchTestCase::test_unrecognized_element",
"tests.py::EqualityTestCase::test_patch_equality",
"tests.py::EqualityTestCase::test_patch_hash_equality",
"tests.py::EqualityTestCase::test_patch_hash_unequal",
"tests.py::EqualityTestCase::test_patch_neq_other_objs",
"tests.py::EqualityTestCase::test_patch_unequal",
"tests.py::EqualityTestCase::test_str",
"tests.py::MakePatchTestCase::test_add_nested",
"tests.py::MakePatchTestCase::test_apply_patch_to_copy",
"tests.py::MakePatchTestCase::test_apply_patch_to_same_instance",
"tests.py::MakePatchTestCase::test_array_add_remove",
"tests.py::MakePatchTestCase::test_arrays",
"tests.py::MakePatchTestCase::test_arrays_one_element_sequences",
"tests.py::MakePatchTestCase::test_complex_object",
"tests.py::MakePatchTestCase::test_escape",
"tests.py::MakePatchTestCase::test_issue103",
"tests.py::MakePatchTestCase::test_issue40",
"tests.py::MakePatchTestCase::test_issue76",
"tests.py::MakePatchTestCase::test_issue90",
"tests.py::MakePatchTestCase::test_json_patch",
"tests.py::MakePatchTestCase::test_list_in_dict",
"tests.py::MakePatchTestCase::test_make_patch_unicode",
"tests.py::MakePatchTestCase::test_move_from_numeric_to_alpha_dict_key",
"tests.py::MakePatchTestCase::test_nested",
"tests.py::MakePatchTestCase::test_objects",
"tests.py::MakePatchTestCase::test_root_list",
"tests.py::OptimizationTests::test_minimal_patch",
"tests.py::OptimizationTests::test_success_if_correct_expected_patch_appied",
"tests.py::OptimizationTests::test_success_if_correct_patch_appied",
"tests.py::OptimizationTests::test_success_if_replace_inside_dict",
"tests.py::OptimizationTests::test_success_if_replace_single_value",
"tests.py::OptimizationTests::test_success_if_replaced_by_object",
"tests.py::OptimizationTests::test_use_move_instead_of_add_remove",
"tests.py::OptimizationTests::test_use_move_instead_of_remove_add",
"tests.py::OptimizationTests::test_use_replace_instead_of_remove_add",
"tests.py::OptimizationTests::test_use_replace_instead_of_remove_add_nested",
"tests.py::ListTests::test_fail_prone_list_1",
"tests.py::ListTests::test_fail_prone_list_2",
"tests.py::ListTests::test_fail_prone_list_3",
"tests.py::ListTests::test_fail_prone_list_4",
"tests.py::InvalidInputTests::test_invalid_op",
"tests.py::InvalidInputTests::test_missing_op",
"tests.py::ConflictTests::test_insert_oob",
"tests.py::ConflictTests::test_move_into_child",
"tests.py::ConflictTests::test_remove_indexerror",
"tests.py::ConflictTests::test_remove_keyerror",
"tests.py::ConflictTests::test_remove_keyerror_dict",
"tests.py::ConflictTests::test_replace_missing",
"tests.py::ConflictTests::test_replace_oob",
"tests.py::ConflictTests::test_replace_oob_length",
"tests.py::JsonPointerTests::test_create_with_pointer"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-23 10:18:35+00:00
|
bsd-3-clause
| 5,710 |
|
stephantul__reach-23
|
diff --git a/reach/reach.py b/reach/reach.py
index 59fb490..13d55a9 100644
--- a/reach/reach.py
+++ b/reach/reach.py
@@ -215,7 +215,7 @@ class Reach(object):
if unk_word is not None:
if unk_word not in items:
- unk_vec = np.zeros((1, vectors.shape[1]))
+ unk_vec = np.zeros((1, vectors.shape[1]), dtype=desired_dtype)
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
|
stephantul/reach
|
ae704219e7aed326bdd7739451abeb03ba2d3bbf
|
diff --git a/tests/test_io.py b/tests/test_io.py
index 95d13d2..7851300 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -64,9 +64,13 @@ class TestLoad(unittest.TestCase):
instance = Reach.load(tempfile.name, unk_word=None)
self.assertEqual(instance.unk_index, None)
- instance = Reach.load(tempfile.name, unk_word="[UNK]")
+ desired_dtype = "float32"
+ instance = Reach.load(
+ tempfile.name, unk_word="[UNK]", desired_dtype=desired_dtype
+ )
self.assertEqual(instance.unk_index, 0)
self.assertEqual(instance.items["[UNK]"], instance.unk_index)
+ self.assertEqual(instance.vectors.dtype, desired_dtype)
instance = Reach.load(tempfile.name, unk_word="splinter")
self.assertEqual(instance.unk_index, 2)
|
Fix bug: adding <UNK> resets dtype
Loading a .vec file with a given dtype (e.g., float32) using an OOV UNK token silently resets the dtype to the system default (usually float64).
Small fix
|
0.0
|
ae704219e7aed326bdd7739451abeb03ba2d3bbf
|
[
"tests/test_io.py::TestLoad::test_unk"
] |
[
"tests/test_io.py::TestLoad::test_corrupted_file",
"tests/test_io.py::TestLoad::test_duplicate",
"tests/test_io.py::TestLoad::test_limit",
"tests/test_io.py::TestLoad::test_load_from_file_with_header",
"tests/test_io.py::TestLoad::test_load_from_file_without_header",
"tests/test_io.py::TestLoad::test_save_load",
"tests/test_io.py::TestLoad::test_save_load_fast_format",
"tests/test_io.py::TestLoad::test_sep",
"tests/test_io.py::TestLoad::test_truncation",
"tests/test_io.py::TestLoad::test_wordlist"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-30 07:49:19+00:00
|
mit
| 5,711 |
|
stephend017__sd_utils-5
|
diff --git a/sd_utils/plugins/plugin_base.py b/sd_utils/plugins/plugin_base.py
index 1aef059..21ff90a 100644
--- a/sd_utils/plugins/plugin_base.py
+++ b/sd_utils/plugins/plugin_base.py
@@ -10,10 +10,14 @@ class PluginBase:
"""
pass
- def on_register(self):
+ def on_register(self, data: Any = None):
"""
runs when this plugin is registered with
the plugin manager
+
+ Args:
+ data (Any): any parameters passed to this
+ plugin from the plugin manager
"""
raise NotImplementedError
@@ -21,11 +25,19 @@ class PluginBase:
"""
runs when the manager begins a query for
any plugin.
+
+ Args:
+ data (Any): any parameters passed to this
+ plugin from the plugin manager
"""
raise NotImplementedError
- def on_find(self, data: Any = None):
+ def on_find(self, data: Any = None) -> Any:
"""
runs when the manager specifically queries this plugin
+
+ Args:
+ data (Any): any parameters passed to this
+ plugin from the plugin manager
"""
raise NotImplementedError
diff --git a/sd_utils/plugins/plugin_collector.py b/sd_utils/plugins/plugin_collector.py
index f40e3fe..44dc3d1 100644
--- a/sd_utils/plugins/plugin_collector.py
+++ b/sd_utils/plugins/plugin_collector.py
@@ -8,7 +8,7 @@ from importlib import import_module
def collect_plugins(
registering_file: str,
registering_file_name: str,
- cls: ClassVar[PluginBase],
+ cls: ClassVar[PluginBase] = PluginBase,
exclude_files: List[str] = [],
assert_one_per_source: bool = True,
) -> List[str]:
@@ -20,10 +20,13 @@ def collect_plugins(
registering_file (str): should be `__file__` of the calling file
registering_file_name (str): should be `__name__` of the calling file
cls (ClassVar[PluginBase]): the type of plugin to collect
- exclude_files (List[str]): any file to exclude from being collected as a plugin
- assert_one_per_source (bool): asserts that only 1 plugin may be defined in each source file
+ exclude_files (List[str]): any file to exclude from being collected
+ as a plugin
+ assert_one_per_source (bool): asserts that only 1 plugin may be
+ defined in each source file
Returns:
- List[str]: a list of all the plugin files collected
+ List[str]: a list of all the plugin files collected. should be
+ stored in the calling files `__all__` variable
"""
exports = []
diff --git a/sd_utils/plugins/plugin_manager.py b/sd_utils/plugins/plugin_manager.py
index 5331be0..deb41ff 100644
--- a/sd_utils/plugins/plugin_manager.py
+++ b/sd_utils/plugins/plugin_manager.py
@@ -1,15 +1,21 @@
from sd_utils.plugins.plugin_base import PluginBase
-from typing import ClassVar
+from typing import Any, ClassVar, final
class PluginManager:
def __init__(self):
self._plugins = {}
- def register(self, name: str, **kwargs):
+ @final
+ def register(self, name: str, on_register_params: dict = {}, **kwargs):
"""
decorator for registering a plugin to this instance of a
plugin manager
+
+ Args:
+ name (str): the name to register this plugin under
+ **kwargs: parameters to be passed to the plugin
+ class when constructed
"""
def decorator(plugin: ClassVar[PluginBase]):
@@ -24,15 +30,33 @@ class PluginManager:
w = Wrapper(plugin(**kwargs))
self._plugins[name] = w
- w.plugin.on_register()
+ w.plugin.on_register(
+ self.get_on_register_params(name, **on_register_params)
+ )
return w
return decorator
- def run(self, name: str):
+ @final
+ def run(
+ self, name: str, on_search_params: dict = {}, on_find_params: dict = {}
+ ) -> Any:
"""
- runs a given plugin
+ runs a given plugin.
+
+ Note: this function
+
+ Args:
+ name (str): the name of the plugin to run
+ on_search_params (dict): parameters to pass to
+ the get_on_search_params function
+ on_find_params (dict): parameters to pass to
+ the get_on_find_params functions
+
+ Returns:
+ Any: The value returned by running the to_find
+ function of the called plugin
"""
to_run = None
@@ -40,7 +64,9 @@ class PluginManager:
if name == plugin_name:
to_run = wrapper
try:
- wrapper.plugin.on_search()
+ wrapper.plugin.on_search(
+ self.get_on_search_params(name, **on_search_params)
+ )
except NotImplementedError:
# just skip if its not implemented
pass
@@ -48,4 +74,55 @@ class PluginManager:
if to_run is None:
raise ValueError(f"Unable to find plugin with name [{name}]")
- to_run.plugin.on_find()
+ return to_run.plugin.on_find(
+ self.get_on_find_params(name, **on_find_params)
+ )
+
+ def get_on_search_params(self, name: str, **kwargs) -> Any:
+ """
+ function that generates parameters for the on
+ search function of a plugin given its name
+
+ Args:
+ name (str): the name of the command to
+ call on_search for
+ **kwargs: any arguments sent from the run
+ function
+
+ Returns:
+ Any: the arguments to be sent to the on_search function
+ """
+ return kwargs
+
+ def get_on_find_params(self, name: str, **kwargs) -> Any:
+ """
+ function that generates parameters for the on
+ find function of a plugin given its name
+
+ Args:
+ name (str): the name of the command to
+ call on_find for
+ **kwargs: any arguments sent from the run
+ function
+
+ Returns:
+ Any: the arguments to be sent to the on_find function
+ """
+ return kwargs
+
+ def get_on_register_params(self, name: str, **kwargs) -> Any:
+ """
+ function that generates parameters for the on
+ register function of a plugin given its name
+
+ Args:
+ name (str): the name of the command to
+ call on_register for
+ **kwargs: any arguments sent from the
+ register function
+
+ Returns:
+ Any: the arguments to be sent to the
+ on_register function
+ """
+ return kwargs
diff --git a/setup.py b/setup.py
index 4f7f17d..340de1c 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ with open("README.md", "r") as file:
setup(
name="sd_utils",
- version="0.1.0",
+ version="0.2.0",
description="A python module with basic utils I tend to use in my projects",
long_description=readme,
long_description_content_type="text/markdown",
|
stephend017/sd_utils
|
34f6f3fcefe79557f80fcb5f9663376a7c9e57e3
|
diff --git a/tests/plugins/__init__.py b/tests/plugins/__init__.py
index 6d5fcb4..b5792c1 100644
--- a/tests/plugins/__init__.py
+++ b/tests/plugins/__init__.py
@@ -1,7 +1,6 @@
-from sd_utils.plugins.plugin_base import PluginBase
from sd_utils.plugins.plugin_collector import collect_plugins
from sd_utils.plugins.plugin_manager import PluginManager
mypluginmanager = PluginManager()
-collect_plugins(__file__, __name__, PluginBase)
+__all__ = collect_plugins(__file__, __name__)
diff --git a/tests/plugins/my_other_plugin.py b/tests/plugins/my_other_plugin.py
index bb73b4d..2f2542a 100644
--- a/tests/plugins/my_other_plugin.py
+++ b/tests/plugins/my_other_plugin.py
@@ -13,7 +13,7 @@ class MyOtherPlugin(PluginBase):
"""
self.operations = []
- def on_register(self):
+ def on_register(self, data: Any = None):
"""
runs when this plugin is registered with
the plugin manager
diff --git a/tests/plugins/my_plugin.py b/tests/plugins/my_plugin.py
index 23bf7a1..cc75323 100644
--- a/tests/plugins/my_plugin.py
+++ b/tests/plugins/my_plugin.py
@@ -12,8 +12,9 @@ class MyPlugin(PluginBase):
"""
"""
self.operations = []
+ self.data = []
- def on_register(self):
+ def on_register(self, data: Any = None):
"""
runs when this plugin is registered with
the plugin manager
@@ -26,9 +27,12 @@ class MyPlugin(PluginBase):
any plugin.
"""
self.operations.append("searched")
+ self.data.append(data)
def on_find(self, data: Any = None):
"""
runs when the manager specifically queries this plugin
"""
self.operations.append("found")
+ self.data.append(data)
+ return data
diff --git a/tests/plugins/test_plugins.py b/tests/plugins/test_plugins.py
index 3f7a6c7..4f75aa5 100644
--- a/tests/plugins/test_plugins.py
+++ b/tests/plugins/test_plugins.py
@@ -22,8 +22,7 @@ def test_search_and_find():
assert "searched" in mypluginmanager._plugins["myplugin"].plugin.operations
assert "found" in mypluginmanager._plugins["myplugin"].plugin.operations
- mypluginmanager._plugins["myplugin"].plugin.operations.remove("searched")
- mypluginmanager._plugins["myplugin"].plugin.operations.remove("found")
+ mypluginmanager._plugins["myplugin"].plugin.operations.clear()
def test_plugin_doesnt_exist():
@@ -34,7 +33,7 @@ def test_plugin_doesnt_exist():
with pytest.raises(ValueError):
mypluginmanager.run("notmyplugin")
- mypluginmanager._plugins["myplugin"].plugin.operations.remove("searched")
+ mypluginmanager._plugins["myplugin"].plugin.operations.clear()
def test_search_only():
@@ -49,4 +48,46 @@ def test_search_only():
"found" not in mypluginmanager._plugins["myplugin"].plugin.operations
)
- mypluginmanager._plugins["myplugin"].plugin.operations.remove("searched")
+ mypluginmanager._plugins["myplugin"].plugin.operations.clear()
+
+
+def test_get_on_search_params():
+ """
+ Tests that get_on_search params properly takes in
+ the correct arguments
+ """
+
+ mydata = {"data": "value"}
+ mypluginmanager.run("myplugin", mydata)
+
+ assert mydata in mypluginmanager._plugins["myplugin"].plugin.data
+
+ mypluginmanager._plugins["myplugin"].plugin.data.clear()
+
+
+def test_get_on_find_params():
+ """
+ Tests that get_on_search params properly takes in
+ the correct arguments
+ """
+
+ mydata = {"data": "value"}
+ mypluginmanager.run("myplugin", on_find_params=mydata)
+
+ assert mydata in mypluginmanager._plugins["myplugin"].plugin.data
+
+ mypluginmanager._plugins["myplugin"].plugin.data.clear()
+
+
+def test_on_find_return_value():
+ """
+ Tests that get_on_search params properly takes in
+ the correct arguments
+ """
+
+ mydata = {"data": "value"}
+ response = mypluginmanager.run("myplugin", on_find_params=mydata)
+
+ assert response == mydata
+
+ mypluginmanager._plugins["myplugin"].plugin.data.clear()
|
Allow plugins to return values
allow a plugin to return a value. along with this update a plugin should also be able to receive a value in the on_register hook
|
0.0
|
34f6f3fcefe79557f80fcb5f9663376a7c9e57e3
|
[
"tests/plugins/test_plugins.py::test_registered",
"tests/plugins/test_plugins.py::test_search_and_find",
"tests/plugins/test_plugins.py::test_plugin_doesnt_exist",
"tests/plugins/test_plugins.py::test_search_only",
"tests/plugins/test_plugins.py::test_get_on_search_params",
"tests/plugins/test_plugins.py::test_get_on_find_params",
"tests/plugins/test_plugins.py::test_on_find_return_value"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-15 16:31:59+00:00
|
mit
| 5,712 |
|
stephend017__sd_utils-8
|
diff --git a/sd_utils/plugins/plugin_base.py b/sd_utils/plugins/plugin_base.py
index 21ff90a..3578331 100644
--- a/sd_utils/plugins/plugin_base.py
+++ b/sd_utils/plugins/plugin_base.py
@@ -41,3 +41,13 @@ class PluginBase:
plugin from the plugin manager
"""
raise NotImplementedError
+
+ def on_iterate(self, data: Any = None):
+ """
+ runs when the manager specifically calls iterate_all
+
+ Args:
+ data (Any): any parameters passed to this
+ plugin from the plugin manager
+ """
+ raise NotImplementedError
diff --git a/sd_utils/plugins/plugin_manager.py b/sd_utils/plugins/plugin_manager.py
index deb41ff..e6322a0 100644
--- a/sd_utils/plugins/plugin_manager.py
+++ b/sd_utils/plugins/plugin_manager.py
@@ -30,9 +30,13 @@ class PluginManager:
w = Wrapper(plugin(**kwargs))
self._plugins[name] = w
- w.plugin.on_register(
- self.get_on_register_params(name, **on_register_params)
- )
+ try:
+ w.plugin.on_register(
+ self.get_on_register_params(name, **on_register_params)
+ )
+ except NotImplementedError:
+ # dont need to implement this hook
+ pass
return w
@@ -45,7 +49,12 @@ class PluginManager:
"""
runs a given plugin.
- Note: this function
+ Note: this function iterates over all plugins and will call the
+ on_search for each plugin before executing the on_find hook
+ for the plugin being searched for.
+
+ This function should not be used just to iterate over every plugin.
+ instead the iterate_all function should be used
Args:
name (str): the name of the plugin to run
@@ -78,6 +87,25 @@ class PluginManager:
self.get_on_find_params(name, **on_find_params)
)
+ @final
+ def iterate_all(self, on_iterate_params: dict = {}):
+ """
+ Iterates over all the plugins without directly calling
+ one of them. Only hook used is on_iterate
+
+ Args:
+ on_iterate_params (dict): a list of parameters to pass
+ to the on_iterate hook
+ """
+ for name, wrapper in self._plugins.items():
+ try:
+ wrapper.plugin.on_iterate(
+ self.get_on_iterate_params(name, **on_iterate_params)
+ )
+ except NotImplementedError:
+ # just skip if its not implemented
+ pass
+
def get_on_search_params(self, name: str, **kwargs) -> Any:
"""
function that generates parameters for the on
@@ -126,3 +154,20 @@ class PluginManager:
on_register function
"""
return kwargs
+
+ def get_on_iterate_params(self, name: str, **kwargs) -> Any:
+ """
+ function that generates parameters for the on
+ iterate_all function of a plugin given its name
+
+ Args:
+ name (str): the name of the command to
+ call iterate_all for
+ **kwargs: any arguments sent from the
+ iterate_all function
+
+ Returns:
+ Any: the arguments to be sent to the
+ iterate_all function
+ """
+ return kwargs
diff --git a/setup.py b/setup.py
index 340de1c..c9d2f12 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ with open("README.md", "r") as file:
setup(
name="sd_utils",
- version="0.2.0",
+ version="0.2.1",
description="A python module with basic utils I tend to use in my projects",
long_description=readme,
long_description_content_type="text/markdown",
|
stephend017/sd_utils
|
dfcc52f200e3a79d900b2f2b962ccf58b8f792d7
|
diff --git a/tests/plugins/my_other_plugin.py b/tests/plugins/my_other_plugin.py
index 2f2542a..06a3c89 100644
--- a/tests/plugins/my_other_plugin.py
+++ b/tests/plugins/my_other_plugin.py
@@ -13,13 +13,6 @@ class MyOtherPlugin(PluginBase):
"""
self.operations = []
- def on_register(self, data: Any = None):
- """
- runs when this plugin is registered with
- the plugin manager
- """
- self.operations.append("registered")
-
def on_search(self, data: Any = None):
"""
runs when the manager begins a query for
diff --git a/tests/plugins/my_plugin.py b/tests/plugins/my_plugin.py
index cc75323..93454a7 100644
--- a/tests/plugins/my_plugin.py
+++ b/tests/plugins/my_plugin.py
@@ -36,3 +36,7 @@ class MyPlugin(PluginBase):
self.operations.append("found")
self.data.append(data)
return data
+
+ def on_iterate(self, data: Any):
+ self.operations.append("iterate")
+ self.data.append(data)
diff --git a/tests/plugins/test_plugins.py b/tests/plugins/test_plugins.py
index 4f75aa5..c468df4 100644
--- a/tests/plugins/test_plugins.py
+++ b/tests/plugins/test_plugins.py
@@ -91,3 +91,17 @@ def test_on_find_return_value():
assert response == mydata
mypluginmanager._plugins["myplugin"].plugin.data.clear()
+
+
+def test_iterate_all():
+ """
+ tests that the iterate all function works correctly
+ """
+ mydata = {"data": "value"}
+ mypluginmanager.iterate_all(mydata)
+
+ assert "iterate" in mypluginmanager._plugins["myplugin"].plugin.operations
+ assert mydata in mypluginmanager._plugins["myplugin"].plugin.data
+
+ mypluginmanager._plugins["myplugin"].plugin.data.clear()
+ mypluginmanager._plugins["myplugin"].plugin.operations.clear()
|
on_register hook required
currently the `on_register` hook in a plugin base must be implemented. This should be an optional hook
|
0.0
|
dfcc52f200e3a79d900b2f2b962ccf58b8f792d7
|
[
"tests/plugins/test_plugins.py::test_registered",
"tests/plugins/test_plugins.py::test_search_and_find",
"tests/plugins/test_plugins.py::test_plugin_doesnt_exist",
"tests/plugins/test_plugins.py::test_search_only",
"tests/plugins/test_plugins.py::test_get_on_search_params",
"tests/plugins/test_plugins.py::test_get_on_find_params",
"tests/plugins/test_plugins.py::test_on_find_return_value",
"tests/plugins/test_plugins.py::test_iterate_all"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-16 15:20:08+00:00
|
mit
| 5,713 |
|
steve-todorov__mkdocs-pom-parser-plugin-4
|
diff --git a/setup.py b/setup.py
index 7f51d15..fc0553e 100644
--- a/setup.py
+++ b/setup.py
@@ -117,7 +117,7 @@ setup(
# Note that this is a list of additional keywords, separated
# by commas, to be used to assist searching for the distribution in a
# larger catalog.
- keywords='mkdocs, setuptools, development', # Optional
+ keywords='mkdocs, maven, pom, parser, plugin', # Optional
# When your source code is in a subdirectory under the project root, e.g.
# `src/`, it is necessary to specify the `package_dir` argument.
diff --git a/src/mkdocs_pom_parser_plugin/parser.py b/src/mkdocs_pom_parser_plugin/parser.py
index d3ed244..c07ea40 100644
--- a/src/mkdocs_pom_parser_plugin/parser.py
+++ b/src/mkdocs_pom_parser_plugin/parser.py
@@ -1,10 +1,9 @@
-import xml.etree.ElementTree as ET
-
import re
+import sys
+import xml.etree.ElementTree as ET
+from pathlib import Path
-namespaces = {
- '': 'http://maven.apache.org/POM/4.0.0',
-}
+namespaces = {'': 'http://maven.apache.org/POM/4.0.0', 'mvn': 'http://maven.apache.org/POM/4.0.0'}
class PomParser:
@@ -12,16 +11,23 @@ class PomParser:
This class is simply a wrapper around ElementTree
"""
- def __init__(self, arg: str):
- result = re.search("([\n+])", arg)
+ oldPython = True
+ def __init__(self, fileOrContent: str, **kwargs):
+ version = sys.version_info
+ if kwargs.get("version_info", None):
+ version = kwargs.get("version_info")
+
+ self.oldPython = version < (3, 8)
+
+ path = Path(fileOrContent)
# arg is the xml string. (easier testing)
- if result is not None:
- self.tree = ET.fromstring(arg)
+ if path.exists() is not True:
+ self.tree = ET.fromstring(fileOrContent)
# arg is file
else:
- self.tree = ET.parse(arg)
+ self.tree = ET.parse(fileOrContent)
def getTree(self):
return self.tree
@@ -50,10 +56,16 @@ class PomParser:
def getUrl(self):
return self.findTextByXpath("./url")
- def findByXpath(self, xpath: str):
- return self.tree.find(xpath, namespaces)
-
def findTextByXpath(self, xpath: str):
- element = self.tree.find(xpath, namespaces)
+ element = self.findByXpath(xpath)
# print(element.text) if element is not None else None
return element.text if element is not None else None
+
+ def findByXpath(self, xpath: str):
+ # Add support for older Python versions - necessary for Netlify since it does not support >= 3.8 at the time of
+ # writing this.
+ defaultNamespace = "./{" + namespaces.get('') + "}"
+ if self.oldPython and xpath.startswith(defaultNamespace) is False and xpath.startswith("./mvn:") is False:
+ xpath = re.sub(r"^\./(.+)$", r'./mvn:\1', xpath)
+
+ return self.tree.find(xpath, namespaces)
diff --git a/src/mkdocs_pom_parser_plugin/plugin.py b/src/mkdocs_pom_parser_plugin/plugin.py
index 9544ec3..8ea4feb 100644
--- a/src/mkdocs_pom_parser_plugin/plugin.py
+++ b/src/mkdocs_pom_parser_plugin/plugin.py
@@ -43,6 +43,12 @@ class PomParserPlugin(BasePlugin):
}
def on_config(self, config: Config):
+ oldPython = sys.version_info < (3, 8)
+
+ if oldPython:
+ log.warning("Python versions lower than 3.8 (current: %s) do not support default namespace! ", str(sys.version_info.major) + "." + str(sys.version_info.minor))
+ log.warning("None results while referencing POM_* variables in templates are likely because of that.")
+
env_vars = {}
for name, plugin in config.get('plugins').items():
if name == 'mkdocs-pom-parser-plugin':
@@ -56,21 +62,24 @@ class PomParserPlugin(BasePlugin):
path = plugin_config.get('path')
if path is not None:
log.debug("Configured pom file: %s", path)
- path = Path(path).resolve().__str__()
+ path = Path(path).resolve()
log.info("Resolved pom file: %s", path)
- additional = plugin_config.get('additional', {})
- env_vars = copy.copy(self.DEFAULT_ENV_VARS)
+ if path.exists():
+ additional = plugin_config.get('additional', {})
+ env_vars = copy.copy(self.DEFAULT_ENV_VARS)
- if additional is not None:
- log.debug("Additional pom variables detected: %s", additional)
- for key, value in additional.items():
- env_vars["POM_" + key.upper()] = value
+ if additional is not None:
+ log.debug("Additional pom variables detected: %s", additional)
+ for key, value in additional.items():
+ env_vars["POM_" + key.upper()] = value
- parser = PomParser(path)
- for key, xpath in env_vars.items():
- value = parser.findTextByXpath(xpath)
- env_vars[key] = value
+ parser = PomParser(path.__str__())
+ for key, xpath in env_vars.items():
+ value = parser.findTextByXpath(xpath)
+ env_vars[key] = value
+ else:
+ log.warning("File %s does not exist or is not readable/accessible!", path)
config.update({"pom_env_vars": env_vars})
if env_vars.__sizeof__() > 0:
@@ -89,4 +98,4 @@ class PomParserPlugin(BasePlugin):
# md_template = Template(markdown)
env = jinja2.Environment(undefined=jinja2.DebugUndefined)
md_template = env.from_string(markdown)
- return md_template.render(copy.copy(config.get("pom_env_vars")))
+ return md_template.render(copy.deepcopy(config.get("pom_env_vars")))
diff --git a/tox.ini b/tox.ini
index 42f935c..fb1095e 100644
--- a/tox.ini
+++ b/tox.ini
@@ -40,7 +40,7 @@ commands =
# `setup.py check` is not needed. If your project contains a README.rst,
# use `python setup.py check -m -r -s` instead.
python setup.py check -m -s
- flake8 .
+ flake8 --ignore=E501 .
py.test tests {posargs}
[flake8]
|
steve-todorov/mkdocs-pom-parser-plugin
|
493389fa6366c9a21bf0d477a502cef3dbbd5903
|
diff --git a/tests/test_parser.py b/tests/test_parser.py
index f298b60..7b07386 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1,7 +1,6 @@
# the inclusion of the tests module is not meant to offer best practices for
# testing in general, but rather to support the `find_packages` example in
# setup.py that excludes installing the "tests" package
-
import unittest
from mkdocs_pom_parser_plugin.parser import PomParser
@@ -70,6 +69,18 @@ class TestPomParser(unittest.TestCase):
self.assertIsNotNone(element)
self.assertEqual('scm:git:git://github.com', element)
+ def test_findByXpathOlderPythonVersions(self):
+ version = (3, 7, 0, 'final', 0)
+ element = PomParser(self.stringXml, version_info=version).findTextByXpath("./scm/connection")
+ self.assertIsNotNone(element)
+ self.assertEqual('scm:git:git://github.com', element)
+
+ def test_findByXpathOlderPythonVersionsWithExplicitNamespace(self):
+ version = (3, 7, 0, 'final', 0)
+ element = PomParser(self.stringXml, version_info=version).findTextByXpath("./{http://maven.apache.org/POM/4.0.0}scm/connection")
+ self.assertIsNotNone(element)
+ self.assertEqual('scm:git:git://github.com', element)
+
if __name__ == '__main__':
unittest.main()
|
Add support for older python versions
## Description
Older versions of Python do not support default namespaces for xml parsing - you need to explicitly define the namespace in the xpath or it will simply return `None`. This is problematic for Netlify builds which are currently using Python 3.7 as their "latest" version.
|
0.0
|
493389fa6366c9a21bf0d477a502cef3dbbd5903
|
[
"tests/test_parser.py::TestPomParser::test_findByXpathOlderPythonVersions",
"tests/test_parser.py::TestPomParser::test_findByXpathOlderPythonVersionsWithExplicitNamespace"
] |
[
"tests/test_parser.py::TestPomParser::test_findByXpath",
"tests/test_parser.py::TestPomParser::test_findByXpathDeep",
"tests/test_parser.py::TestPomParser::test_findTextByXpath",
"tests/test_parser.py::TestPomParser::test_findTextByXpathDeep",
"tests/test_parser.py::TestPomParser::test_getArtifactId",
"tests/test_parser.py::TestPomParser::test_getDescription",
"tests/test_parser.py::TestPomParser::test_getGroupId",
"tests/test_parser.py::TestPomParser::test_getModelVersion",
"tests/test_parser.py::TestPomParser::test_getName",
"tests/test_parser.py::TestPomParser::test_getPackaging",
"tests/test_parser.py::TestPomParser::test_getUrl",
"tests/test_parser.py::TestPomParser::test_getVersion"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-01 14:50:37+00:00
|
mit
| 5,714 |
|
stfc__PSyclone-1101
|
diff --git a/changelog b/changelog
index 863a4d892..45b2fd83f 100644
--- a/changelog
+++ b/changelog
@@ -375,6 +375,8 @@
120) PR #1105 for #1104. Adds support for program, module and subroutine
to Fparser2Reader
+ 121) PR #1101 towards #1089. Remove check on arrays dimension symbols.
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/symbols/datatypes.py b/src/psyclone/psyir/symbols/datatypes.py
index 379f14821..e37098570 100644
--- a/src/psyclone/psyir/symbols/datatypes.py
+++ b/src/psyclone/psyir/symbols/datatypes.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2019-2020, Science and Technology Facilities Council.
+# Copyright (c) 2019-2021, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -43,6 +43,7 @@ from enum import Enum
import six
from psyclone.errors import InternalError
from psyclone.psyir.symbols import TypeSymbol, DataSymbol
+from psyclone.psyir.symbols.symbol import Symbol
@six.add_metaclass(abc.ABCMeta)
@@ -377,19 +378,9 @@ class ArrayType(DataType):
"declaration then it should be a scalar "
"integer or an unknown type, but '{0}' is a "
"'{1}'.".format(symbol.name, symbol.datatype))
- # Check that any references are not to a local
- # datasymbol that is not constant (as this would have
+ # TODO #1089 - add check that any References are not to a
+ # local datasymbol that is not constant (as this would have
# no value).
- references = dimension.walk(Reference)
- if references:
- for reference in references:
- if reference.symbol.is_local and \
- not reference.symbol.is_constant:
- raise TypeError(
- "If a local datasymbol is used as part of a "
- "dimension declaration then it should be a "
- "constant, but '{0}' is not."
- "".format(reference.symbol.name))
elif not isinstance(dimension, (self.Extent, int)):
raise TypeError(
"DataSymbol shape list elements can only be "
@@ -493,9 +484,6 @@ class StructureType(DataType):
:raises TypeError: if any of the supplied values are of the wrong type.
'''
- # This import has to be here to avoid circular dependencies
- # pylint: disable=import-outside-toplevel
- from psyclone.psyir.symbols import Symbol, TypeSymbol
if not isinstance(name, str):
raise TypeError(
"The name of a component of a StructureType must be a 'str' "
|
stfc/PSyclone
|
49b6a4db5a47e9f57a151785f90be066ed8c6c04
|
diff --git a/src/psyclone/tests/psyir/symbols/datatype_test.py b/src/psyclone/tests/psyir/symbols/datatype_test.py
index e03fa35d8..2adc12db0 100644
--- a/src/psyclone/tests/psyir/symbols/datatype_test.py
+++ b/src/psyclone/tests/psyir/symbols/datatype_test.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2020, Science and Technology Facilities Council.
+# Copyright (c) 2020-2021, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -40,8 +40,9 @@ from __future__ import absolute_import
import pytest
from psyclone.psyir.symbols import DataType, DeferredType, ScalarType, \
ArrayType, UnknownFortranType, DataSymbol, StructureType, \
- INTEGER_TYPE, REAL_TYPE, Symbol, TypeSymbol
-from psyclone.psyir.nodes import Literal, BinaryOperation, Reference
+ INTEGER_TYPE, REAL_TYPE, Symbol, TypeSymbol, SymbolTable
+from psyclone.psyir.nodes import Literal, BinaryOperation, Reference, \
+ Container, KernelSchedule
from psyclone.errors import InternalError
@@ -304,22 +305,9 @@ def test_arraytype_invalid_shape_dimension_2():
in str(excinfo.value))
[email protected](reason="issue #948. Support for this check "
- "needs to be added")
[email protected](reason="issue #1089. Support for this check needs to be"
+ "implemented")
def test_arraytype_invalid_shape_dimension_3():
- '''Test that the ArrayType class raises an exception when one of the
- dimensions of the shape list argument is a local datasymbol that does
- not have a constant value (as this will not be initialised).'''
-
- scalar_type = ScalarType(ScalarType.Intrinsic.INTEGER, 4)
- data_symbol = DataSymbol("var", scalar_type)
- with pytest.raises(TypeError) as info:
- _ = ArrayType(scalar_type, [data_symbol])
- assert ("If a local datasymbol is used to declare a dimension then it "
- "should be a constant, but 'var' is not." in str(info.value))
-
-
-def test_arraytype_invalid_shape_dimension_4():
'''Test that the ArrayType class raises an exception when one of the
dimensions of the shape list argument is a DataNode that contains
a local datasymbol that does not have a constant value (as this
@@ -338,6 +326,21 @@ def test_arraytype_invalid_shape_dimension_4():
"not." in str(info.value))
+def test_arraytype_shape_dim_from_parent_scope():
+ ''' Check that the shape checking in the ArrayType class permits the
+ use of a reference to a symbol in a parent scope. '''
+ cont = Container("test_mod")
+ dim_sym = cont.symbol_table.new_symbol("dim1", symbol_type=DataSymbol,
+ datatype=INTEGER_TYPE)
+ kernel1 = KernelSchedule.create("mod_1", SymbolTable(), [])
+ cont.addchild(kernel1)
+ kernel1.parent = cont
+ asym = kernel1.symbol_table.new_symbol(
+ "array1", symbol_type=DataSymbol,
+ datatype=ArrayType(INTEGER_TYPE, [Reference(dim_sym)]))
+ assert isinstance(asym, DataSymbol)
+
+
def test_arraytype_str():
'''Test that the ArrayType class str method works as expected.'''
scalar_type = ScalarType(ScalarType.Intrinsic.INTEGER,
|
[psyir] Check on whether dimensioning symbol is local does not work when symbol is in an ancestor scope.
For the following Fortran:
module my_mod
integer :: dim
contains
subroutine init()
dim = 10
end subroutine
subroutine work()
real, dimension(dim) :: my_array
end subroutine
end module
Then PSyclone complains:
If a local datasymbol is used as part of a dimension declaration then it should be a constant, but 'dim' is not.
The problem is in `ArrayType._validate_shape` where the Symbol being referred to in the shape specification is looked up. It is found to have a 'local' interface and not be a constant. Both of which are correct. However, no check is made on which SymbolTable the symbol is in.
|
0.0
|
49b6a4db5a47e9f57a151785f90be066ed8c6c04
|
[
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_shape_dim_from_parent_scope"
] |
[
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_deferredtype",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_deferredtype_str",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.INTEGER-Precision.SINGLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.INTEGER-Precision.DOUBLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.INTEGER-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.REAL-Precision.SINGLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.REAL-Precision.DOUBLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.REAL-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.BOOLEAN-Precision.SINGLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.BOOLEAN-Precision.DOUBLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.BOOLEAN-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.CHARACTER-Precision.SINGLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.CHARACTER-Precision.DOUBLE]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_enum_precision[Intrinsic.CHARACTER-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.INTEGER-1]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.INTEGER-8]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.INTEGER-16]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.REAL-1]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.REAL-8]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.REAL-16]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.BOOLEAN-1]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.BOOLEAN-8]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.BOOLEAN-16]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.CHARACTER-1]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.CHARACTER-8]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_int_precision[Intrinsic.CHARACTER-16]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_datasymbol_precision[Intrinsic.INTEGER]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_datasymbol_precision[Intrinsic.REAL]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_datasymbol_precision[Intrinsic.BOOLEAN]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_datasymbol_precision[Intrinsic.CHARACTER]",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_invalid_intrinsic_type",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_invalid_precision_type",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_invalid_precision_int_value",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_invalid_precision_datasymbol",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_str",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_scalartype_immutable",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_invalid_datatype",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_typesymbol_only",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_typesymbol",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_invalid_shape",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_invalid_shape_dimension_1",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_invalid_shape_dimension_2",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_str",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_str_invalid",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_arraytype_immutable",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_unknown_fortran_type",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_structure_type",
"src/psyclone/tests/psyir/symbols/datatype_test.py::test_create_structuretype"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-03 12:28:44+00:00
|
bsd-3-clause
| 5,715 |
|
stfc__PSyclone-1111
|
diff --git a/changelog b/changelog
index 89d16decf..3bf34bc3b 100644
--- a/changelog
+++ b/changelog
@@ -358,6 +358,8 @@
115) PR #1102 towards #1031. Improves PSyIR fparser2 frontend support for
structures types.
+ 116) PR #1111 for #1110. The Call create method is a classmethod.
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/nodes/call.py b/src/psyclone/psyir/nodes/call.py
index f25f9cf6d..380d97ec9 100644
--- a/src/psyclone/psyir/nodes/call.py
+++ b/src/psyclone/psyir/nodes/call.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2020, Science and Technology Facilities Council.
+# Copyright (c) 2020-21, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -66,19 +66,19 @@ class Call(Statement):
self._routine = routine
- @staticmethod
- def create(routine, arguments):
- '''Create a Call instance given valid instances of a routine symbol,
- and a list of child nodes for its arguments.
+ @classmethod
+ def create(cls, routine, arguments):
+ '''Create an instance of class cls given valid instances of a routine
+ symbol, and a list of child nodes for its arguments.
- :param routine: the routine that this call calls.
+ :param routine: the routine that class cls calls.
:type routine: py:class:`psyclone.psyir.symbols.RoutineSymbol`
:param arguments: the arguments to this routine. These are \
added as child nodes.
:type arguments: list of :py:class:`psyclone.psyir.nodes.DataNode`
- :returns: a Call instance.
- :rtype: :py:class:`psyclone.psyir.nodes.Call`
+ :returns: an instance of cls.
+ :rtype: :py:class:`psyclone.psyir.nodes.Call` or a subclass thereof.
'''
if not isinstance(routine, RoutineSymbol):
@@ -90,7 +90,7 @@ class Call(Statement):
"Call create arguments argument should be a list but found "
"'{0}'.".format(type(arguments).__name__))
- call = Call(routine)
+ call = cls(routine)
call.children = arguments
for child in call.children:
child.parent = call
|
stfc/PSyclone
|
76ccb352e37e2905a4cd4a731fda03967267d0aa
|
diff --git a/src/psyclone/tests/psyir/nodes/call_test.py b/src/psyclone/tests/psyir/nodes/call_test.py
index 6d8986b05..c73c09334 100644
--- a/src/psyclone/tests/psyir/nodes/call_test.py
+++ b/src/psyclone/tests/psyir/nodes/call_test.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2020, Science and Technology Facilities Council.
+# Copyright (c) 2020-21, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -45,6 +45,10 @@ from psyclone.psyir.symbols import ArrayType, INTEGER_TYPE, DataSymbol, \
from psyclone.errors import GenerationError
+class SpecialCall(Call):
+ '''Test Class specialising the Call class'''
+
+
def test_call_init():
'''Test that a Call can be created as expected. Also test the routine
property.
@@ -77,14 +81,17 @@ def test_call_init_error():
"'NoneType'." in str(info.value))
-def test_call_create():
[email protected]("cls", [Call, SpecialCall])
+def test_call_create(cls):
'''Test that the create method creates a valid call with arguments'''
routine = RoutineSymbol("ellie")
array_type = ArrayType(INTEGER_TYPE, shape=[10, 20])
arguments = [Reference(DataSymbol("arg1", INTEGER_TYPE)),
ArrayReference(DataSymbol("arg2", array_type))]
- call = Call.create(routine, arguments)
+ call = cls.create(routine, arguments)
+ # pylint: disable=unidiomatic-typecheck
+ assert type(call) is cls
assert call.routine is routine
for idx, child, in enumerate(call.children):
assert child is arguments[idx]
|
Call create method should be a classmethod not a staticmethod
In the future we may want to subclass a `Call` node and use the `create` method in the `Call` node to create an instance of the subclass. An example of this could be in the generation of a PSyIR version of the algorithm layer for LFRic where invoke calls will contain `builtin` or `coded` calls which are subclasses of `Call` and could be simply created using the `create` method.
|
0.0
|
76ccb352e37e2905a4cd4a731fda03967267d0aa
|
[
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_create[SpecialCall]"
] |
[
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_init",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_init_error",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_create[Call]",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_create_error1",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_error2",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_error3",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_node_str",
"src/psyclone/tests/psyir/nodes/call_test.py::test_call_str"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-07 22:37:51+00:00
|
bsd-3-clause
| 5,716 |
|
stfc__PSyclone-1138
|
diff --git a/changelog b/changelog
index 6a2c66eec..2ef739173 100644
--- a/changelog
+++ b/changelog
@@ -393,6 +393,8 @@
126) PR #1095 for #1083. Adds a LoopTrans base class that Loop
transformations can subclass and use any common functionality.
+ 127) PR #1138 for #1137. Add support for Fortran Program in the PSyIR.
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/backend/fortran.py b/src/psyclone/psyir/backend/fortran.py
index 4b6c12b2a..e03cdcc1f 100644
--- a/src/psyclone/psyir/backend/fortran.py
+++ b/src/psyclone/psyir/backend/fortran.py
@@ -732,10 +732,13 @@ class FortranWriter(PSyIRVisitor):
if not node.name:
raise VisitorError("Expected node name to have a value.")
- args = [symbol.name for symbol in node.symbol_table.argument_list]
- result = (
- "{0}subroutine {1}({2})\n"
- "".format(self._nindent, node.name, ", ".join(args)))
+ if node.is_program:
+ result = ("{0}program {1}\n".format(self._nindent, node.name))
+ else:
+ args = [symbol.name for symbol in node.symbol_table.argument_list]
+ result = (
+ "{0}subroutine {1}({2})\n"
+ "".format(self._nindent, node.name, ", ".join(args)))
self._depth += 1
@@ -773,9 +776,13 @@ class FortranWriter(PSyIRVisitor):
"".format(imports, declarations, exec_statements))
self._depth -= 1
+ if node.is_program:
+ keyword = "program"
+ else:
+ keyword = "subroutine"
result += (
- "{0}end subroutine {1}\n"
- "".format(self._nindent, node.name))
+ "{0}end {1} {2}\n"
+ "".format(self._nindent, keyword, node.name))
return result
diff --git a/src/psyclone/psyir/frontend/fparser2.py b/src/psyclone/psyir/frontend/fparser2.py
index a2b167a21..6a182367e 100644
--- a/src/psyclone/psyir/frontend/fparser2.py
+++ b/src/psyclone/psyir/frontend/fparser2.py
@@ -768,6 +768,7 @@ class Fparser2Reader(object):
Fortran2003.Call_Stmt: self._call_handler,
Fortran2003.Subroutine_Subprogram: self._subroutine_handler,
Fortran2003.Module: self._module_handler,
+ Fortran2003.Main_Program: self._main_program_handler,
Fortran2003.Program: self._program_handler,
}
@@ -3436,6 +3437,45 @@ class Fparser2Reader(object):
return routine
+ def _main_program_handler(self, node, parent):
+ '''Transforms an fparser2 Main_Program statement into a PSyIR
+ Routine node.
+
+ :param node: node in fparser2 parse tree.
+ :type node: :py:class:`fparser.two.Fortran2003.Main_Program`
+ :param parent: parent node of the PSyIR node being constructed.
+ :type parent: subclass of :py:class:`psyclone.psyir.nodes.Node`
+
+ :returns: PSyIR representation of node.
+ :rtype: :py:class:`psyclone.psyir.nodes.Routine`
+
+ '''
+ name = node.children[0].children[1].string
+ routine = Routine(name, parent=parent, is_program=True)
+
+ try:
+ prog_spec = _first_type_match(node.content,
+ Fortran2003.Specification_Part)
+ decl_list = prog_spec.content
+ except ValueError:
+ # program has no Specification_Part so has no
+ # declarations. Continue with empty list.
+ decl_list = []
+ finally:
+ self.process_declarations(routine, decl_list, [])
+
+ try:
+ prog_exec = _first_type_match(node.content,
+ Fortran2003.Execution_Part)
+ except ValueError:
+ # Routines without any execution statements are still
+ # valid.
+ pass
+ else:
+ self.process_nodes(routine, prog_exec.content)
+
+ return routine
+
def _module_handler(self, node, parent):
'''Transforms an fparser2 Module statement into a PSyIR Container node.
|
stfc/PSyclone
|
313bd5a4c31a8216716ffb9a38a64835c975d5ad
|
diff --git a/src/psyclone/tests/psyir/backend/fortran_test.py b/src/psyclone/tests/psyir/backend/fortran_test.py
index 138950100..be4738927 100644
--- a/src/psyclone/tests/psyir/backend/fortran_test.py
+++ b/src/psyclone/tests/psyir/backend/fortran_test.py
@@ -945,6 +945,34 @@ def test_fw_routine(fort_writer, monkeypatch, tmpdir):
_ = fort_writer(schedule)
assert "Expected node name to have a value." in str(excinfo.value)
+
+def test_fw_routine_program(parser, fort_writer, tmpdir):
+ '''Check the FortranWriter class outputs correct code when a routine node
+ is found with is_program set to True i.e. it should be output as a program.
+
+ '''
+ # Generate PSyIR from Fortran code via fparser2 ast
+ code = (
+ "program test\n"
+ " real :: a\n"
+ " a = 0.0\n"
+ "end program test")
+ reader = FortranStringReader(code)
+ fp2_ast = parser(reader)
+ fp2_reader = Fparser2Reader()
+ psyir = fp2_reader.generate_psyir(fp2_ast)
+
+ # Generate Fortran from PSyIR
+ result = fort_writer(psyir)
+
+ assert(
+ "program test\n"
+ " real :: a\n\n"
+ " a = 0.0\n\n"
+ "end program test\n" in result)
+ assert Compile(tmpdir).string_compiles(result)
+
+
# assignment and binaryoperation (not intrinsics) are already checked
# within previous tests
diff --git a/src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py b/src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py
index 9fd84b4d2..549f9fcaf 100644
--- a/src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py
+++ b/src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py
@@ -83,10 +83,10 @@ PROGRAM_IN = (
"a=0.0\n"
"end program main\n")
PROGRAM_OUT = (
- "PROGRAM main\n"
- " REAL :: a\n"
- " a = 0.0\n"
- "END PROGRAM main")
+ "program main\n"
+ " real :: a\n\n"
+ " a = 0.0\n\n"
+ "end program main\n")
FUNCTION_IN = (
"integer function tmp(a)\n"
"real :: a\n"
@@ -102,7 +102,7 @@ FUNCTION_OUT = (
@pytest.mark.parametrize("code,expected,node_class",
[(MODULE_IN, MODULE_OUT, Container),
(SUB_IN, SUB_OUT, Routine),
- (PROGRAM_IN, PROGRAM_OUT, CodeBlock),
+ (PROGRAM_IN, PROGRAM_OUT, Routine),
(FUNCTION_IN, FUNCTION_OUT, CodeBlock)])
def test_generate_psyir(parser, code, expected, node_class):
'''Test that generate_psyir generates PSyIR from an fparser2 parse
diff --git a/src/psyclone/tests/psyir/frontend/fparser2_main_program_handler_test.py b/src/psyclone/tests/psyir/frontend/fparser2_main_program_handler_test.py
new file mode 100644
index 000000000..7362de4d5
--- /dev/null
+++ b/src/psyclone/tests/psyir/frontend/fparser2_main_program_handler_test.py
@@ -0,0 +1,96 @@
+# -----------------------------------------------------------------------------
+# BSD 3-Clause License
+#
+# Copyright (c) 2021, Science and Technology Facilities Council.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# * Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# -----------------------------------------------------------------------------
+# Author R. W. Ford, STFC Daresbury Lab
+
+'''Module containing pytest tests for the _main_program_handler method
+in the class Fparser2Reader. This handler deals with the translation
+of the fparser2 Main_Program construct to PSyIR.
+
+'''
+from __future__ import absolute_import
+import pytest
+
+from fparser.common.readfortran import FortranStringReader
+from psyclone.psyir.nodes import Routine
+from psyclone.psyir.frontend.fparser2 import Fparser2Reader
+from psyclone.psyir.backend.fortran import FortranWriter
+
+# program no declarations
+PROG1_IN = (
+ "program prog\n"
+ "end program prog\n")
+PROG1_OUT = (
+ "program prog\n\n\n"
+ "end program prog\n")
+# program with symbols/declarations
+PROG2_IN = (
+ "program prog\n"
+ "real :: a\n"
+ "end program\n")
+PROG2_OUT = (
+ "program prog\n"
+ " real :: a\n\n\n"
+ "end program prog\n")
+# program with executable content
+PROG3_IN = (
+ "program prog\n"
+ "real :: a\n"
+ "a=0.0\n"
+ "end\n")
+PROG3_OUT = (
+ "program prog\n"
+ " real :: a\n\n"
+ " a = 0.0\n\n"
+ "end program prog\n")
+
+
[email protected]("code,expected",
+ [(PROG1_IN, PROG1_OUT),
+ (PROG2_IN, PROG2_OUT),
+ (PROG3_IN, PROG3_OUT)])
+def test_main_program_handler(parser, code, expected):
+ '''Test that main_program_handler handles valid Fortran subroutines.'''
+
+ processor = Fparser2Reader()
+ reader = FortranStringReader(code)
+ parse_tree = parser(reader)
+ program = parse_tree.children[0]
+ psyir = processor._main_program_handler(program, None)
+ # Check the expected PSyIR nodes are being created
+ assert isinstance(psyir, Routine)
+ assert psyir.is_program
+ assert psyir.parent is None
+ writer = FortranWriter()
+ result = writer(psyir)
+ assert expected == result
|
Support a fortran program in the PSyIR
At the moment a Fortran program will produce a code block in the PSyIR when processed using the `fparser2reader` class' `generate_psyir` method. There is an unused option in a `Routine` node (`is_program`) which specifies that the instance is a program. This could be used to translate from an fparser2 ast to PSyIR. Further, the Fortran back-end does not seem to support a Routine's `is_program` option so would also need to be updated.
|
0.0
|
313bd5a4c31a8216716ffb9a38a64835c975d5ad
|
[
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_routine_program",
"src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py::test_generate_psyir[program",
"src/psyclone/tests/psyir/frontend/fparser2_main_program_handler_test.py::test_main_program_handler[program"
] |
[
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_intent",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_intent_error",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_dims",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_dims_error",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_default_precision[Intrinsic.REAL-real]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_default_precision[Intrinsic.INTEGER-integer]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_default_precision[Intrinsic.CHARACTER-character]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_default_precision[Intrinsic.BOOLEAN-logical]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.REAL-Precision.SINGLE-real]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.REAL-Precision.DOUBLE-double",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.INTEGER-Precision.SINGLE-integer]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.INTEGER-Precision.DOUBLE-integer]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.CHARACTER-Precision.SINGLE-character]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.CHARACTER-Precision.DOUBLE-character]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.BOOLEAN-Precision.SINGLE-logical]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_relative_precision[Intrinsic.BOOLEAN-Precision.DOUBLE-logical]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-1]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-2]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-4]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-8]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-16]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.INTEGER-integer-32]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-1]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-2]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-4]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-8]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-16]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision[Intrinsic.BOOLEAN-logical-32]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[1]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[2]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[4]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[8]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[16]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_real[32]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_absolute_precision_character",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_kind_precision[Intrinsic.REAL-real]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_kind_precision[Intrinsic.INTEGER-integer]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_kind_precision[Intrinsic.CHARACTER-character]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_kind_precision[Intrinsic.BOOLEAN-logical]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_derived_type",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_exception_1",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_datatype_exception_2",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_typedecl_validation",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_typedecl_unknown_fortran_type",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_typedecl",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_reverse_map",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_reverse_map_duplicates",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_get_fortran_operator[Operator.SIN-SIN]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_get_fortran_operator[Operator.MIN-MIN]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_get_fortran_operator[Operator.SUM-SUM]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_get_fortran_operator_error",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_is_fortran_intrinsic",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_precedence",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_precedence_error",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_gen_use",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_gen_vardecl",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_decls",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_decls_routine",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_gen_routine_access_stmts",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_exception",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_container_1",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_container_2",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_container_3",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_container_4",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_routine",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator[mod]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator[max]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator[min]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator[sign]",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator_sum",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator_matmul",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator_unknown",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_binaryoperator_precedence",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_mixed_operator_precedence",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_naryoperator",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_naryoperator_unknown",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_reference",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_arrayreference",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_arrayreference_incomplete",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_range",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_structureref",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_arrayofstructuresref",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_arrayofstructuresmember",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_ifblock",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_loop",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_unaryoperator",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_unaryoperator2",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_unaryoperator_unknown",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_return",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_codeblock_1",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_codeblock_2",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_codeblock_3",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_query_intrinsics",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_literal_node",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_call_node",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_unknown_decln_error",
"src/psyclone/tests/psyir/backend/fortran_test.py::test_fw_unknown_decln",
"src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py::test_generate_psyir[module",
"src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py::test_generate_psyir[subroutine",
"src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py::test_generate_psyir[integer",
"src/psyclone/tests/psyir/frontend/fparser2_generate_psyir_test.py::test_generate_psyir_error"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-28 22:16:30+00:00
|
bsd-3-clause
| 5,717 |
|
stfc__PSyclone-1150
|
diff --git a/changelog b/changelog
index 3800fe5a3..6938211e2 100644
--- a/changelog
+++ b/changelog
@@ -434,6 +434,9 @@
140) PR #1144 for #1136. Add checks that PSyIR nodes are only children
of one parent.
+ 141) PR #1150 for #1146. Fixed bug in PSyIR, making the name
+ matching in the Node swap method case insensitive.
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/symbols/symboltable.py b/src/psyclone/psyir/symbols/symboltable.py
index 5d9df53a1..a2fe85132 100644
--- a/src/psyclone/psyir/symbols/symboltable.py
+++ b/src/psyclone/psyir/symbols/symboltable.py
@@ -595,7 +595,7 @@ class SymbolTable(object):
:raises TypeError: if either old/new_symbol are not Symbols.
:raises SymbolError: if `old_symbol` and `new_symbol` don't have \
- the same name.
+ the same name (after normalising).
'''
if not isinstance(old_symbol, Symbol):
raise TypeError("Symbol to remove must be of type Symbol but "
@@ -603,7 +603,10 @@ class SymbolTable(object):
if not isinstance(new_symbol, Symbol):
raise TypeError("Symbol to add must be of type Symbol but "
"got '{0}'".format(type(new_symbol).__name__))
- if old_symbol.name != new_symbol.name:
+ # The symbol table is not case sensitive so we must normalise the
+ # symbol names before comparing them.
+ if (self._normalize(old_symbol.name) !=
+ self._normalize(new_symbol.name)):
raise SymbolError(
"Cannot swap symbols that have different names, got: '{0}' "
"and '{1}'".format(old_symbol.name, new_symbol.name))
|
stfc/PSyclone
|
f37b0d021bc86eeb4c8da784eae15435d1ef598d
|
diff --git a/src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py b/src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py
index 45295197a..b89c509e3 100644
--- a/src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py
+++ b/src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py
@@ -154,8 +154,10 @@ def test_name_clash_derived_type_def(f2008_parser):
@pytest.mark.usefixtures("f2008_parser")
@pytest.mark.parametrize("use_stmt", ["use grid_mod, only: grid_type",
+ "use grid_mod, only: GRID_TYPE",
"use grid_mod"])
-def test_parse_derived_type(use_stmt):
[email protected]("type_name", ["GRID_TYPE", "grid_type"])
+def test_parse_derived_type(use_stmt, type_name):
''' Check that the fronted correctly creates a TypeSymbol of type
StructureType from the declaration of a derived type. '''
fake_parent = KernelSchedule("dummy_schedule")
@@ -164,10 +166,11 @@ def test_parse_derived_type(use_stmt):
reader = FortranStringReader("{0}\n"
"type :: my_type\n"
" integer :: flag\n"
- " type(grid_type), private :: grid\n"
+ " type({1}), private :: grid\n"
" real, dimension(3) :: posn\n"
"end type my_type\n"
- "type(my_type) :: var\n".format(use_stmt))
+ "type(my_type) :: var\n".format(use_stmt,
+ type_name))
fparser2spec = Fortran2003.Specification_Part(reader)
processor.process_declarations(fake_parent, fparser2spec.content, [])
sym = symtab.lookup("my_type")
diff --git a/src/psyclone/tests/psyir/symbols/symboltable_test.py b/src/psyclone/tests/psyir/symbols/symboltable_test.py
index 72b21fd8a..4fde3e0ff 100644
--- a/src/psyclone/tests/psyir/symbols/symboltable_test.py
+++ b/src/psyclone/tests/psyir/symbols/symboltable_test.py
@@ -490,8 +490,9 @@ def test_swap_symbol():
assert ("Cannot swap symbols that have different names, got: 'var1' and "
"'var2'" in str(err.value))
# Finally, check that the method correctly adds the new symbol to the
- # table and removes the old one.
- symbol3 = DataSymbol("var1", REAL_TYPE)
+ # table and removes the old one (even if the case of the name of the
+ # new symbol differs from the original).
+ symbol3 = DataSymbol("Var1", REAL_TYPE)
sym_table.swap(symbol1, symbol3)
assert sym_table.lookup("var1") is symbol3
assert symbol1 not in sym_table._symbols
@@ -536,7 +537,9 @@ def test_swap_symbol_properties():
sym_table.swap_symbol_properties(symbol1, symbol4)
assert "Symbol 'var2' is not in the symbol table." in str(excinfo.value)
- # Raise exception if both symbols have the same name
+ # Raise exception if both symbols have the same name. The only way this
+ # can currently occur is if they are the same symbol (as the normalised
+ # symbol name is used as the key in the symbol table).
with pytest.raises(ValueError) as excinfo:
sym_table.swap_symbol_properties(symbol1, symbol1)
assert("The symbols should have different names, but found 'var1' for "
|
Swapping of symbols is case sensitive (and shouldn't be).
As reported by Simon:
$ psyclone -api nemo -l output src/TOP/trc.F90
Error, unexpected exception, please report to the authors:
Description ...
PSyclone SymbolTable error: Error when generating Container for module 'trc': Cannot swap symbols that have different names, got: 'obc_data' and 'OBC_DATA'
Type ...
<class 'psyclone.psyir.symbols.symbol.SymbolError'>
Stacktrace ...
[Stacktrace omitted]
When I rename 'OBC_DATA' to 'obc_data' in trc.F90, PSyclone seems to process the file well.
|
0.0
|
f37b0d021bc86eeb4c8da784eae15435d1ef598d
|
[
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_parse_derived_type[GRID_TYPE-use",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_swap_symbol"
] |
[
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_deferred_derived_type[my_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_deferred_derived_type[MY_TYPE]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_deferred_derived_type[mY_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_missing_derived_type",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_name_clash_derived_type[my_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_name_clash_derived_type[MY_TYPE]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_name_clash_derived_type[mY_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_name_clash_derived_type_def",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_parse_derived_type[grid_type-use",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_self_ref[my_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_self_ref[MY_TYPE]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_self_ref[mY_type]",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_accessibility",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_ref",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_array_of_derived_type_ref",
"src/psyclone/tests/psyir/frontend/fparser2_derived_type_test.py::test_derived_type_codeblocks",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_instance",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_parent_symbol_table",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_next_available_name_2",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_next_available_name_3",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_next_available_name_4",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_new_symbol_5",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_add_1",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_add_with_tags_1",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_add_with_tags_hierachical",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_imported_symbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_genericsymbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_routineymbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_containersymbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_unsupported_types",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_case_insensitive[var1]",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_case_insensitive[vAr1]",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_remove_case_insensitive[VAR1]",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_swap_symbol_properties",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_1",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_2",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_3",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_4",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_with_tag_1",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_with_tag_2",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_lookup_with_tag_3",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_view",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_can_be_printed",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_specify_argument_list",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_specify_arg_list_errors",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_argument_list_errors",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_validate_non_args",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_contains",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_symbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_local_datasymbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_global_symbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_abstract_properties",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_unresolved",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_copy_external_global",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_normalization",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_shallow_copy",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_get_symbols",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_get_tags",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_symbols_tags_dict",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_new_symbol",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_symbol_from_tag",
"src/psyclone/tests/psyir/symbols/symboltable_test.py::test_rename_symbol"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-09 11:50:42+00:00
|
bsd-3-clause
| 5,718 |
|
stfc__PSyclone-1165
|
diff --git a/changelog b/changelog
index d89377fea..9338cac02 100644
--- a/changelog
+++ b/changelog
@@ -453,6 +453,9 @@
that the 'same space' option is now provided with the options
dict, in line with the way other transformations work.
+ 147) PR #1165 for #1164. Update PSyIR Assignment node
+ is_array_range test to work with structures.
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/nodes/assignment.py b/src/psyclone/psyir/nodes/assignment.py
index b4d6772b3..1a0a99d0c 100644
--- a/src/psyclone/psyir/nodes/assignment.py
+++ b/src/psyclone/psyir/nodes/assignment.py
@@ -39,9 +39,12 @@
''' This module contains the Assignment node implementation.'''
import re
+from psyclone.psyir.nodes.array_reference import ArrayReference
+from psyclone.psyir.nodes.ranges import Range
from psyclone.psyir.nodes.statement import Statement
from psyclone.psyir.nodes.datanode import DataNode
from psyclone.psyir.nodes.structure_reference import StructureReference
+from psyclone.psyir.nodes.operation import Operation, REDUCTION_OPERATORS
from psyclone.core.access_info import VariablesAccessInfo, AccessType
from psyclone.errors import InternalError
from psyclone.f2pygen import PSyIRGen
@@ -188,16 +191,37 @@ class Assignment(Statement):
@property
def is_array_range(self):
'''
- returns: True if the lhs of the assignment is an array with at \
- least one of its dimensions being a range and False \
- otherwise.
+ returns: True if the lhs of the assignment is an array access with at \
+ least one of its dimensions being a range and False otherwise.
rtype: bool
'''
- from psyclone.psyir.nodes import ArrayReference, Range
- if not isinstance(self.lhs, ArrayReference):
- return False
- return any(dim for dim in self.lhs.children if isinstance(dim, Range))
+ # It's not sufficient simply to check for a Range node as that may be
+ # part of an argument to an Operator or function that performs a
+ # reduction and thus returns a scalar result, e.g. a(SUM(b(:))) = 1.0
+ # TODO #658 this check for reductions needs extending to also support
+ # user-implemented functions.
+ if isinstance(self.lhs, (ArrayReference, StructureReference)):
+ ranges = self.lhs.walk(Range)
+ for array_range in ranges:
+ opn = array_range.ancestor(Operation)
+ while opn:
+ if opn.operator in REDUCTION_OPERATORS:
+ # The current array range is in an argument to a
+ # reduction operation so we assume that the result
+ # is a scalar.
+ # TODO 658 this could still be a reduction into an
+ # array (e.g. SUM(a(:,:), 1)) but we need to be able
+ # to interrogate the type of a PSyIR expression in
+ # order to be sure. e.g. SUM(a(:,:), mask(:,:)) will
+ # return a scalar.
+ break
+ opn = opn.ancestor(Operation)
+ else:
+ # We didn't find a reduction operation so there is an
+ # array range on the LHS
+ return True
+ return False
def gen_code(self, parent):
'''F2pygen code generation of an Assignment.
diff --git a/src/psyclone/psyir/nodes/operation.py b/src/psyclone/psyir/nodes/operation.py
index 6b607e1b2..e5102c257 100644
--- a/src/psyclone/psyir/nodes/operation.py
+++ b/src/psyclone/psyir/nodes/operation.py
@@ -398,3 +398,14 @@ class NaryOperation(Operation):
for child in children:
child.parent = nary_op
return nary_op
+
+
+# TODO #658 this can be removed once we have support for determining the
+# type of a PSyIR expression.
+#: Those operators that perform a reduction on an array.
+REDUCTION_OPERATORS = [UnaryOperation.Operator.SUM,
+ BinaryOperation.Operator.SUM,
+ NaryOperation.Operator.SUM]
+
+# For automatic API documentation generation
+__all__ = ["Operation", "UnaryOperation", "BinaryOperation", "NaryOperation"]
|
stfc/PSyclone
|
64b7091bcca32a10378a36c5e79e876163681e53
|
diff --git a/src/psyclone/tests/psyir/nodes/assignment_test.py b/src/psyclone/tests/psyir/nodes/assignment_test.py
index ac1ad34dc..a753df704 100644
--- a/src/psyclone/tests/psyir/nodes/assignment_test.py
+++ b/src/psyclone/tests/psyir/nodes/assignment_test.py
@@ -41,9 +41,11 @@
from __future__ import absolute_import
import pytest
from psyclone.psyir.nodes import Assignment, Reference, Literal, \
- ArrayReference, Range
-from psyclone.psyir.symbols import DataSymbol, REAL_SINGLE_TYPE, \
- INTEGER_SINGLE_TYPE, REAL_TYPE, ArrayType, INTEGER_TYPE
+ ArrayReference, Range, BinaryOperation, StructureReference, \
+ ArrayOfStructuresReference, UnaryOperation
+from psyclone.psyir.symbols import DataSymbol, REAL_SINGLE_TYPE, Symbol, \
+ INTEGER_SINGLE_TYPE, REAL_TYPE, ArrayType, INTEGER_TYPE, StructureType, \
+ TypeSymbol
from psyclone.errors import InternalError, GenerationError
from psyclone.psyir.backend.fortran import FortranWriter
from psyclone.tests.utilities import check_links
@@ -133,28 +135,182 @@ def test_assignment_children_validation():
def test_is_array_range():
'''test that the is_array_range method behaves as expected, returning
- true if the LHS of the assignment is an array range access and
- false otherwise.
+ true if the LHS of the assignment is an array range access.
'''
one = Literal("1.0", REAL_TYPE)
int_one = Literal("1", INTEGER_TYPE)
+ int_ten = Literal("10", INTEGER_TYPE)
+
+ # lhs is an array reference with a range
+ array_type = ArrayType(REAL_TYPE, [10, 10])
+ symbol = DataSymbol("x", array_type)
+ x_range = Range.create(int_one, int_ten.copy(), int_one.copy())
+ array_ref = ArrayReference.create(symbol, [x_range, int_one.copy()])
+ assignment = Assignment.create(array_ref, one.copy())
+ assert assignment.is_array_range is True
+
+ # Check when lhs consists of various forms of structure access
+ grid_type = StructureType.create([
+ ("dx", REAL_SINGLE_TYPE, Symbol.Visibility.PUBLIC),
+ ("dy", REAL_SINGLE_TYPE, Symbol.Visibility.PUBLIC)])
+ grid_type_symbol = TypeSymbol("grid_type", grid_type)
+ # Create the definition of the 'field_type', contains array of grid_types
+ field_type_def = StructureType.create(
+ [("data", ArrayType(REAL_SINGLE_TYPE, [10]), Symbol.Visibility.PUBLIC),
+ ("sub_meshes", ArrayType(grid_type_symbol, [3]),
+ Symbol.Visibility.PUBLIC)])
+ field_type_symbol = TypeSymbol("field_type", field_type_def)
+ field_symbol = DataSymbol("wind", field_type_symbol)
+
+ # Array reference to component of derived type using a range
+ lbound = BinaryOperation.create(
+ BinaryOperation.Operator.LBOUND,
+ StructureReference.create(field_symbol, ["data"]), int_one.copy())
+ ubound = BinaryOperation.create(
+ BinaryOperation.Operator.UBOUND,
+ StructureReference.create(field_symbol, ["data"]), int_one.copy())
+ my_range = Range.create(lbound, ubound)
+
+ data_ref = StructureReference.create(field_symbol, [("data", [my_range])])
+ assign = Assignment.create(data_ref, one.copy())
+ assert assign.is_array_range is True
+
+ # Access to slice of 'sub_meshes': wind%sub_meshes(1:3)%dx = 1.0
+ sub_range = Range.create(int_one.copy(), Literal("3", INTEGER_TYPE))
+ dx_ref = StructureReference.create(field_symbol, [("sub_meshes",
+ [sub_range]), "dx"])
+ sub_assign = Assignment.create(dx_ref, one.copy())
+ assert sub_assign.is_array_range is True
+
+ # Create an array of these derived types and assign to a slice:
+ # chi(1:10)%data(1) = 1.0
+ field_bundle_symbol = DataSymbol("chi", ArrayType(field_type_symbol, [3]))
+ fld_range = Range.create(int_one.copy(), Literal("10", INTEGER_TYPE))
+ fld_ref = ArrayOfStructuresReference.create(field_bundle_symbol,
+ [fld_range],
+ [("data", [int_one.copy()])])
+ fld_assign = Assignment.create(fld_ref, one.copy())
+ assert fld_assign.is_array_range is True
+
+ # When the slice has two operator ancestors, none of which are a reduction
+ # e.g y(1, INT(ABS(map(:, 1)))) = 1.0
+ int_array_type = ArrayType(INTEGER_SINGLE_TYPE, [10, 10])
+ map_sym = DataSymbol("map", int_array_type)
+ lbound1 = BinaryOperation.create(
+ BinaryOperation.Operator.LBOUND,
+ Reference(map_sym), int_one.copy())
+ ubound1 = BinaryOperation.create(
+ BinaryOperation.Operator.UBOUND,
+ Reference(map_sym), int_one.copy())
+ my_range1 = Range.create(lbound1, ubound1)
+ abs_op = UnaryOperation.create(UnaryOperation.Operator.ABS,
+ ArrayReference.create(map_sym,
+ [my_range1,
+ int_one.copy()]))
+ int_op = UnaryOperation.create(UnaryOperation.Operator.INT, abs_op)
+ assignment = Assignment.create(
+ ArrayReference.create(symbol, [int_one.copy(), int_op]),
+ one.copy())
+ assert assignment.is_array_range is True
+
+
[email protected](reason="#658 needs typing of PSyIR expressions")
+def test_array_range_with_reduction():
+ ''' Test that we correctly identify an array range when it is the result
+ of a reduction from an array, e.g x(1, INT(SUM(map(:, :), 1))) = 1.0
+
+ '''
+ one = Literal("1.0", REAL_TYPE)
+ int_one = Literal("1", INTEGER_TYPE)
+ int_two = Literal("2", INTEGER_TYPE)
+ int_array_type = ArrayType(INTEGER_SINGLE_TYPE, [10, 10])
+ map_sym = DataSymbol("map", int_array_type)
+ array_type = ArrayType(REAL_TYPE, [10, 10])
+ symbol = DataSymbol("x", array_type)
+ lbound1 = BinaryOperation.create(
+ BinaryOperation.Operator.LBOUND,
+ Reference(map_sym), int_one.copy())
+ ubound1 = BinaryOperation.create(
+ BinaryOperation.Operator.UBOUND,
+ Reference(map_sym), int_one.copy())
+ my_range1 = Range.create(lbound1, ubound1)
+ lbound2 = BinaryOperation.create(
+ BinaryOperation.Operator.LBOUND,
+ Reference(map_sym), int_two.copy())
+ ubound2 = BinaryOperation.create(
+ BinaryOperation.Operator.UBOUND,
+ Reference(map_sym), int_two.copy())
+ my_range2 = Range.create(lbound2, ubound2)
+ bsum_op = BinaryOperation.create(BinaryOperation.Operator.SUM,
+ ArrayReference.create(map_sym,
+ [my_range1,
+ my_range2]),
+ int_one.copy())
+ int_op2 = UnaryOperation.create(UnaryOperation.Operator.INT, bsum_op)
+ assignment = Assignment.create(
+ ArrayReference.create(symbol,
+ [int_one.copy(), int_op2]),
+ one.copy())
+ assert assignment.is_array_range is True
+
+
+def test_is_not_array_range():
+ ''' Test that is_array_range correctly rejects things that aren't
+ an assignment to an array range.
+
+ '''
+ int_one = Literal("1", INTEGER_SINGLE_TYPE)
+ one = Literal("1.0", REAL_TYPE)
var = DataSymbol("x", REAL_TYPE)
reference = Reference(var)
# lhs is not an array
assignment = Assignment.create(reference, one)
- assert not assignment.is_array_range
+ assert assignment.is_array_range is False
# lhs is an array reference but has no range
array_type = ArrayType(REAL_TYPE, [10, 10])
- symbol = DataSymbol("x", array_type)
+ symbol = DataSymbol("y", array_type)
array_ref = Reference(symbol)
assignment = Assignment.create(array_ref, one.copy())
- assert not assignment.is_array_range
+ assert assignment.is_array_range is False
- # lhs is an array reference with a range
- my_range = Range.create(int_one, int_one.copy(), int_one.copy())
- array_ref = ArrayReference.create(symbol, [my_range, int_one.copy()])
- assignment = Assignment.create(array_ref, one.copy())
- assert assignment.is_array_range
+ # lhs is an array reference but the single index value is obtained
+ # using an array range, y(1, SUM(map(:), 1)) = 1.0
+ int_array_type = ArrayType(INTEGER_SINGLE_TYPE, [10])
+ map_sym = DataSymbol("map", int_array_type)
+ start = BinaryOperation.create(BinaryOperation.Operator.LBOUND,
+ Reference(map_sym), int_one.copy())
+ stop = BinaryOperation.create(BinaryOperation.Operator.UBOUND,
+ Reference(map_sym), int_one.copy())
+ my_range = Range.create(start, stop)
+ sum_op = BinaryOperation.create(BinaryOperation.Operator.SUM,
+ ArrayReference.create(map_sym, [my_range]),
+ int_one.copy())
+ assignment = Assignment.create(
+ ArrayReference.create(symbol, [int_one.copy(), sum_op]),
+ one.copy())
+ assert assignment.is_array_range is False
+
+ # When the slice has two operator ancestors, one of which is a reduction
+ # e.g y(1, SUM(ABS(map(:)), 1)) = 1.0
+ abs_op = UnaryOperation.create(UnaryOperation.Operator.ABS,
+ ArrayReference.create(map_sym,
+ [my_range.copy()]))
+ sum_op2 = BinaryOperation.create(BinaryOperation.Operator.SUM,
+ abs_op, int_one.copy())
+ assignment = Assignment.create(
+ ArrayReference.create(symbol, [int_one.copy(), sum_op2]),
+ one.copy())
+ assert assignment.is_array_range is False
+
+ # lhs is a scalar member of a structure
+ grid_type = StructureType.create([
+ ("dx", REAL_SINGLE_TYPE, Symbol.Visibility.PUBLIC),
+ ("dy", REAL_SINGLE_TYPE, Symbol.Visibility.PUBLIC)])
+ grid_type_symbol = TypeSymbol("grid_type", grid_type)
+ grid_sym = DataSymbol("grid", grid_type_symbol)
+ assignment = Assignment.create(StructureReference.create(grid_sym, ["dx"]),
+ one.copy())
+ assert assignment.is_array_range is False
|
[psyir] Assignment.is_array_range does not work for Structures
Currently, `Assignment.is_array_range` only checks that the lhs is an `ArrayReference`. Now that we can have e.g.
some_struc(ji)%data(:,:) = 0.0
this is clearly insufficient and results in missed parallelisation opportunities when processing NEMO, as reported by @deardenchris .
|
0.0
|
64b7091bcca32a10378a36c5e79e876163681e53
|
[
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_is_array_range"
] |
[
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_assignment_node_str",
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_assignment_can_be_printed",
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_assignment_semantic_navigation",
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_assignment_create",
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_assignment_children_validation",
"src/psyclone/tests/psyir/nodes/assignment_test.py::test_is_not_array_range"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-18 12:59:27+00:00
|
bsd-3-clause
| 5,719 |
|
stfc__PSyclone-1674
|
diff --git a/changelog b/changelog
index 7f1ac5de8..8fa269897 100644
--- a/changelog
+++ b/changelog
@@ -4,6 +4,8 @@
2) PR #1670 for #1650. Fixes various inconsistencies in the symbol
table implementation.
+ 3) PR #1674 for #1644. Fixes bug in matmul transformation.
+
release 2.2.0 17th March 2022
1) PR #1439 for #1074. Adds a GOcean example for the use of the NaN-
diff --git a/src/psyclone/psyir/transformations/intrinsics/matmul2code_trans.py b/src/psyclone/psyir/transformations/intrinsics/matmul2code_trans.py
index b898bc4e8..ead3d63b9 100644
--- a/src/psyclone/psyir/transformations/intrinsics/matmul2code_trans.py
+++ b/src/psyclone/psyir/transformations/intrinsics/matmul2code_trans.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2020-2021, Science and Technology Facilities Council
+# Copyright (c) 2020-2022, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -31,8 +31,9 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# -----------------------------------------------------------------------------
-# Author: R. W. Ford, STFC Daresbury Lab
+# Author: R. W. Ford, STFC Daresbury Laboratory
# Modified: S. Siso, STFC Daresbury Laboratory
+# A. R. Porter, STFC Daresbury Laboratory
'''Module providing a transformation from a PSyIR MATMUL operator to
PSyIR code. This could be useful if the MATMUL operator is not
@@ -42,9 +43,8 @@ matrix vector multiply. At the moment this transformation is limited
to matrix vector multiply.
'''
-from __future__ import absolute_import
from psyclone.psyir.nodes import BinaryOperation, Assignment, Reference, \
- Loop, Literal, ArrayReference, Range, DataNode
+ Loop, Literal, ArrayReference, Range
from psyclone.psyir.symbols import DataSymbol, INTEGER_TYPE, REAL_TYPE, \
ArrayType
from psyclone.psyir.transformations.intrinsics.operator2code_trans import \
@@ -78,8 +78,9 @@ def _get_array_bound(array, index):
my_dim = array.symbol.shape[index]
if isinstance(my_dim, ArrayType.ArrayBounds):
- lower_bound = my_dim.lower
- upper_bound = my_dim.upper
+ # Use .copy() to ensure we return new nodes.
+ lower_bound = my_dim.lower.copy()
+ upper_bound = my_dim.upper.copy()
elif my_dim in [ArrayType.Extent.DEFERRED, ArrayType.Extent.ATTRIBUTE]:
lower_bound = BinaryOperation.create(
BinaryOperation.Operator.LBOUND, Reference(array.symbol),
@@ -89,8 +90,8 @@ def _get_array_bound(array, index):
Literal(str(index), INTEGER_TYPE))
else:
raise TransformationError(
- "Unsupported index type '{0}' found for dimension {1} of array "
- "'{2}'.".format(type(my_dim).__name__, index+1, array.name))
+ f"Unsupported index type '{type(my_dim).__name__}' found for "
+ f"dimension {index+1} of array '{array.name}'.")
step = Literal("1", INTEGER_TYPE)
return (lower_bound, upper_bound, step)
@@ -163,34 +164,32 @@ class Matmul2CodeTrans(Operator2CodeTrans):
if not (isinstance(matrix, Reference) and
isinstance(vector, Reference)):
raise TransformationError(
- "Expected children of a MATMUL BinaryOperation to be "
- "references, but found '{0}', '{1}'."
- "".format(type(matrix).__name__,
- type(vector).__name__))
+ f"Expected children of a MATMUL BinaryOperation to be "
+ f"references, but found '{type(matrix).__name__}', "
+ f"'{type(vector).__name__}'.")
# The children of matvec should be References to arrays
if not (matrix.symbol.shape or vector.symbol.shape):
raise TransformationError(
- "Expected children of a MATMUL BinaryOperation to be "
- "references to arrays, but found '{0}', '{1}'."
- "".format(type(matrix.symbol).__name__,
- type(vector.symbol).__name__))
+ f"Expected children of a MATMUL BinaryOperation to be "
+ f"references to arrays, but found "
+ f"'{type(matrix.symbol).__name__}', "
+ f"'{type(vector.symbol).__name__}'.")
# The first child (the matrix) should be declared as an array
# with at least 2 dimensions
if len(matrix.symbol.shape) < 2:
raise TransformationError(
- "Expected 1st child of a MATMUL BinaryOperation to be "
- "a matrix with at least 2 dimensions, but found '{0}'."
- "".format(len(matrix.symbol.shape)))
+ f"Expected 1st child of a MATMUL BinaryOperation to be a "
+ f"matrix with at least 2 dimensions, but found "
+ f"'{len(matrix.symbol.shape)}'.")
+
if len(matrix.symbol.shape) > 2 and not matrix.children:
# If the matrix has no children then it is a reference. If
- # it is a reference then the number of arguments must be
- # 2.
+ # it is a reference then the number of arguments must be 2.
raise TransformationError(
- "Expected 1st child of a MATMUL BinaryOperation to have 2 "
- "dimensions, but found '{0}'."
- "".format(len(matrix.symbol.shape)))
+ f"Expected 1st child of a MATMUL BinaryOperation to have 2 "
+ f"dimensions, but found '{len(matrix.symbol.shape)}'.")
if len(matrix.symbol.shape) == 2 and not matrix.children:
# If the matrix only has 2 dimensions and all of its data is
# used in the matrix vector multiply then the reference does
@@ -208,28 +207,27 @@ class Matmul2CodeTrans(Operator2CodeTrans):
# dimension.
if not (matrix.is_full_range(0) and matrix.is_full_range(1)):
raise NotImplementedError(
- "To use matmul2code_trans on matmul, indices 0 and 1 of "
- "the 1st (matrix) argument '{0}' must be full ranges."
- "".format(matrix.name))
+ f"To use matmul2code_trans on matmul, indices 0 and 1 of "
+ f"the 1st (matrix) argument '{matrix.name}' must be full "
+ f"ranges.")
if len(matrix.children) > 2:
# The 3rd index and onwards must not be ranges.
for (count, index) in enumerate(matrix.children[2:]):
if isinstance(index, Range):
raise NotImplementedError(
- "To use matmul2code_trans on matmul, only the "
- "first two indices of the 1st (matrix) argument "
- "are permitted to be Ranges but found {0} at "
- "index {1}.".format(type(index).__name__, count+2))
+ f"To use matmul2code_trans on matmul, only the "
+ f"first two indices of the 1st (matrix) argument "
+ f"are permitted to be Ranges but found "
+ f"{type(index).__name__} at index {count+2}.")
if len(vector.symbol.shape) > 1 and not vector.children:
# If the vector has no children then it is a reference. If
# it is a reference then the number of arguments must be
# 1.
raise TransformationError(
- "Expected 2nd child of a MATMUL BinaryOperation to have 1 "
- "dimension, but found '{0}'."
- "".format(len(vector.symbol.shape)))
+ f"Expected 2nd child of a MATMUL BinaryOperation to have 1 "
+ f"dimension, but found '{len(vector.symbol.shape)}'.")
if len(vector.symbol.shape) == 1 and not vector.children:
# If the vector only has 1 dimension and all of its data is
# used in the matrix vector multiply then the reference does
@@ -244,18 +242,17 @@ class Matmul2CodeTrans(Operator2CodeTrans):
# specify the full extent of the dimension.
if not vector.is_full_range(0):
raise NotImplementedError(
- "To use matmul2code_trans on matmul, index 0 of the 2nd "
- "(vector) argument '{0}' must be a full range."
- "".format(matrix.name))
+ f"To use matmul2code_trans on matmul, index 0 of the 2nd "
+ f"(vector) argument '{vector.name}' must be a full range.")
if len(vector.children) > 1:
# The 2nd index and onwards must not be ranges.
for (count, index) in enumerate(vector.children[1:]):
if isinstance(index, Range):
raise NotImplementedError(
- "To use matmul2code_trans on matmul, only the "
- "first index of the 2nd (vector) argument is "
- "permitted to be a Range but found {0} at index "
- "{1}.".format(type(index).__name__, count+1))
+ f"To use matmul2code_trans on matmul, only the "
+ f"first index of the 2nd (vector) argument is "
+ f"permitted to be a Range but found "
+ f"{type(index).__name__} at index {count+1}.")
def apply(self, node, options=None):
'''Apply the MATMUL intrinsic conversion transformation to the
|
stfc/PSyclone
|
d2dd5bc68d01cfd0038690968469b42425d515ee
|
diff --git a/src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py b/src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py
index c704e5f99..433642b4a 100644
--- a/src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py
+++ b/src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2020-2021, Science and Technology Facilities Council
+# Copyright (c) 2020-2022, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -31,11 +31,10 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# -----------------------------------------------------------------------------
-# Authors R. W. Ford and S. Siso, STFC Daresbury Lab
+# Authors R. W. Ford, A. R. Porter and S. Siso, STFC Daresbury Laboratory
'''Module containing tests for the matmul2code transformation.'''
-from __future__ import absolute_import
import pytest
from psyclone.psyir.transformations import Matmul2CodeTrans, \
TransformationError
@@ -331,7 +330,7 @@ def test_validate12():
with pytest.raises(NotImplementedError) as excinfo:
trans.validate(matmul)
assert ("To use matmul2code_trans on matmul, index 0 of the 2nd (vector) "
- "argument 'x' must be a full range." in str(excinfo.value))
+ "argument 'y' must be a full range." in str(excinfo.value))
def test_validate13():
@@ -539,7 +538,8 @@ def test_get_array_bound_error():
def test_get_array_bound():
'''Test that the _get_array_bound utility function returns the expected
- bound values for different types of array declaration.
+ bound values for different types of array declaration. Also checks that
+ new nodes are created each time the utility is called.
'''
scalar_symbol = DataSymbol("n", INTEGER_TYPE, constant_value=20)
@@ -559,6 +559,11 @@ def test_get_array_bound():
assert isinstance(step, Literal)
assert step.value == "1"
assert step.datatype.intrinsic == ScalarType.Intrinsic.INTEGER
+ # Check that the method creates new nodes each time.
+ (lower_bound2, upper_bound2, step2) = _get_array_bound(reference, 0)
+ assert lower_bound2 is not lower_bound
+ assert upper_bound2 is not upper_bound
+ assert step2 is not step
# symbol
(lower_bound, upper_bound, step) = _get_array_bound(reference, 1)
assert isinstance(lower_bound, Literal)
@@ -569,6 +574,11 @@ def test_get_array_bound():
assert isinstance(step, Literal)
assert step.value == "1"
assert step.datatype.intrinsic == ScalarType.Intrinsic.INTEGER
+ # Check that the method creates new nodes each time.
+ (lower_bound2, upper_bound2, step2) = _get_array_bound(reference, 1)
+ assert lower_bound2 is not lower_bound
+ assert upper_bound2 is not upper_bound
+ assert step2 is not step
# deferred and attribute
def _check_ulbound(lower_bound, upper_bound, step, index):
@@ -598,5 +608,13 @@ def test_get_array_bound():
assert step.datatype.intrinsic == ScalarType.Intrinsic.INTEGER
(lower_bound, upper_bound, step) = _get_array_bound(reference, 2)
_check_ulbound(lower_bound, upper_bound, step, 2)
+ (lower_bound2, upper_bound2, step2) = _get_array_bound(reference, 2)
+ assert lower_bound2 is not lower_bound
+ assert upper_bound2 is not upper_bound
+ assert step2 is not step
(lower_bound, upper_bound, step) = _get_array_bound(reference, 3)
_check_ulbound(lower_bound, upper_bound, step, 3)
+ (lower_bound2, upper_bound2, step2) = _get_array_bound(reference, 3)
+ assert lower_bound2 is not lower_bound
+ assert upper_bound2 is not upper_bound
+ assert step2 is not step
|
matmul2code transformation is failing
From `tl_vorticity_advection_kernel_mod.F90`, after manually making matmul the only thing on the rhs of an assignment in two cases ...
```
...
matmul1 = matmul( jac, ls_vorticity_at_quad )
j_ls_vorticity(:) = wqp_h(qp1) * wqp_v(qp2) * &
matmul1(:)
matmul2 = matmul( jac, vorticity_at_quad )
j_vorticity(:) = wqp_h(qp1) * wqp_v(qp2) * &
matmul2(:)
...
```
we get the following error matmul2code transformation error ...
```
psyclone.errors.GenerationError: Generation Error: Item 'Literal' can't be added as child of 'Loop' because it is not an orphan. It already has a 'Loop' as a parent.
```
|
0.0
|
d2dd5bc68d01cfd0038690968469b42425d515ee
|
[
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate12",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_get_array_bound"
] |
[
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_initialise",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate1",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate2",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate3",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate4",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate5",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate6",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate7",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate8",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate9",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate10",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate11",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate13",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_validate14",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_apply1",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_apply2",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_apply3",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_apply4",
"src/psyclone/tests/psyir/transformations/intrinsics/matmul2code_trans_test.py::test_get_array_bound_error"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-25 20:41:09+00:00
|
bsd-3-clause
| 5,720 |
|
stfc__PSyclone-2191
|
diff --git a/changelog b/changelog
index 621f560a1..92402e14c 100644
--- a/changelog
+++ b/changelog
@@ -479,6 +479,9 @@
162) PR #2187 towards #1618. Remove builtin use statements when
lowering.
+ 163) PR #2191 for #2185. Fix element order used in PSyAD test
+ harness.
+
release 2.3.1 17th of June 2022
1) PR #1747 for #1720. Adds support for If blocks to PSyAD.
diff --git a/src/psyclone/domain/lfric/algorithm/lfric_alg.py b/src/psyclone/domain/lfric/algorithm/lfric_alg.py
index 4cca91f5e..f29a5bf17 100644
--- a/src/psyclone/domain/lfric/algorithm/lfric_alg.py
+++ b/src/psyclone/domain/lfric/algorithm/lfric_alg.py
@@ -61,11 +61,6 @@ class LFRicAlg:
layer from Kernel metadata.
'''
-
- #: The order of the finite-element scheme that will be used by any
- #: generated algorithm layer.
- _ELEMENT_ORDER = "1"
-
def create_from_kernel(self, name, kernel_path):
'''
Generates LFRic algorithm PSyIR that calls the supplied kernel through
@@ -240,9 +235,10 @@ class LFRicAlg:
def _create_function_spaces(self, prog, fspaces):
'''
- Adds PSyIR to the supplied Routine that declares and intialises the
- specified function spaces. The order of these spaces is set by the
- `_ELEMENT_ORDER` class constant.
+ Adds PSyIR to the supplied Routine that declares and intialises
+ the specified function spaces. The order of these spaces is
+ set by the element_order variable which is provided by the
+ LFRic finite_element_config_mod module.
:param prog: the routine to which to add declarations and \
initialisation.
@@ -252,20 +248,19 @@ class LFRicAlg:
:raises InternalError: if a function space is supplied that is not a \
recognised LFRic function space.
+
'''
table = prog.symbol_table
reader = FortranReader()
# The order of the finite-element scheme.
- table.add_lfric_precision_symbol("i_def")
- data_type_class = LFRicTypes("LFRicIntegerScalarDataType")
- order = table.new_symbol("element_order", tag="element_order",
- symbol_type=DataSymbol,
- datatype=data_type_class(),
- constant_value=Literal(
- self._ELEMENT_ORDER,
- data_type_class()))
+ fe_config_mod = table.new_symbol(
+ "finite_element_config_mod", symbol_type=ContainerSymbol)
+ order = table.new_symbol(
+ "element_order", tag="element_order",
+ symbol_type=DataSymbol, datatype=DeferredType(),
+ interface=ImportInterface(fe_config_mod))
fs_cont_mod = table.new_symbol("fs_continuity_mod",
symbol_type=ContainerSymbol)
|
stfc/PSyclone
|
7c9daf7175215177e84ba8ff8bcf21032c7b7fb0
|
diff --git a/src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py b/src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py
index 8aa1aa826..dbc5f56cf 100644
--- a/src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py
+++ b/src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py
@@ -126,6 +126,9 @@ def test_create_function_spaces_no_spaces(lfric_alg, prog):
''' Check that a Routine is populated as expected, even when there
are no actual function spaces. '''
lfric_alg._create_function_spaces(prog, [])
+ fe_config_mod = prog.symbol_table.lookup("finite_element_config_mod")
+ element_order = prog.symbol_table.lookup("element_order")
+ assert element_order.interface.container_symbol == fe_config_mod
assert prog.symbol_table.lookup("element_order")
assert isinstance(prog.symbol_table.lookup("fs_continuity_mod"),
ContainerSymbol)
@@ -144,6 +147,9 @@ def test_create_function_spaces(lfric_alg, prog, fortran_writer):
''' Check that a Routine is populated correctly when valid function-space
names are supplied. '''
lfric_alg._create_function_spaces(prog, ["w3", "w1"])
+ fe_config_mod = prog.symbol_table.lookup("finite_element_config_mod")
+ element_order = prog.symbol_table.lookup("element_order")
+ assert element_order.interface.container_symbol == fe_config_mod
fs_mod_sym = prog.symbol_table.lookup("fs_continuity_mod")
gen = fortran_writer(prog)
for space in ["w1", "w3"]:
diff --git a/src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py b/src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py
index d9ec943d9..4bcc6c86f 100644
--- a/src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py
+++ b/src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py
@@ -356,10 +356,11 @@ def test_init_scalar_value(monkeypatch):
# property of the datatype.
sym4 = DataSymbol("my_var", LFRicTypes("LFRicRealScalarDataType")())
- class broken_type:
+ class BrokenType:
+ '''Utility class to provide an unsupported type.'''
def __init__(self):
self.name = "wrong"
- monkeypatch.setattr(sym4.datatype, "intrinsic", broken_type())
+ monkeypatch.setattr(sym4.datatype, "intrinsic", BrokenType())
with pytest.raises(InternalError) as err:
_init_scalar_value(sym4, routine, {})
assert ("scalars of REAL, INTEGER or BOOLEAN type are supported but got "
@@ -495,6 +496,7 @@ def test_generate_lfric_adjoint_harness(fortran_reader, fortran_writer):
tl_psyir = fortran_reader.psyir_from_source(TL_CODE)
psyir = generate_lfric_adjoint_harness(tl_psyir)
gen = fortran_writer(psyir).lower()
+ assert "use finite_element_config_mod, only : element_order" in gen
assert "module adjoint_test_mod" in gen
assert "subroutine adjoint_test(mesh, chi, panel_id)" in gen
# We should have a field, a copy of that field and an inner-product value
|
include element_order from an LFRic module in PSyAD test harness
The test harness hard codes element_order to 1. However, it may have a different value and this has caused errors when validating some of the PSyAD-generated LFRic adjoint kernels. The value should instead be included from the appropriate module file `finite_element_config_mod`.
|
0.0
|
7c9daf7175215177e84ba8ff8bcf21032c7b7fb0
|
[
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_function_spaces_no_spaces",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_function_spaces",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness"
] |
[
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_alg_routine_wrong_arg_type",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_alg_routine",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_function_spaces_invalid_space",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_initialise_field",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_initialise_quadrature",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_initialise_quadrature_unsupported_shape",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_kernel_from_metadata",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_construct_kernel_args",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_from_kernel_invalid_kernel",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_from_kernel_invalid_field_type",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_from_kernel_with_scalar",
"src/psyclone/tests/domain/lfric/algorithm/lfric_alg_test.py::test_create_from_kernel_with_vector",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_compute_inner_products_scalars",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_compute_inner_products_fields",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_compute_field_inner_products",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_compute_field_vector_inner_products",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_compute_field_inner_products_errors",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_init_fields_random",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_init_fields_random_vector",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_init_fields_random_error",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_init_operators_random",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_init_scalar_value",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_validate_geom_arg",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_invalid_code",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adj_test_quadrature",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_operator",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_gen_lfric_adjoint_harness_written_operator",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_invalid_geom_arg",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_chi_arg",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_panel_id_arg",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adjoint_harness_geom_args",
"src/psyclone/tests/psyad/domain/lfric/test_lfric_adjoint_harness.py::test_generate_lfric_adj_harness_scalar_geom_arg"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-26 15:02:44+00:00
|
bsd-3-clause
| 5,721 |
|
stfc__PSyclone-2230
|
diff --git a/changelog b/changelog
index dab8c8548..060343dfb 100644
--- a/changelog
+++ b/changelog
@@ -527,6 +527,9 @@
new, associated optimisation scripts. Includes bug fixes for
matmul inlining transformation.
+ 179) PR #2230 for #2228. Improve reporting of errors due to kernel
+ functors not explicitly included in algorithm use statements.
+
release 2.3.1 17th of June 2022
1) PR #1747 for #1720. Adds support for If blocks to PSyAD.
diff --git a/src/psyclone/generator.py b/src/psyclone/generator.py
index c3d2aafc3..69dc40bdf 100644
--- a/src/psyclone/generator.py
+++ b/src/psyclone/generator.py
@@ -61,6 +61,7 @@ from psyclone.domain.common.transformations import AlgTrans
from psyclone.domain.gocean.transformations import (
RaisePSyIR2GOceanKernTrans, GOceanAlgInvoke2PSyCallTrans)
from psyclone.domain.lfric.algorithm import LFRicBuiltinFunctor
+from psyclone.domain.lfric.lfric_builtins import BUILTIN_MAP
from psyclone.domain.lfric.transformations import (
LFRicAlgTrans, RaisePSyIR2LFRicKernTrans, LFRicAlgInvoke2PSyCallTrans)
from psyclone.errors import GenerationError, InternalError
@@ -75,6 +76,7 @@ from psyclone.psyir.backend.fortran import FortranWriter
from psyclone.psyir.frontend.fortran import FortranReader
from psyclone.psyir.frontend.fparser2 import Fparser2Reader
from psyclone.psyir.nodes import Loop, Container, Routine
+from psyclone.psyir.symbols import UnresolvedInterface
from psyclone.psyir.transformations import TransformationError
from psyclone.version import __VERSION__
@@ -92,7 +94,6 @@ LFRIC_TESTING = False
def handle_script(script_name, info, function_name, is_optional=False):
- # pylint: disable=too-many-locals
'''Loads and applies the specified script to the given algorithm or
psy layer. The relevant script function (in 'function_name') is
called with 'info' as the argument.
@@ -188,34 +189,39 @@ def generate(filename, api="", kernel_paths=None, script_name=None,
:param str filename: the file containing the algorithm specification.
:param str api: the name of the API to use. Defaults to empty string.
- :param kernel_paths: the directories from which to recursively \
- search for the files containing the kernel source (if \
- different from the location of the algorithm specification). \
+ :param kernel_paths: the directories from which to recursively
+ search for the files containing the kernel source (if
+ different from the location of the algorithm specification).
Defaults to None.
:type kernel_paths: Optional[List[str]]
- :param str script_name: a script file that can apply optimisations \
- to the PSy layer (can be a path to a file or a filename that \
+ :param str script_name: a script file that can apply optimisations
+ to the PSy layer (can be a path to a file or a filename that
relies on the PYTHONPATH to find the module). Defaults to None.
- :param bool line_length: a logical flag specifying whether we care \
- about line lengths being longer than 132 characters. If so, \
- the input (algorithm and kernel) code is checked to make sure \
+ :param bool line_length: a logical flag specifying whether we care
+ about line lengths being longer than 132 characters. If so,
+ the input (algorithm and kernel) code is checked to make sure
that it conforms. The default is False.
- :param bool distributed_memory: a logical flag specifying whether \
- to generate distributed memory code. The default is set in the \
+ :param bool distributed_memory: a logical flag specifying whether
+ to generate distributed memory code. The default is set in the
'config.py' file.
- :param str kern_out_path: directory to which to write transformed \
+ :param str kern_out_path: directory to which to write transformed
kernel code. Defaults to empty string.
- :param bool kern_naming: the scheme to use when re-naming transformed \
+ :param bool kern_naming: the scheme to use when re-naming transformed
kernels. Defaults to "multiple".
- :return: 2-tuple containing the fparser1 AST for the algorithm code and \
+ :return: 2-tuple containing the fparser1 AST for the algorithm code and
the fparser1 AST or a string (for NEMO) of the psy code.
- :rtype: Tuple[:py:class:`fparser.one.block_statements.BeginSource`, \
- :py:class:`fparser.one.block_statements.Module`] | \
- Tuple[:py:class:`fparser.one.block_statements.BeginSource`, str]
+ :rtype: Tuple[:py:class:`fparser.one.block_statements.BeginSource`,
+ :py:class:`fparser.one.block_statements.Module`] |
+ Tuple[:py:class:`fparser.one.block_statements.BeginSource`, str]
:raises GenerationError: if an invalid API is specified.
:raises GenerationError: if an invalid kernel-renaming scheme is specified.
+ :raises GenerationError: if there is an error raising the PSyIR to
+ domain-specific PSyIR.
+ :raises GenerationError: if a kernel functor is not named in a use
+ statement.
:raises IOError: if the filename or search path do not exist.
+ :raises NoInvokesError: if no invokes are found in the algorithm file.
For example:
@@ -318,6 +324,27 @@ def generate(filename, api="", kernel_paths=None, script_name=None,
if isinstance(kern, LFRicBuiltinFunctor):
# Skip builtins
continue
+ if isinstance(kern.symbol.interface, UnresolvedInterface):
+ # This kernel functor is not specified in a use statement.
+ # Find all container symbols that are in scope.
+ st_ref = kern.scope.symbol_table
+ container_symbols = [
+ symbol.name for symbol in st_ref.containersymbols]
+ while st_ref.parent_symbol_table():
+ st_ref = st_ref.parent_symbol_table()
+ container_symbols += [
+ symbol.name for symbol in st_ref.containersymbols]
+ message = (
+ f"Kernel functor '{kern.symbol.name}' in routine "
+ f"'{kern.scope.name}' from algorithm file "
+ f"'{filename}' must be named in a use "
+ f"statement (found {container_symbols})")
+ if api == "dynamo0.3":
+ message += (
+ f" or be a recognised built-in (one of "
+ f"{list(BUILTIN_MAP.keys())})")
+ message += "."
+ raise GenerationError(message)
container_symbol = kern.symbol.interface.container_symbol
# Find the kernel file containing the container
|
stfc/PSyclone
|
fd61e6f51f974de6da10a1d2e72595b4c4bd0d29
|
diff --git a/src/psyclone/tests/generator_test.py b/src/psyclone/tests/generator_test.py
index d269c3db6..b21925a3b 100644
--- a/src/psyclone/tests/generator_test.py
+++ b/src/psyclone/tests/generator_test.py
@@ -45,8 +45,10 @@ functions.
import os
import re
+import shutil
import stat
from sys import modules
+
import pytest
from fparser.common.readfortran import FortranStringReader
@@ -1274,3 +1276,92 @@ def test_no_invokes_lfric_new(monkeypatch):
api="dynamo0.3")
assert ("Algorithm file contains no invoke() calls: refusing to generate "
"empty PSy code" in str(info.value))
+
+
+def test_generate_unknown_container_lfric(tmpdir, monkeypatch):
+ '''Test that a GenerationError exception in the generate function is
+ raised for the LFRic DSL if one of the functors is not explicitly
+ declared. This can happen in LFRic algorithm code as it is never
+ compiled. The exception is only raised with the new PSyIR approach
+ to modify the algorithm layer which is currently in development so
+ is protected by a switch. This switch is turned on in this test by
+ monkeypatching.
+
+ At the moment this exception is only raised if the functor is
+ declared in a different subroutine or function, as the original
+ parsing approach picks up all other cases. However, the original
+ parsing approach will eventually be removed.
+
+ '''
+ monkeypatch.setattr(generator, "LFRIC_TESTING", True)
+ code = (
+ "module some_kernel_mod\n"
+ "use module_mod, only : module_type\n"
+ "contains\n"
+ "subroutine dummy_kernel()\n"
+ " use testkern_mod, only: testkern_type\n"
+ "end subroutine dummy_kernel\n"
+ "subroutine some_kernel()\n"
+ " use constants_mod, only: r_def\n"
+ " use field_mod, only : field_type\n"
+ " type(field_type) :: field1, field2, field3, field4\n"
+ " real(kind=r_def) :: scalar\n"
+ " call invoke(testkern_type(scalar, field1, field2, field3, "
+ "field4))\n"
+ "end subroutine some_kernel\n"
+ "end module some_kernel_mod\n")
+ alg_filename = str(tmpdir.join("alg.f90"))
+ with open(alg_filename, "w", encoding='utf-8') as my_file:
+ my_file.write(code)
+ kern_filename = os.path.join(DYN03_BASE_PATH, "testkern_mod.F90")
+ shutil.copyfile(kern_filename, str(tmpdir.join("testkern_mod.F90")))
+ with pytest.raises(GenerationError) as info:
+ _, _ = generate(alg_filename)
+ assert ("Kernel functor 'testkern_type' in routine 'some_kernel' from "
+ "algorithm file '" in str(info.value))
+ assert ("alg.f90' must be named in a use statement (found ["
+ "'constants_mod', 'field_mod', '_psyclone_builtins', "
+ "'module_mod']) or be a recognised built-in (one of "
+ "['x_plus_y', 'inc_x_plus_y'," in str(info.value))
+
+
+def test_generate_unknown_container_gocean(tmpdir):
+ '''Test that a GenerationError exception in the generate function is
+ raised for the GOcean DSL if one of the functors is not explicitly
+ declared. This can happen in GOcean algorithm code as it is never
+ compiled.
+
+ At the moment this exception is only raised if the functor is
+ declared in a different subroutine or function, as the original
+ parsing approach picks up all other cases. However, the original
+ parsing approach will eventually be removed.
+
+ '''
+ code = (
+ "module some_kernel_mod\n"
+ "use module_mod, only : module_type\n"
+ "contains\n"
+ "subroutine dummy_kernel()\n"
+ " use compute_cu_mod, only: compute_cu\n"
+ "end subroutine dummy_kernel\n"
+ "subroutine some_kernel()\n"
+ " use kind_params_mod\n"
+ " use grid_mod, only: grid_type\n"
+ " use field_mod, only: r2d_field\n"
+ " type(grid_type), target :: model_grid\n"
+ " type(r2d_field) :: p_fld, u_fld, cu_fld\n"
+ " call invoke( compute_cu(cu_fld, p_fld, u_fld) )\n"
+ "end subroutine some_kernel\n"
+ "end module some_kernel_mod\n")
+ alg_filename = str(tmpdir.join("alg.f90"))
+ with open(alg_filename, "w", encoding='utf-8') as my_file:
+ my_file.write(code)
+ kern_filename = os.path.join(GOCEAN_BASE_PATH, "compute_cu_mod.f90")
+ shutil.copyfile(kern_filename, str(tmpdir.join("compute_cu_mod.f90")))
+ with pytest.raises(GenerationError) as info:
+ _, _ = generate(alg_filename, api="gocean1.0")
+ assert ("Kernel functor 'compute_cu' in routine 'some_kernel' from "
+ "algorithm file '" in str(info.value))
+ assert ("alg.f90' must be named in a use statement (found "
+ "['kind_params_mod', 'grid_mod', 'field_mod', 'module_mod'])."
+ in str(info.value))
|
LFRic alg layer error when using PSyIR: unknown kernel symbol
The version of `mixed_schur_preconditioner_alg_mod` on LFRic trunk is causing LFRic PSyIR alg-layer parsing to fail as `dg_inc_matrix_vector_kernel_type` is not imported in subroutine `back_substitute`. This is an error in the LFRic code which I've passed on but I need to tidy the error produced by PSyclone to make it clearer what the problem is.
|
0.0
|
fd61e6f51f974de6da10a1d2e72595b4c4bd0d29
|
[
"src/psyclone/tests/generator_test.py::test_generate_unknown_container_lfric",
"src/psyclone/tests/generator_test.py::test_generate_unknown_container_gocean"
] |
[
"src/psyclone/tests/generator_test.py::test_script_file_not_found",
"src/psyclone/tests/generator_test.py::test_script_file_no_extension",
"src/psyclone/tests/generator_test.py::test_script_file_wrong_extension",
"src/psyclone/tests/generator_test.py::test_script_invalid_content",
"src/psyclone/tests/generator_test.py::test_script_invalid_content_runtime",
"src/psyclone/tests/generator_test.py::test_script_no_trans",
"src/psyclone/tests/generator_test.py::test_script_no_trans_alg",
"src/psyclone/tests/generator_test.py::test_non_existent_filename",
"src/psyclone/tests/generator_test.py::test_invalid_api",
"src/psyclone/tests/generator_test.py::test_invalid_kernel_paths",
"src/psyclone/tests/generator_test.py::test_wrong_kernel_paths",
"src/psyclone/tests/generator_test.py::test_correct_kernel_paths",
"src/psyclone/tests/generator_test.py::test_same_kernel_paths",
"src/psyclone/tests/generator_test.py::test_similar_kernel_name",
"src/psyclone/tests/generator_test.py::test_recurse_correct_kernel_paths",
"src/psyclone/tests/generator_test.py::test_kernel_parsing_internalerror",
"src/psyclone/tests/generator_test.py::test_script_file_too_short",
"src/psyclone/tests/generator_test.py::test_no_script_gocean",
"src/psyclone/tests/generator_test.py::test_script_gocean",
"src/psyclone/tests/generator_test.py::test_profile_gocean",
"src/psyclone/tests/generator_test.py::test_script_attr_error",
"src/psyclone/tests/generator_test.py::test_script_null_trans",
"src/psyclone/tests/generator_test.py::test_script_null_trans_relative",
"src/psyclone/tests/generator_test.py::test_script_trans_dynamo0p3",
"src/psyclone/tests/generator_test.py::test_api_no_alg",
"src/psyclone/tests/generator_test.py::test_alg_lines_too_long_tested",
"src/psyclone/tests/generator_test.py::test_alg_lines_too_long_not_tested",
"src/psyclone/tests/generator_test.py::test_kern_lines_too_long_tested",
"src/psyclone/tests/generator_test.py::test_kern_lines_too_long_not_tested",
"src/psyclone/tests/generator_test.py::test_continuators",
"src/psyclone/tests/generator_test.py::test_main_version",
"src/psyclone/tests/generator_test.py::test_main_profile",
"src/psyclone/tests/generator_test.py::test_main_invalid_api",
"src/psyclone/tests/generator_test.py::test_main_api",
"src/psyclone/tests/generator_test.py::test_main_directory_arg",
"src/psyclone/tests/generator_test.py::test_main_expected_fatal_error",
"src/psyclone/tests/generator_test.py::test_generate_trans_error",
"src/psyclone/tests/generator_test.py::test_generate_no_builtin_container",
"src/psyclone/tests/generator_test.py::test_main_unexpected_fatal_error",
"src/psyclone/tests/generator_test.py::test_main_fort_line_length[all]",
"src/psyclone/tests/generator_test.py::test_main_fort_line_length[output]",
"src/psyclone/tests/generator_test.py::test_main_fort_line_length_off[limit0]",
"src/psyclone/tests/generator_test.py::test_main_fort_line_length_off[limit1]",
"src/psyclone/tests/generator_test.py::test_main_fort_line_length_output_only",
"src/psyclone/tests/generator_test.py::test_main_no_invoke_alg_stdout",
"src/psyclone/tests/generator_test.py::test_main_write_psy_file",
"src/psyclone/tests/generator_test.py::test_main_no_invoke_alg_file",
"src/psyclone/tests/generator_test.py::test_main_kern_output_no_dir",
"src/psyclone/tests/generator_test.py::test_main_kern_output_dir",
"src/psyclone/tests/generator_test.py::test_invalid_kern_naming",
"src/psyclone/tests/generator_test.py::test_main_include_invalid",
"src/psyclone/tests/generator_test.py::test_main_include_path",
"src/psyclone/tests/generator_test.py::test_utf_char",
"src/psyclone/tests/generator_test.py::test_check_psyir",
"src/psyclone/tests/generator_test.py::test_add_builtins_use",
"src/psyclone/tests/generator_test.py::test_no_script_lfric_new",
"src/psyclone/tests/generator_test.py::test_script_lfric_new",
"src/psyclone/tests/generator_test.py::test_builtins_lfric_new",
"src/psyclone/tests/generator_test.py::test_no_invokes_lfric_new"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-21 11:48:29+00:00
|
bsd-3-clause
| 5,722 |
|
stfc__PSyclone-904
|
diff --git a/changelog b/changelog
index a1faa0681..9d3e2351a 100644
--- a/changelog
+++ b/changelog
@@ -100,7 +100,7 @@
34) #823 for #471. Updates the access from INC to READWRITE for
those kernels that loop over DoFs.
-
+
35) #872 for #736 and #858. Routine Symbols are captured by the Fortran
front-end when parsing a Container.
@@ -126,6 +126,9 @@
provided about a symbol and replace the symbol latter on if more information
if found.
+ 42) #904 for #903. Fixed an error in handling use statements (a
+ symbol clash when there should not be one).
+
release 1.9.0 20th May 2020
1) #602 for #597. Modify Node.ancestor() to optionally include
diff --git a/src/psyclone/psyir/frontend/fparser2.py b/src/psyclone/psyir/frontend/fparser2.py
index e279263a9..9d16e1e54 100644
--- a/src/psyclone/psyir/frontend/fparser2.py
+++ b/src/psyclone/psyir/frontend/fparser2.py
@@ -1188,14 +1188,18 @@ class Fparser2Reader(object):
# will replace a previous import with an empty only-list.
pass
for name in decl.items[4].items:
- # The DataSymbol adds itself to the list of symbols
- # imported by the Container referenced in the
- # GlobalInterface.
sym_name = str(name).lower()
if sym_name not in parent.symbol_table:
+ # We're dealing with a symbol named in a use statement
+ # in the *current* scope therefore we do not check
+ # any ancestor symbol tables; we just create a
+ # new symbol. Since we don't yet know anything about
+ # this symbol apart from its name we create a generic
+ # Symbol.
parent.symbol_table.add(
Symbol(sym_name,
- interface=GlobalInterface(container)))
+ interface=GlobalInterface(container)),
+ check_ancestors=False)
else:
# There's already a symbol with this name
existing_symbol = parent.symbol_table.lookup(
|
stfc/PSyclone
|
055cca26fc5706f97c4e113cd96cbc693a8412a0
|
diff --git a/src/psyclone/tests/psyir/frontend/fparser2_test.py b/src/psyclone/tests/psyir/frontend/fparser2_test.py
index 8e654cf1b..0ed8b08e5 100644
--- a/src/psyclone/tests/psyir/frontend/fparser2_test.py
+++ b/src/psyclone/tests/psyir/frontend/fparser2_test.py
@@ -2678,3 +2678,42 @@ def test_loop_var_exception(parser):
"Loop-variable name 'i' is not declared and there are no unqualified "
"use statements. This is currently unsupported."
in str(excinfo.value))
+
+
+def test_named_and_wildcard_use_var(f2008_parser):
+ ''' Check that we handle the case where a variable is accessed first by
+ a wildcard import and then by a named import. '''
+ reader = FortranStringReader('''
+ module test_mod
+ use some_mod
+ contains
+ subroutine test_sub1()
+ ! a_var here must be being brought into scope by the
+ ! `use some_mod` in the module.
+ a_var = 1.0
+ end subroutine test_sub1
+ subroutine test_sub2()
+ use some_mod, only: a_var
+ a_var = 2.0
+ end subroutine test_sub2
+ end module test_mod
+ ''')
+ prog = f2008_parser(reader)
+ psy = PSyFactory(api="nemo").create(prog)
+ # We should have an entry for "a_var" in the Container symbol table
+ # due to the access in "test_sub1".
+ container = psy.invokes.container
+ avar1 = container.symbol_table.lookup("a_var")
+ # It must be a generic Symbol since we don't know anything about it
+ # pylint: disable=unidiomatic-typecheck
+ assert type(avar1) == Symbol
+ # There should be no entry for "a_var" in the symbol table for the
+ # "test_sub1" routine as it is not declared there.
+ schedule = psy.invokes.invoke_list[0].schedule
+ assert "a_var" not in schedule.symbol_table
+ # There should be another, distinct entry for "a_var" in the symbol table
+ # for "test_sub2" as it has a use statement that imports it.
+ schedule = psy.invokes.invoke_list[1].schedule
+ avar2 = schedule.symbol_table.lookup("a_var")
+ assert type(avar2) == Symbol
+ assert avar2 is not avar1
|
[psyir FE] wildcard import followed by specific import causes failure
The following Fortran code causes the fparser2 frontend to fail:
module test_mod
use some_mod
contains
subroutine test_sub1()
! a_var here must be being brought into scope by the
! `use some_mod` in the module.
a_var = 1.0
end subroutine test_sub1
subroutine test_sub2()
use some_mod, only: a_var
a_var = 2.0
end subroutine test_sub2
end module test_mod
with:
E KeyError: "Symbol table already contains a symbol with name 'a_var'."
This prevents the current master of PSyclone from processing (some of) the NEMO source.
|
0.0
|
055cca26fc5706f97c4e113cd96cbc693a8412a0
|
[
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_named_and_wildcard_use_var"
] |
[
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_check_args",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_is_bound_full_extent",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_is_array_range_literal",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_is_range_full_extent",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_precision[Intrinsic.REAL]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_precision[Intrinsic.INTEGER]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_precision[Intrinsic.BOOLEAN]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_precision[Intrinsic.CHARACTER]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_precision[None]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_integer_type",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_default_real_type",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_array_notation_rank",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_generate_schedule_empty_subroutine",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_generate_schedule_module_decls",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_generate_schedule_dummy_subroutine",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_generate_schedule_no_args_subroutine",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_generate_schedule_unmatching_arguments",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_accessibility",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_unsupported_declarations",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unsupported_decln_duplicate_symbol",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-1]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-2]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-4]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-8]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-16]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.INTEGER-integer-32]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-1]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-2]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-4]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-8]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-16]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.REAL-real-32]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-1]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-2]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-4]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-8]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-16]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_precision[Intrinsic.BOOLEAN-logical-32]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_double_precision",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_array_declarations",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_not_supported_declarations",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_module_function_symbol",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_save_attribute_declarations",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_intent",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_new_param",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_use",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_wrong_type_kind_param",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[real-1.0d0-Precision.DOUBLE]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[real-1.0D7-Precision.DOUBLE]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[real-1_t_def-None]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[real-1.0-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[real-1.0E3-Precision.SINGLE]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[integer-1-Precision.UNDEFINED]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_kind_literals[integer-34359738368_t_def-None]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unsupported_kind[logical-.false.]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unsupported_kind[real--1.0D7]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unsupported_kind[real-kvar]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unsupported_kind[real-kvar(1)]",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_stmt_functions",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_parse_array_dimensions_attributes",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_deferred_array_size",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unresolved_array_size",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_use_stmt",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_use_stmt_error",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_process_declarations_unrecognised_attribute",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_parse_array_dimensions_unhandled",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_assignment_stmt",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_name",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_parenthesis",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_part_ref",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_intrinsics",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_intrinsic_no_args",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_unary_op_handler_error",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_binary_op_handler_error",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_nary_op_handler_error",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_nested_intrinsic",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_array_section",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_array_product",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_if_stmt",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_if_construct",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_if_construct_errors",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_complex_if_construct",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_case_construct",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_case_default",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_case_list",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_case_range",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_case_range_list",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_invalid_case_construct",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_case_default_only",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_binaryopbase",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_unaryopbase",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_return_stmt",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_handling_end_subroutine_stmt",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_nodes_to_code_block_2",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_nodes_to_code_block_3",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_nodes_to_code_block_4",
"src/psyclone/tests/psyir/frontend/fparser2_test.py::test_loop_var_exception"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-22 10:53:27+00:00
|
bsd-3-clause
| 5,723 |
|
stfc__fparser-109
|
diff --git a/src/fparser/one/block_statements.py b/src/fparser/one/block_statements.py
index a4f1cc6..af7d1c3 100644
--- a/src/fparser/one/block_statements.py
+++ b/src/fparser/one/block_statements.py
@@ -1239,7 +1239,8 @@ class EndType(EndStatement):
blocktype = 'type'
-class Type(BeginStatement, HasVariables, HasAttributes, AccessSpecs):
+class Type(BeginStatement, HasVariables, HasAttributes, HasModuleProcedures,
+ AccessSpecs):
"""
TYPE [[, <typ-attr-spec-list>] ::] <type-name> [( <type-param-name-list> )]
<typ-attr-spec> = <access-spec> | EXTENDS ( <parent-type-name> )
|
stfc/fparser
|
1ad4fa664c6eeebaa3315e288b202eb51437e2aa
|
diff --git a/src/fparser/one/tests/test_parsefortran.py b/src/fparser/one/tests/test_parsefortran.py
index 6481c61..62bf562 100644
--- a/src/fparser/one/tests/test_parsefortran.py
+++ b/src/fparser/one/tests/test_parsefortran.py
@@ -186,10 +186,10 @@ end module foo
expected = [' MODULE foo',
' SUBROUTINE bar()',
' REAL r',
- ' IF (pc_get_lun() .ne. 6)'
- + ' WRITE (pc_get_lun(), \'( /, A, /, " P = ", i4,'
- + ' " stopping c_flag=", a, /, " print unit=", i8)\')'
- + ' trim(title), pcpsx_i_pel(), trim(c_flag), pc_get_lun()',
+ ' IF (pc_get_lun() .ne. 6)' +
+ ' WRITE (pc_get_lun(), \'( /, A, /, " P = ", i4,' +
+ ' " stopping c_flag=", a, /, " print unit=", i8)\')' +
+ ' trim(title), pcpsx_i_pel(), trim(c_flag), pc_get_lun()',
' IF (.true.) THEN',
' CALL smth',
' END IF ',
@@ -213,6 +213,30 @@ end module foo
assert caught[1:] == expected
+def test_module_procedure():
+ '''
+ Tests a type that contains a procedure, and makes sure
+ it has a module_procedures attribute
+ '''
+ string = """
+module foo
+ type, public :: grid_type
+ contains
+ procedure :: get_tmask
+ end type grid_type
+end module foo
+"""
+
+ reader = fparser.common.readfortran.FortranStringReader(string)
+ mode = fparser.common.sourceinfo.FortranFormat.from_mode('free')
+ reader.set_format(mode)
+ parser = fparser.one.parsefortran.FortranParser(reader)
+ parser.parse()
+
+ # Fails if the class Type does not have a "module_procedures" attribute
+ parser.analyze()
+
+
def test_f77():
'''
Tests inherited from implementation code.
|
Module Procedures in a Fortran type
The following code is not parsed and then analyzed correctly with fparser 1:
```
module foo
type, public :: grid_type
contains
procedure :: get_tmask
end type grid_type
end module foo
```
Reason: The class Type does not contain an attribute "module_procedures".
|
0.0
|
1ad4fa664c6eeebaa3315e288b202eb51437e2aa
|
[
"src/fparser/one/tests/test_parsefortran.py::test_module_procedure"
] |
[
"src/fparser/one/tests/test_parsefortran.py::test_pyf",
"src/fparser/one/tests/test_parsefortran.py::test_free90",
"src/fparser/one/tests/test_parsefortran.py::test_f77"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-09-19 06:29:32+00:00
|
bsd-3-clause
| 5,724 |
|
stfc__fparser-234
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d7d8a3..554ebeb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,9 @@ Modifications by (in alphabetical order):
* J. Tiira, University of Helsinki, Finland
* P. Vitt, University of Siegen, Germany
+08/01/2020 PR #234 for #228. Remove the blank space at the end of unnamed
+ "END DO" statements.
+
07/01/2020 PR #233 for #161. Improve the reader handling of multi-statement
source lines. Especially those containing labels or construct
names.
diff --git a/src/fparser/common/base_classes.py b/src/fparser/common/base_classes.py
index c27aca6..1b19163 100644
--- a/src/fparser/common/base_classes.py
+++ b/src/fparser/common/base_classes.py
@@ -1002,5 +1002,21 @@ class EndStatement(Statement):
return Statement.get_indent_tab(self, deindent=True, isfix=isfix)
def tofortran(self, isfix=None):
- return self.get_indent_tab(isfix=isfix) + 'END %s %s'\
- % (self.blocktype.upper(), self.name or '')
+ '''Returns a valid Fortran string for this END statement. It
+ guarantees that there is no white space after the 'END' in case
+ of an unnamed statement.
+
+ :param bool isfix: True if the code is in fixed format.
+
+ :returns: the (named or unnamed) valid Fortran END statement \
+ as a string.
+ :rtype: str
+
+ '''
+ if self.name:
+ return self.get_indent_tab(isfix=isfix) + 'END {0} {1}'\
+ .format(self.blocktype.upper(), self.name)
+
+ # Make sure there is no space after an unnamed END:
+ return self.get_indent_tab(isfix=isfix) + 'END {0}'\
+ .format(self.blocktype.upper())
|
stfc/fparser
|
57d0ca7b4955a9f60e9efe48702c4e8c2a846a56
|
diff --git a/src/fparser/common/tests/test_base_classes.py b/src/fparser/common/tests/test_base_classes.py
index b286f41..960632b 100644
--- a/src/fparser/common/tests/test_base_classes.py
+++ b/src/fparser/common/tests/test_base_classes.py
@@ -46,6 +46,7 @@ import fparser.common.base_classes
import fparser.common.readfortran
import fparser.common.sourceinfo
import fparser.common.utils
+from fparser import api
def test_statement_logging(log, monkeypatch):
@@ -165,3 +166,33 @@ def test_log_unexpected(log):
"in 'BeginThing' block."
result = log.messages['warning'][0].split('\n')[1]
assert result == expected
+
+
+def test_space_after_enddo():
+ '''Make sure that there is no space after an 'END DO' without name,
+ but there is a space if there is a name after 'END DO'.
+ '''
+
+ # Unnamed loop:
+ source_str = '''\
+ subroutine foo
+ integer i, r
+ do i = 1,100
+ r = r + 1
+ end do
+ end subroutine foo
+ '''
+ tree = api.parse(source_str, isfree=True, isstrict=False)
+ assert "END DO " not in tree.tofortran()
+
+ # Named loop:
+ source_str = '''\
+ subroutine foo
+ integer i, r
+ loop1: do i = 1,100
+ r = r + 1
+ end do loop1
+ end subroutine foo
+ '''
+ tree = api.parse(source_str, isfree=True, isstrict=False)
+ assert "END DO loop1" in tree.tofortran()
diff --git a/src/fparser/one/tests/test_do_block_r814.py b/src/fparser/one/tests/test_do_block_r814.py
index 9b791ad..9406375 100644
--- a/src/fparser/one/tests/test_do_block_r814.py
+++ b/src/fparser/one/tests/test_do_block_r814.py
@@ -49,6 +49,26 @@ from fparser.one.parsefortran import FortranParser
from fparser.common.readfortran import FortranStringReader
+def get_end_do(name):
+ '''A small helper function to return either "END DO" (without space) if
+ name is empty, or "END DO "+name. This simplifies the tests now that
+ tofortran does not return an "END DO" with one space in case of an
+ unnamed end statement.
+
+ :param str name: Either None if it is an unnamed statement, or \
+ the label to use in the end statement.
+
+ :returns: either "END DO" (without space) if name is empty, or \
+ "END DO "+name.
+ :rtype: str
+
+ '''
+
+ if name:
+ return "END DO {0}".format(name)
+ return "END DO"
+
+
@pytest.mark.parametrize('name', [None, 'loop_name'])
@pytest.mark.parametrize('label', [None, '123'])
@pytest.mark.parametrize('control_comma', [False, True])
@@ -73,7 +93,7 @@ def test_do(name, label, control_comma, terminal_expression,
# TODO: Although the Fortran standard allows for "continue" to be used in
# place of "end do" fparser does not support it.
end_snippet = 'continue' if end_name == 'continue' \
- else 'end do {endname}'.format(endname=end_name or '')
+ else get_end_do(end_name)
do_code = '''{name}do {label}{comma}variable = 1, {term}, 1
write (6, '(I0)') variable
{endlabel} {end}
@@ -85,12 +105,12 @@ def test_do(name, label, control_comma, terminal_expression,
end=end_snippet)
do_expected = ''' {name}DO {label}variable = 1, {term}, 1
WRITE (6, '(I0)') variable
-{endlabel} END DO {endname}
+{endlabel} {endstmt}
'''.format(name=name_snippet or '',
label=label_snippet or '',
term=terminal_expression,
endlabel=end_label or ' ',
- endname=end_name or '')
+ endstmt=get_end_do(end_name))
do_reader = FortranStringReader(do_code)
do_reader.set_format(FortranFormat(True, False))
do_parser = FortranParser(do_reader)
@@ -122,21 +142,21 @@ def test_do_while(name, label, control_comma, terminal_expression,
comma_snippet = ', ' if control_comma else None
code = '''{name}do {label}{comma}while ({term})
write (6, '(I0)') variable
-{endlabel} end do {endname}
+{endlabel} {endstmt}
'''.format(name=name_snippet or '',
label=label_snippet or '',
comma=comma_snippet or '',
term=terminal_expression,
endlabel=end_label or '',
- endname=end_name or '')
+ endstmt=get_end_do(end_name))
expected = ''' {name}DO {label}while ({term})
WRITE (6, '(I0)') variable
-{endlabel} END DO {endname}
+{endlabel} {endstmt}
'''.format(name=name_snippet or '',
label=label_snippet or '',
term=terminal_expression,
endlabel=end_label or ' ',
- endname=end_name or '')
+ endstmt=get_end_do(end_name))
print(code)
reader = FortranStringReader(code)
reader.set_format(FortranFormat(True, False))
diff --git a/src/fparser/one/tests/test_parsefortran.py b/src/fparser/one/tests/test_parsefortran.py
index e8abeb9..6c9948e 100644
--- a/src/fparser/one/tests/test_parsefortran.py
+++ b/src/fparser/one/tests/test_parsefortran.py
@@ -193,7 +193,7 @@ end module foo
' trim(title), pcpsx_i_pel(), trim(c_flag), pc_get_lun()',
' IF (.true.) THEN',
' CALL smth',
- ' END IF ',
+ ' END IF',
' aaa: IF (.false.) THEN',
' ELSE IF (a) THEN',
' ELSE',
@@ -201,7 +201,7 @@ end module foo
' hey = 1',
' END SUBROUTINE bar',
' ABSTRACT INTERFACE',
- ' END INTERFACE ',
+ ' END INTERFACE',
' END MODULE foo']
reader = fparser.common.readfortran.FortranStringReader(string)
|
Space after 'end do'
Atm psyclone creates 'end do' statements as 'END DO ' - notice the space at the end. While mostly this does not matter, it triggers pylint warnings if a ''' multi-line string is used to compare the output with, e.g. in gocean1p0_config_test:
```
new_loop1 = ''' DO j=1,2
DO i=3,4
CALL compute_kern1_code(i, j, cu_fld%data, p_fld%data, u_fld%data)
END DO
END DO ''' # nopep8
```
Since multi-line strings are very convenient for storing Fortran strings, I would prefer if the space at the end of 'end do' could be removed, so that we don't need to add pylint/pycodestyle directives.
The patch appears to be simple:
```
diff --git a/src/fparser/common/base_classes.py b/src/fparser/common/base_classes.py
index c27aca6..0d8a86c 100644
--- a/src/fparser/common/base_classes.py
+++ b/src/fparser/common/base_classes.py
@@ -1002,5 +1002,8 @@ class EndStatement(Statement):
return Statement.get_indent_tab(self, deindent=True, isfix=isfix)
def tofortran(self, isfix=None):
+ if self.name:
+ return self.get_indent_tab(isfix=isfix) + 'END %s %s'\
+ % (self.blocktype.upper(), self.name or '')
return self.get_indent_tab(isfix=isfix) + 'END %s %s'\
% (self.blocktype.upper(), self.name or '')
```
But I am not sure if this might affect anything else. Let me know if you are interested in a pull request for this.
Note that I could not find a convenient way to fix this in psyclone itself (short of converting the EndDo instance to a new class that would return 'end do' without a string, which seems to be silly todo 😜 ).
|
0.0
|
57d0ca7b4955a9f60e9efe48702c4e8c2a846a56
|
[
"src/fparser/common/tests/test_base_classes.py::test_space_after_enddo",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_parsefortran.py::test_free90"
] |
[
"src/fparser/common/tests/test_base_classes.py::test_statement_logging",
"src/fparser/common/tests/test_base_classes.py::test_log_comment_mix",
"src/fparser/common/tests/test_base_classes.py::test_log_unexpected",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[None-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[123-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-10-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do[456-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[None-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[123-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-None-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-loop_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-1-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-x+y-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(array)-True-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-False-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-False-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-False-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-False-123-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-True-None-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-True-None-loop_name]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-True-123-None]",
"src/fparser/one/tests/test_do_block_r814.py::test_do_while[456-wrong_name-size(this%array)-True-123-loop_name]",
"src/fparser/one/tests/test_parsefortran.py::test_log_empty",
"src/fparser/one/tests/test_parsefortran.py::test_log_cache",
"src/fparser/one/tests/test_parsefortran.py::test_log_failure",
"src/fparser/one/tests/test_parsefortran.py::test_pyf",
"src/fparser/one/tests/test_parsefortran.py::test_module_procedure",
"src/fparser/one/tests/test_parsefortran.py::test_f77"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-08 05:10:32+00:00
|
bsd-3-clause
| 5,725 |
|
stfc__fparser-263
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5e77548..6b4b42c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,9 @@ Modifications by (in alphabetical order):
* J. Tiira, University of Helsinki, Finland
* P. Vitt, University of Siegen, Germany
+03/06/2020 PR #263 for #262. Fixes bug in fparser2 logging a 'critical'
+ error when it reaches the end of a file.
+
03/06/2020 PR #249. Adds support for Fortran2008 CONTIGUOUS and
CODIMENSION keywords.
diff --git a/src/fparser/common/readfortran.py b/src/fparser/common/readfortran.py
index 2409318..60e4ea2 100644
--- a/src/fparser/common/readfortran.py
+++ b/src/fparser/common/readfortran.py
@@ -870,12 +870,18 @@ class FortranReaderBase(object):
Resolves ``;`` statement terminations.
- :param bool ignore_comments: Whether or not to ignore comments
- (overrides self._ignore_comments)
-
See also
--------
next, get_source_item
+
+ :param bool ignore_comments: Whether or not to ignore comments \
+ (overrides self._ignore_comments)
+
+ :returns: the next line of Fortran.
+ :rtype: :py:class:`fparser.common.readfortran.Line`
+
+ :raises StopIteration: if no new items are found.
+
"""
if ignore_comments is None:
ignore_comments = self._ignore_comments
@@ -887,9 +893,9 @@ class FortranReaderBase(object):
except IndexError:
# construct a new item from source
item = self.get_source_item()
- if item is None:
- raise StopIteration
- if not (item.isempty(ignore_comments)):
+ if item is None:
+ raise StopIteration
+ if not item.isempty(ignore_comments):
break
# else ignore empty lines and comments by getting next line
diff --git a/src/fparser/two/C99Preprocessor.py b/src/fparser/two/C99Preprocessor.py
index 8557a9b..4a4fc94 100644
--- a/src/fparser/two/C99Preprocessor.py
+++ b/src/fparser/two/C99Preprocessor.py
@@ -76,7 +76,8 @@ def match_cpp_directive(reader):
if isinstance(reader, FortranReaderBase):
item = reader.get_item()
is_potential_cpp_directive = isinstance(item, CppDirective)
- reader.put_item(item)
+ if item:
+ reader.put_item(item)
# Do not bail out early here to have a catch all return statement
# at the end (that would not be reachable by tests otherwise)
if is_potential_cpp_directive:
|
stfc/fparser
|
e98eb1f167efa4efa66f367c0ad6bdd74383bc30
|
diff --git a/src/fparser/common/tests/test_readfortran.py b/src/fparser/common/tests/test_readfortran.py
index 8af7530..8b75af1 100644
--- a/src/fparser/common/tests/test_readfortran.py
+++ b/src/fparser/common/tests/test_readfortran.py
@@ -745,7 +745,32 @@ def test_file_reader():
raise
-##############################################################################
+def test_none_in_fifo(log):
+ ''' Check that a None entry in the reader FIFO buffer is handled
+ correctly. '''
+ log.reset()
+ handle, filename = tempfile.mkstemp(suffix='.f90', text=True)
+ os.close(handle)
+
+ with io.open(filename, mode='w', encoding='UTF-8') as source_file:
+ source_file.write(FULL_FREE_SOURCE)
+
+ with io.open(filename, mode='r', encoding='UTF-8') as source_file:
+ unit_under_test = FortranFileReader(source_file)
+ while True:
+ try:
+ _ = unit_under_test.next(ignore_comments=False)
+ except StopIteration:
+ break
+ # Erroneously push a None to the FIFO buffer
+ unit_under_test.put_item(None)
+ # Attempt to read the next item
+ with pytest.raises(StopIteration):
+ _ = unit_under_test.next(ignore_comments=False)
+ # Check that nothing has been logged
+ for log_level in ["debug", "info", "warning", "error", "critical"]:
+ assert log.messages[log_level] == []
+
def test_bad_file_reader():
'''
diff --git a/src/fparser/two/tests/test_scripts.py b/src/fparser/two/tests/test_scripts.py
index 7225b7f..3770e87 100644
--- a/src/fparser/two/tests/test_scripts.py
+++ b/src/fparser/two/tests/test_scripts.py
@@ -275,10 +275,11 @@ def test_runner_multi_output_except(tmpdir, capsys):
# fparser2.py script function main()
-def test_main_output_task_default(tmpdir, capsys, monkeypatch):
+def test_main_output_task_default(tmpdir, capsys, monkeypatch, log):
'''Test that the script main() function outputs the code it has parsed
- by default.'''
+ by default and that no errors are logged.'''
import sys
+ log.reset()
# Create a temporary file containing Fortran code to pass into runner()
my_file = tmpdir.mkdir("sub").join("hello.f90")
my_file.write("program hello\nend program hello\n")
@@ -290,6 +291,9 @@ def test_main_output_task_default(tmpdir, capsys, monkeypatch):
stdout, stderr = capsys.readouterr()
assert stdout == "PROGRAM hello\nEND PROGRAM hello\n"
assert "File: '" in stderr and "hello.f90'" in stderr
+ # Check that nothing has been logged (apart from some 'debug' msgs)
+ for log_level in ["info", "warning", "error", "critical"]:
+ assert log.messages[log_level] == []
def test_main_output_task_show(tmpdir, capsys, monkeypatch):
|
fparser2 logs a 'critical' error when it reaches the end of a file
(fparser) [@DLHRT0030 code_fragments]$ cat hello.f90
program hello
write(*,*) "Hello."
end program hello
(fparser) [code_fragments]$ fparser2 hello.f90
File: 'hello.f90'
CRITICAL:fparser.common.readfortran:While processing 'hello.f90' (mode='free')..
1:program hello
2: write(*,*) "Hello."
3:end program hello <== while processing line
CRITICAL:fparser.common.readfortran:STOPPED READING
PROGRAM hello
WRITE(*, FMT = *) "Hello."
END PROGRAM hello
|
0.0
|
e98eb1f167efa4efa66f367c0ad6bdd74383bc30
|
[
"src/fparser/common/tests/test_readfortran.py::test_none_in_fifo",
"src/fparser/two/tests/test_scripts.py::test_main_output_task_default"
] |
[
"src/fparser/common/tests/test_readfortran.py::test_empty_line_err",
"src/fparser/common/tests/test_readfortran.py::test_111fortranreaderbase",
"src/fparser/common/tests/test_readfortran.py::test_include_not_found",
"src/fparser/common/tests/test_readfortran.py::test_base_next_good_include",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_info",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_error",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_warning",
"src/fparser/common/tests/test_readfortran.py::test_base_handle_multilines",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_nonlabel",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_continuation",
"src/fparser/common/tests/test_readfortran.py::test_base_free_continuation",
"src/fparser/common/tests/test_readfortran.py::test_include1",
"src/fparser/common/tests/test_readfortran.py::test_include2",
"src/fparser/common/tests/test_readfortran.py::test_include3",
"src/fparser/common/tests/test_readfortran.py::test_include4",
"src/fparser/common/tests/test_readfortran.py::test_include5",
"src/fparser/common/tests/test_readfortran.py::test_include6[True]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[True]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_include6[False]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line1",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line2",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line3",
"src/fparser/common/tests/test_readfortran.py::test_filename_reader",
"src/fparser/common/tests/test_readfortran.py::test_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_bad_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_string_reader",
"src/fparser/common/tests/test_readfortran.py::test_inherited_f77",
"src/fparser/common/tests/test_readfortran.py::test_pyf",
"src/fparser/common/tests/test_readfortran.py::test_fix90",
"src/fparser/common/tests/test_readfortran.py::test_utf_char_in_code",
"src/fparser/common/tests/test_readfortran.py::test_extract_label",
"src/fparser/common/tests/test_readfortran.py::test_extract_construct_name",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#include",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#define",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#ifdef",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#if",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[abc",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[\"#\"-False]",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[!",
"src/fparser/common/tests/test_readfortran.py::test_reader_cpp_directives",
"src/fparser/common/tests/test_readfortran.py::test_multiline_cpp_directives",
"src/fparser/two/tests/test_scripts.py::test_runner_no_files",
"src/fparser/two/tests/test_scripts.py::test_runner_non_existant_file",
"src/fparser/two/tests/test_scripts.py::test_runner_no_file_multi",
"src/fparser/two/tests/test_scripts.py::test_runner_set_mode",
"src/fparser/two/tests/test_scripts.py::test_runner_syntax_error",
"src/fparser/two/tests/test_scripts.py::test_runner_internal_error",
"src/fparser/two/tests/test_scripts.py::test_runner_output_task_show",
"src/fparser/two/tests/test_scripts.py::test_runner_output_task_repr",
"src/fparser/two/tests/test_scripts.py::test_runner_output_task_none",
"src/fparser/two/tests/test_scripts.py::test_runner_multi_output",
"src/fparser/two/tests/test_scripts.py::test_runner_multi_output_except",
"src/fparser/two/tests/test_scripts.py::test_main_output_task_show",
"src/fparser/two/tests/test_scripts.py::test_main_output_task_repr",
"src/fparser/two/tests/test_scripts.py::test_main_output_task_none",
"src/fparser/two/tests/test_scripts.py::test_main_output_task_invalid",
"src/fparser/two/tests/test_scripts.py::test_main_output_std_f2003",
"src/fparser/two/tests/test_scripts.py::test_main_output_std_f2008",
"src/fparser/two/tests/test_scripts.py::test_main_output_std_invalid",
"src/fparser/two/tests/test_scripts.py::test_read_runner_nofiles",
"src/fparser/two/tests/test_scripts.py::test_read_runner_file",
"src/fparser/two/tests/test_scripts.py::test_read_runner_files",
"src/fparser/two/tests/test_scripts.py::test_read_runner_no_show",
"src/fparser/two/tests/test_scripts.py::test_read_main"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-01 09:15:14+00:00
|
bsd-3-clause
| 5,726 |
|
stfc__fparser-269
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58aa14c..bd2e1f3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,10 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
+11/03/2021 PR #269 for #268. Removed recognition of f2py directives in
+ the reader. The original code is still there if needed in
+ the future.
+
20/01/2021 PR #289 for #288. Bug fix for matching expressions containing
real literals with signed exponents. This bug was introduced
by #285.
diff --git a/doc/developers_guide.rst b/doc/developers_guide.rst
index b34125b..7b35e13 100644
--- a/doc/developers_guide.rst
+++ b/doc/developers_guide.rst
@@ -49,6 +49,15 @@ provided as a string. Both of these classes sub-class `FortranReaderBase`:
Note that the setting for `ignore_comments` provided here can be overridden
on a per-call basis by methods such as `get_single_line`.
+The 'mode' of the reader is controlled by passing in a suitable instance of
+the `FortranFormat` class:
+
+.. autoclass:: fparser.common.sourceinfo.FortranFormat
+
+Due to its origins in the f2py project, the reader contains support
+for recognising `f2py` directives
+(https://numpy.org/devdocs/f2py/signature-file.html). However, this
+functionality is disabled by default.
A convenience script called read.py is provided in the scripts
directory which takes a filename as input and returns the file
diff --git a/src/fparser/common/readfortran.py b/src/fparser/common/readfortran.py
index 7960f99..1f88998 100644
--- a/src/fparser/common/readfortran.py
+++ b/src/fparser/common/readfortran.py
@@ -173,19 +173,26 @@ def _is_fix_cont(line):
return line and len(line) > 5 and line[5] != ' ' and line[:5] == 5 * ' '
-def _is_fix_comment(line, isstrict):
- """
+def _is_fix_comment(line, isstrict, f2py_enabled):
+ '''
Check whether line is a comment line in fixed format Fortran source.
- :param str line: Line of code to check
- :param bool isstrict: Whether we are strictly enforcing fixed/free fmt
-
References
----------
:f2008:`3.3.3`
- """
+
+ :param str line: line of code to check.
+ :param bool isstrict: whether we are strictly enforcing fixed/free fmt.
+ :param bool f2py_enabled: whether support for f2py directives is enabled.
+
+ :returns: whether or not the supplied line is a fixed-format comment.
+ :rtype: bool
+
+ '''
if line:
if line[0] in '*cC!':
+ if f2py_enabled and line[1:5].lower() == "f2py":
+ return False
return True
if not isstrict:
i = line.find('!')
@@ -544,14 +551,14 @@ class FortranReaderBase(object):
code, free format Fortran code, or PYF signatures (with extended
free format Fortran syntax).
- :param source: A file-like object with .next() method used to
+ :param source: a file-like object with .next() method used to \
retrive a line.
- :type source: either :py:class:`six.StringIO` or a file handle
- :param mode: A FortranFormat object as returned by
+ :type source: :py:class:`six.StringIO` or a file handle
+ :param mode: a FortranFormat object as returned by \
`sourceinfo.get_source_info()`
:type mode: :py:class:`fparser.common.sourceinfo.Format`
- :param bool isstrict: Whether we are strictly enforcing fixed format
- :param bool ignore_comments: Whether or not to discard comments
+ :param bool isstrict: whether we are strictly enforcing fixed format.
+ :param bool ignore_comments: whether or not to discard comments.
The Fortran source is iterated by `get_single_line`,
`get_next_line`, `put_single_line` methods.
@@ -670,8 +677,8 @@ class FortranReaderBase(object):
In both situations ``linecount`` will be incremented, that is,
the line will be consumed.
- :param bool ignore_empty: If True then ignore empty lines.
- :param bool ignore_comments: If True then ignore comments (overrides
+ :param bool ignore_empty: if True then ignore empty lines.
+ :param bool ignore_comments: if True then ignore comments (overrides \
self._ignore_comments)
See also
@@ -718,11 +725,12 @@ class FortranReaderBase(object):
self.source_lines.append(line)
- if ignore_comments and (self.format.is_fixed or self.format.is_f77):
+ if ignore_comments and (self._format.is_fixed or self._format.is_f77):
# Check for a fixed-format comment. If the current line *is*
# a comment and we are ignoring them, then recursively call this
# routine again to get the next source line.
- if _is_fix_comment(line, isstrict=self.format.is_strict):
+ if _is_fix_comment(line, isstrict=self._format.is_strict,
+ f2py_enabled=self._format.f2py_enabled):
return self.get_single_line(ignore_empty, ignore_comments)
if ignore_empty and not line:
@@ -1110,22 +1118,24 @@ class FortranReaderBase(object):
return (line, line.lstrip().startswith('#'))
def handle_cf2py_start(self, line):
- """ Apply f2py directives to line.
+ '''
+ Process any f2py directives contained in the supplied line. If
+ support for such directives has been disabled then the line is
+ returned unchanged.
F2py directives are specified in the beginning of the line.
f2py directives can be used only in Fortran codes. They are
ignored when used inside PYF files.
- Parameters
- ----------
- line : str
+ :param str line: the line to check for f2py directives.
- Returns
- -------
- line : str
- """
- if not line or self._format.is_pyf:
+ :returns: the line with any f2py directives applied (if they are \
+ enabled in the reader).
+ :rtype: str
+
+ '''
+ if not line or self._format.is_pyf or not self._format.f2py_enabled:
return line
if self._format.is_fixed:
if line[0] in '*cC!#':
@@ -1190,7 +1200,7 @@ class FortranReaderBase(object):
commentline = ''.join(items[k:])
break
if commentline is not None:
- if commentline.startswith('!f2py'):
+ if self._format.f2py_enabled and commentline.startswith('!f2py'):
# go to next iteration:
newline = ''.join(noncomment_items) + commentline[5:]
self.f2py_comment_lines.append(lineno)
@@ -1278,7 +1288,8 @@ class FortranReaderBase(object):
# the following contexts: f77, fixed, free, pyf.
def get_source_item(self):
- """ Return next source item.
+ '''
+ Return the next source item.
A source item is ..
- a fortran line
@@ -1286,11 +1297,20 @@ class FortranReaderBase(object):
- a multiline - lines inside triple-quotes, only when in ispyf mode
- a comment line
- a preprocessor directive line
- """
+
+ :returns: the next source item.
+ :rtype: :py:class:`fparser.common.readfortran.Line` or \
+ :py:class:`fparser.common.readfortran.MultiLine` or \
+ :py:class:`fparser.common.readfortran.Comment` or \
+ :py:class:`fparser.common.readfortran.CppDirective` or \
+ :py:class:`fparser.common.readfortran.SyntaxErrorLine` or \
+ :py:class:`fparser.common.readfortran.SyntaxErrorMultiLine`
+
+ '''
get_single_line = self.get_single_line
line = get_single_line()
if line is None:
- return
+ return None
startlineno = self.linecount
line, is_cpp_directive = self.handle_cpp_directive(line)
if is_cpp_directive:
@@ -1306,7 +1326,8 @@ class FortranReaderBase(object):
endlineno)
line = self.handle_cf2py_start(line)
- is_f2py_directive = startlineno in self.f2py_comment_lines
+ is_f2py_directive = (self._format.f2py_enabled and
+ startlineno in self.f2py_comment_lines)
isstrict = self._format.is_strict
have_comment = False
label = None
@@ -1315,11 +1336,11 @@ class FortranReaderBase(object):
if self._format.is_pyf:
# handle multilines
for mlstr in ['"""', "'''"]:
- r = self.handle_multilines(line, startlineno, mlstr)
- if r:
- return r
+ multiline = self.handle_multilines(line, startlineno, mlstr)
+ if multiline:
+ return multiline
if self._format.is_fixed:
- if _is_fix_comment(line, isstrict):
+ if _is_fix_comment(line, isstrict, self._format.f2py_enabled):
# comment line:
return self.comment_item(line, startlineno, startlineno)
@@ -1415,14 +1436,15 @@ class FortranReaderBase(object):
lines = [newline]
next_line = self.get_next_line()
- while _is_fix_cont(next_line) or _is_fix_comment(next_line,
- isstrict):
+ while (_is_fix_cont(next_line) or
+ _is_fix_comment(next_line, isstrict,
+ self._format.f2py_enabled)):
# handle fix format line continuations for F90 or
# newer code. Mixing fix format and free format line
# continuations is not allowed nor detected, just
# eject warnings.
line2 = get_single_line() # consume next_line as line2
- if _is_fix_comment(line2, isstrict):
+ if _is_fix_comment(line2, isstrict, self._format.f2py_enabled):
# handle fix format comments inside line continuations
# after the line construction
citem = self.comment_item(line2,
diff --git a/src/fparser/common/sourceinfo.py b/src/fparser/common/sourceinfo.py
index 807ff4c..155b131 100644
--- a/src/fparser/common/sourceinfo.py
+++ b/src/fparser/common/sourceinfo.py
@@ -1,4 +1,4 @@
-# Modified work Copyright (c) 2017-2019 Science and Technology
+# Modified work Copyright (c) 2017-2021 Science and Technology
# Facilities Council
# Original work Copyright (c) 1999-2008 Pearu Peterson
@@ -85,15 +85,13 @@ class FortranFormat(object):
"not strict" although it's not entirely clear what that means. It may
refer to the strictness of adherance to fixed format although what that
means in the context of free format I don't know.
- '''
- def __init__(self, is_free, is_strict):
- '''
- Constructs a FortranFormat object from the describing parameters.
- Arguments:
- is_free - (Boolean) True for free format, False for fixed.
- is_strict - (Boolean) Some amount of strictness.
- '''
+ :param bool is_free: True for free format, False for fixed.
+ :param bool is_strict: some amount of strictness.
+ :param bool enable_f2py: whether f2py directives are enabled or treated \
+ as comments (the default).
+ '''
+ def __init__(self, is_free, is_strict, enable_f2py=False):
if is_free is None:
raise Exception('FortranFormat does not accept a None is_free')
if is_strict is None:
@@ -101,6 +99,7 @@ class FortranFormat(object):
self._is_free = is_free
self._is_strict = is_strict
+ self._f2py_enabled = enable_f2py
@classmethod
def from_mode(cls, mode):
@@ -125,7 +124,8 @@ class FortranFormat(object):
def __eq__(self, other):
if isinstance(other, FortranFormat):
return self.is_free == other.is_free \
- and self.is_strict == other.is_strict
+ and self.is_strict == other.is_strict \
+ and self.f2py_enabled == other.f2py_enabled
raise NotImplementedError
def __str__(self):
@@ -183,6 +183,14 @@ class FortranFormat(object):
'''
return self._is_free and self._is_strict
+ @property
+ def f2py_enabled(self):
+ '''
+ :returns: whether or not f2py directives are enabled.
+ :rtype: bool
+ '''
+ return self._f2py_enabled
+
@property
def mode(self):
'''
|
stfc/fparser
|
463d4f7f27d952fba8b2400a6a54378d470853aa
|
diff --git a/src/fparser/common/tests/test_readfortran.py b/src/fparser/common/tests/test_readfortran.py
index 58175e2..ba04c08 100644
--- a/src/fparser/common/tests/test_readfortran.py
+++ b/src/fparser/common/tests/test_readfortran.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
##############################################################################
-# Copyright (c) 2017-2020 Science and Technology Facilities Council
+# Copyright (c) 2017-2021 Science and Technology Facilities Council
#
# All rights reserved.
#
@@ -55,6 +55,15 @@ from fparser.common.readfortran import FortranFileReader, \
from fparser.common.sourceinfo import FortranFormat
[email protected](scope="module",
+ name="f2py_enabled",
+ params=[True, False])
+def f2py_enabled_fixture(request):
+ ''' Fixture that returns whether or not to enable reader support for
+ f2py directives. '''
+ return request.param
+
+
def test_empty_line_err():
''' Check that we raise the expected error if we try and create
an empty Line '''
@@ -809,7 +818,6 @@ c12346 comment
'bar
a 'g
abc=2
-cf2py call me ! hey
call you ! hi
end
'"""
@@ -819,8 +827,8 @@ cf2py call me ! hey
"line #4'call foobar'",
'Comment("a \'g",(6, 6))',
"line #7'abc=2'",
- "line #9'call you ! hi'",
- "line #10'end'"]
+ "line #8'call you ! hi'",
+ "line #9'end'"]
# Reading from buffer
reader = FortranStringReader(
@@ -927,7 +935,6 @@ cComment
!
!4!line cont. with comment symbol
&5
- a = 3!f2py.14 ! pi!
! KDMO
write (obj%print_lun, *) ' KDMO : '
write (obj%print_lun, *) ' COORD = ',coord, ' BIN_WID = ', &
@@ -946,17 +953,15 @@ cComment
"line #5'b = 345'",
"Comment('!',(6, 6))",
"Comment('!line cont. with comment symbol',(7, 7))",
- "line #9'a = 3.14'",
- "Comment('! pi!',(9, 9))",
- "Comment('! KDMO',(10, 10))",
- 'line #11"write (obj%print_lun, *) \' KDMO : \'"',
- 'line #12"write (obj%print_lun, *) \' COORD = \',coord,'
+ "Comment('! KDMO',(9, 9))",
+ 'line #10"write (obj%print_lun, *) \' KDMO : \'"',
+ 'line #11"write (obj%print_lun, *) \' COORD = \',coord,'
+ ' \' BIN_WID = \', &"',
- 'line #13"obj%bin_wid,\' VEL_DMO = \', obj%vel_dmo"',
- "line #14'end subroutine foo'",
- "line #15'subroutine foo'",
- "Comment('',(16, 16))",
- "line #18'end'"]
+ 'line #12"obj%bin_wid,\' VEL_DMO = \', obj%vel_dmo"',
+ "line #13'end subroutine foo'",
+ "line #14'subroutine foo'",
+ "Comment('',(15, 15))",
+ "line #17'end'"]
reader = FortranStringReader(
string_fix90, ignore_comments=False)
assert reader.format.mode == 'fix', repr(reader.format.mode)
@@ -966,6 +971,81 @@ cComment
re.sub("u", "", expected.pop(0))
+def test_f2py_directive_fixf90(f2py_enabled):
+ ''' Test the handling of the f2py directive in fixed-format f90. '''
+ string_fix90 = """c -*- fix -*-
+ subroutine foo
+ a = 3!f2py.14 ! pi!
+!f2py a = 0.0
+ end subroutine foo"""
+ reader = FortranStringReader(string_fix90, ignore_comments=False)
+ reader.set_format(FortranFormat(False, False, f2py_enabled))
+ expected = ["Comment('c -*- fix -*-',(1, 1))",
+ "line #2'subroutine foo'"]
+ if f2py_enabled:
+ expected.extend(["line #3'a = 3.14'",
+ "Comment('! pi!',(3, 3))",
+ "line #4'a = 0.0'"])
+ else:
+ expected.extend(["line #3'a = 3'",
+ "Comment('!f2py.14 ! pi!',(3, 3))",
+ "Comment('!f2py a = 0.0',(4, 4))"])
+ expected.append("line #5'end subroutine foo'")
+ for item in reader:
+ # Remove 'u's to allow for py2/3 unicode differences
+ assert re.sub("u", "", six.text_type(item)) == \
+ re.sub("u", "", expected.pop(0))
+
+
+def test_f2py_freef90(f2py_enabled):
+ ''' Test the handling of f2py directives in free-format f90, in both
+ in-line and full-line comments. '''
+ lines = ["subroutine foo",
+ " a = 3!f2py.14 ! pi!",
+ "!f2py a = 0.0",
+ "end subroutine foo"]
+ reader = FortranStringReader("\n".join(lines), ignore_comments=False)
+ reader.set_format(FortranFormat(True, False, f2py_enabled))
+ expected = ["line #1'subroutine foo'"]
+ if f2py_enabled:
+ expected.extend(["line #2'a = 3.14'",
+ "Comment('! pi!',(2, 2))",
+ "line #3'a = 0.0'"])
+ else:
+ expected.extend(["line #2'a = 3'",
+ "Comment('!f2py.14 ! pi!',(2, 2))",
+ "Comment('!f2py a = 0.0',(3, 3))"])
+ expected.append("line #4'end subroutine foo'")
+ for item in reader:
+ # Remove 'u's to allow for py2/3 unicode differences
+ assert re.sub("u", "", six.text_type(item)) == \
+ re.sub("u", "", expected.pop(0))
+
+
[email protected](reason="Issue #270: f2py directives not working in F77 "
+ "code.")
+def test_f2py_directive_f77(f2py_enabled):
+ ''' Test the handling of the f2py directive in fixed-format f77. '''
+ string_f77 = """c -*- f77 -*-
+ subroutine foo
+cf2py call me ! hey
+ end"""
+ expected = ["Comment('c -*- f77 -*-',(1, 1))",
+ "line #2'subroutine foo'"]
+ if f2py_enabled:
+ expected.append("line #3'call me ! hey'")
+ else:
+ expected.append("Comment('cf2py call me ! hey',(3, 3))")
+ expected.append("line #4'end'")
+
+ # Reading from buffer
+ reader = FortranStringReader(
+ string_f77, ignore_comments=False)
+ for item in reader:
+ assert (re.sub("u", "", six.text_type(item)) ==
+ re.sub("u", "", expected.pop(0)))
+
+
def test_utf_char_in_code(log):
''' Check that we cope with Fortran code that contains UTF characters. This
is not valid Fortran but most compilers cope with it. '''
diff --git a/src/fparser/common/tests/test_sourceinfo.py b/src/fparser/common/tests/test_sourceinfo.py
index 115bab7..a1692db 100644
--- a/src/fparser/common/tests/test_sourceinfo.py
+++ b/src/fparser/common/tests/test_sourceinfo.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
##############################################################################
-# Copyright (c) 2017-2018 Science and Technology Facilities Council
+# Copyright (c) 2017-2021 Science and Technology Facilities Council
#
# All rights reserved.
#
@@ -94,25 +94,15 @@ def test_fortranformat_constructor(pretty):
assert unit_under_test.is_fix == (not pretty[0] and not pretty[1])
assert unit_under_test.is_pyf == (pretty[0] and pretty[1])
assert unit_under_test.mode == pretty[2]
+ assert not unit_under_test.f2py_enabled
-##############################################################################
[email protected](scope="module",
- params=[(False, False),
- (False, True),
- (True, False),
- (True, True)])
-def permutations(request):
- '''
- Returns all possible permutations of the input arguments.
- '''
- return request.param
-
-
-##############################################################################
-
[email protected]("permutations", [(False, False),
+ (False, True),
+ (True, False),
+ (True, True)])
def test_fortranformat_equality(permutations, pretty):
- #pylint: disable=redefined-outer-name
+ # pylint: disable=redefined-outer-name
'''
Tests that the equality operator works as expected.
'''
@@ -166,10 +156,9 @@ def test_fortranformat_from_mode(mode):
assert unit_under_test.is_fix == (not mode[1] and not mode[2])
assert unit_under_test.is_pyf == (mode[1] and mode[2])
assert str(unit_under_test.mode) == mode[0]
+ assert not unit_under_test.f2py_enabled
-##############################################################################
-
def test_format_from_mode_bad():
'''
Tests that an exception is thrown for an unrecognised mode string.
|
fparser handles `!f2py` comments as directives
Due to its origins in the f2py project, `FortranFileReader` still contains functionality that treats comments beginning with `!f2py` as directives. Essentially, it seems to strip off the `!f2py` and then attempts to parse the remainder of the line as standard Fortran.
In this issue we will investigate whether there is already functionality to control this behaviour and, if there isn't, add some.
|
0.0
|
463d4f7f27d952fba8b2400a6a54378d470853aa
|
[
"src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[True]",
"src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[True]",
"src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[False]",
"src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[False]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty3]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode3]"
] |
[
"src/fparser/common/tests/test_readfortran.py::test_empty_line_err",
"src/fparser/common/tests/test_readfortran.py::test_111fortranreaderbase",
"src/fparser/common/tests/test_readfortran.py::test_include_not_found",
"src/fparser/common/tests/test_readfortran.py::test_base_next_good_include",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_info",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_error",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_warning",
"src/fparser/common/tests/test_readfortran.py::test_base_handle_multilines",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_nonlabel",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_continuation",
"src/fparser/common/tests/test_readfortran.py::test_base_free_continuation",
"src/fparser/common/tests/test_readfortran.py::test_include1",
"src/fparser/common/tests/test_readfortran.py::test_include2",
"src/fparser/common/tests/test_readfortran.py::test_include3",
"src/fparser/common/tests/test_readfortran.py::test_include4",
"src/fparser/common/tests/test_readfortran.py::test_include5",
"src/fparser/common/tests/test_readfortran.py::test_include6[True]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[True]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_include6[False]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line1",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line2",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line3",
"src/fparser/common/tests/test_readfortran.py::test_filename_reader",
"src/fparser/common/tests/test_readfortran.py::test_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_none_in_fifo",
"src/fparser/common/tests/test_readfortran.py::test_bad_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_string_reader",
"src/fparser/common/tests/test_readfortran.py::test_inherited_f77",
"src/fparser/common/tests/test_readfortran.py::test_pyf",
"src/fparser/common/tests/test_readfortran.py::test_fix90",
"src/fparser/common/tests/test_readfortran.py::test_utf_char_in_code",
"src/fparser/common/tests/test_readfortran.py::test_extract_label",
"src/fparser/common/tests/test_readfortran.py::test_extract_construct_name",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#include",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#define",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#ifdef",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#if",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[abc",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[\"#\"-False]",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[!",
"src/fparser/common/tests/test_readfortran.py::test_reader_cpp_directives",
"src/fparser/common/tests/test_readfortran.py::test_multiline_cpp_directives",
"src/fparser/common/tests/test_readfortran.py::test_single_comment",
"src/fparser/common/tests/test_readfortran.py::test_many_comments",
"src/fparser/common/tests/test_readfortran.py::test_comments_within_continuation",
"src/fparser/common/tests/test_readfortran.py::test_single_blank_line[\\n]",
"src/fparser/common/tests/test_readfortran.py::test_single_blank_line[",
"src/fparser/common/tests/test_readfortran.py::test_multiple_blank_lines",
"src/fparser/common/tests/test_readfortran.py::test_blank_lines_within_continuation",
"src/fparser/common/tests/test_sourceinfo.py::test_format_constructor_faults",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations3]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations3]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations3]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations0]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations1]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations2]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations3]",
"src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_invalid",
"src/fparser/common/tests/test_sourceinfo.py::test_format_from_mode_bad",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content6]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content5]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content4]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content3]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content2]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content0]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content1]",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_utf8",
"src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_wrong"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-19 13:39:58+00:00
|
bsd-3-clause
| 5,727 |
|
stfc__fparser-287
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b173dc8..d99544f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,9 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
+18/01/2021 PR #287 for #280. Fixes overly-deep recursion when reading
+ multi-line comments.
+
11/01/2021 PR #285 for #283. Removes Structure_Constructor_2 class to fix
problem with Expr matching.
diff --git a/src/fparser/common/readfortran.py b/src/fparser/common/readfortran.py
index 60e4ea2..7960f99 100644
--- a/src/fparser/common/readfortran.py
+++ b/src/fparser/common/readfortran.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-# Modified work Copyright (c) 2017-2020 Science and Technology
+# Modified work Copyright (c) 2017-2021 Science and Technology
# Facilities Council
# Original work Copyright (c) 1999-2008 Pearu Peterson
@@ -1557,9 +1557,15 @@ class FortranReaderBase(object):
self.warning(message)
if name is not None:
self.error('No construct following construct-name.')
- if have_comment:
- return next(self)
- return self.comment_item('', startlineno, endlineno)
+
+ # If this point is reached, the line is a comment or is
+ # blank. If it is a comment, it has been pushed onto the
+ # fifo_item list.
+ try:
+ return self.fifo_item.pop(0)
+ except IndexError:
+ # A blank line is represented as an empty comment
+ return Comment('', (startlineno, endlineno), self)
class FortranFileReader(FortranReaderBase):
|
stfc/fparser
|
e5a314418bd65a42fff85e8ba4825a27a0cea21c
|
diff --git a/src/fparser/common/tests/test_readfortran.py b/src/fparser/common/tests/test_readfortran.py
index 8b75af1..58175e2 100644
--- a/src/fparser/common/tests/test_readfortran.py
+++ b/src/fparser/common/tests/test_readfortran.py
@@ -51,7 +51,7 @@ import pytest
from fparser.common.readfortran import FortranFileReader, \
FortranStringReader, FortranReaderBase, Line, extract_label, \
- extract_construct_name, CppDirective
+ extract_construct_name, CppDirective, Comment
from fparser.common.sourceinfo import FortranFormat
@@ -1042,7 +1042,7 @@ def test_reader_cpp_directives():
'end program test']
ref_text = '\n'.join(input_text[:4] + input_text[5:]).strip()
reader = FortranStringReader('\n'.join(input_text))
- lines = [item for item in reader]
+ lines = list(reader)
pp_lines = [1, 3, 5, 6, 8]
for i, line in enumerate(lines):
@@ -1061,8 +1061,192 @@ def test_multiline_cpp_directives():
'integer a', 'end program test']
ref_text = 'program test\n#define ABC 123\ninteger a\nend program test'
reader = FortranStringReader('\n'.join(input_text))
- lines = [item for item in reader]
+ lines = list(reader)
assert len(lines) == 4
assert isinstance(lines[1], CppDirective)
assert lines[1].span == (2, 3)
assert '\n'.join(item.line for item in lines) == ref_text
+
+
+# Tests for the get_source_item method in class FortranReaderBase :
+# Comments
+
+
+def test_single_comment():
+ '''Test that a free format single line comment is output as expected'''
+ input_text = "! a comment\n"
+
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == 1
+ assert isinstance(lines[0], Comment)
+ assert lines[0].span == (1, 1)
+ assert lines[0].line + "\n" == input_text
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 0
+
+
+def test_many_comments():
+ '''Test that a large consecutive number of single line comments can be
+ successfully processed. Earlier versions of the reader used
+ recursion for multiple consecutive free format single line
+ comments which resulted in a recursion error in this case.
+
+ '''
+ number_of_comments = 1000
+ input_text = "program hello\n"
+ for index in range(number_of_comments):
+ input_text += "! comment{0}\n".format(index+1)
+ input_text += "end program hello\n"
+
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == number_of_comments + 2
+ for index in range(1, number_of_comments):
+ assert isinstance(lines[index], Comment)
+ assert lines[index].span == (index+1, index+1)
+ assert lines[index].line + "\n" == "! comment{0}\n".format(index)
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 2
+
+
+def test_comments_within_continuation():
+ '''Test that comments and multi-line statements are processed
+ correctly.
+
+ '''
+ input_text = (
+ " ! Comment1\n"
+ " real :: a &\n"
+ " ! Comment2\n"
+ " ,b\n"
+ " ! Comment3\n")
+
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == 4
+
+ assert isinstance(lines[0], Comment)
+ assert lines[0].span == (1, 1)
+ assert lines[0].line == "! Comment1"
+
+ assert lines[1].span == (2, 4)
+ assert lines[1].line == "real :: a ,b"
+
+ assert isinstance(lines[2], Comment)
+ assert lines[2].span == (3, 3)
+ assert lines[2].line == "! Comment2"
+
+ assert isinstance(lines[3], Comment)
+ assert lines[3].span == (5, 5)
+ assert lines[3].line == "! Comment3"
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 1
+ assert lines[0].span == (2, 4)
+ assert lines[0].line == "real :: a ,b"
+
+
+# Tests for the get_source_item method in class FortranReaderBase :
+# Blank lines
+
+
[email protected]("input_text", ["\n", " \n"])
+def test_single_blank_line(input_text):
+ '''Test that a single blank line with or without white space is output
+ as an empty Comment object.
+
+ '''
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == 1
+ assert isinstance(lines[0], Comment)
+ assert lines[0].span == (1, 1)
+ assert lines[0].line == ""
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 0
+
+
+def test_multiple_blank_lines():
+ '''Test that multiple blank lines with or without white space are
+ output as an empty Comment objects.
+
+ '''
+ input_text = (
+ " \n\n"
+ "program test\n"
+ " \n\n"
+ "end program test\n"
+ " \n\n")
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == 8
+ for index in [0, 1, 3, 4, 6, 7]:
+ assert isinstance(lines[index], Comment)
+ assert lines[index].span == (index+1, index+1)
+ assert lines[index].line == ""
+ assert isinstance(lines[2], Line)
+ assert lines[2].span == (3, 3)
+ assert lines[2].line == "program test"
+ assert isinstance(lines[5], Line)
+ assert lines[5].span == (6, 6)
+ assert lines[5].line == "end program test"
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 2
+ assert isinstance(lines[0], Line)
+ assert lines[0].span == (3, 3)
+ assert lines[0].line == "program test"
+ assert isinstance(lines[1], Line)
+ assert lines[1].span == (6, 6)
+ assert lines[1].line == "end program test"
+
+
+def test_blank_lines_within_continuation():
+ '''Test that blank lines and multi-line statements are processed
+ correctly. Note, empty lines within a multi-line statement are
+ removed.
+
+ '''
+ input_text = (
+ " \n"
+ " real :: a &\n"
+ " \n\n"
+ " ,b\n"
+ " \n"
+ " real :: c\n")
+
+ reader = FortranStringReader(input_text, ignore_comments=False)
+ lines = list(reader)
+ assert len(lines) == 4
+
+ assert isinstance(lines[0], Comment)
+ assert lines[0].span == (1, 1)
+ assert lines[0].line == ""
+ assert isinstance(lines[1], Line)
+ assert lines[1].span == (2, 5)
+ assert lines[1].line == "real :: a ,b"
+ assert isinstance(lines[2], Comment)
+ assert lines[2].span == (6, 6)
+ assert lines[2].line == ""
+ assert isinstance(lines[3], Line)
+ assert lines[3].span == (7, 7)
+ assert lines[3].line == "real :: c"
+
+ reader = FortranStringReader(input_text, ignore_comments=True)
+ lines = list(reader)
+ assert len(lines) == 2
+ assert isinstance(lines[0], Line)
+ assert lines[0].span == (2, 5)
+ assert lines[0].line == "real :: a ,b"
+ assert isinstance(lines[1], Line)
+ assert lines[1].span == (7, 7)
+ assert lines[1].line == "real :: c"
|
fparser.api.parse fails for long comment blocks
When parsing a kernel that has a comment header longer than 161 lines PSyclone reports the incorrect Fortran error, e.g.
```
"Parse Error: Failed to parse kernel code 'test_fparser_kernel_mod.f90'. Is the Fortran correct?"
```
The error is raised in the [`psyclone.parse.kernel.get_kernel_parse_tree`](https://github.com/stfc/PSyclone/blob/master/src/psyclone/parse/kernel.py#L146) function. However, this is actually an fparser failure but that is not visible from PSyclone as the fparser logging is [disabled](https://github.com/stfc/PSyclone/blob/master/src/psyclone/parse/kernel.py#L160).
`psyclone.parse.kernel.get_kernel_parse_tree` calls [`fparser.api.parse`](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L150) function. This function, in turn, calls the [`fparser.one.parsefortran.FortranParser.parse`](https://github.com/stfc/fparser/blob/master/src/fparser/one/parsefortran.py#L123) function after creating a [reader object](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L83) from a source file.
Attached is the test example [test_fparser.zip](https://github.com/stfc/fparser/files/5771679/test_fparser.zip) with the Python test script `test_parsekernel.py` that illustrates the fparser error and uses the attached test kernel `test_fparser_kernel_mod.f90` to trigger the error.
The attached script tries to parse the kernel by two methods:
1. Directly calling the `fparser.api.parse` function as it is done in [`psyclone.parse.kernel.get_kernel_parse_tree`](https://github.com/stfc/PSyclone/blob/master/src/psyclone/parse/kernel.py#L162);
2. Executing step-by-step commands from the `fparser.api.parse` function that calls [`fparser.api.get_reader`](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L185) and then [`fparser.one.parsefortran.FortranParser.parse`](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L189) function.
The outcome of these methods depends on the value of `ignore_comments` parameter in the [`fparser.api.get_reader`](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L84) and [`fparser.api.parse`](https://github.com/stfc/fparser/blob/master/src/fparser/api.py#L151) functions in an fparser installation. Currently both instances are set to `True` in the `fparser.api`script (and hence in an fparser installation) so a kernel parse tree does not include comments.
- With the default `ignore_comments=True` setting in `get_reader` and `parse` functions the first method, a direct call to `fparser.api.parse` function fails with
```
File "test_parsekernel.py", line 50, in <module>
parse_tree = fpapi.parse(filepath)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/api.py", line 189, in parse
parser.parse()
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/one/parsefortran.py", line 143, in parse
raise error
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/one/parsefortran.py", line 128, in parse
self.block = BeginSource(self)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/common/base_classes.py", line 776, in __init__
Statement.__init__(self, parent, item)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/common/base_classes.py", line 605, in __init__
self.process_item()
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/one/block_statements.py", line 324, in process_item
self.fill(end_flag=True)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/common/base_classes.py", line 827, in fill
if self.process_subitem(item):
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/one/block_statements.py", line 366, in process_subitem
return BeginStatement.process_subitem(self, item)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/common/base_classes.py", line 928, in process_subitem
self.handle_unknown_item(item)
File "/data/users/lfric/modules/packages.rhel7/psyclone/1.9.0/lib/python3.6/site-packages/fparser/common/base_classes.py", line 945, in handle_unknown_item
raise AnalyzeError(message)
fparser.common.utils.AnalyzeError: While processing 'test_fparser_kernel_mod.f90' (mode='free')..
219: end subroutine test_fparser_code
220:
221:end module test_fparser_kernel_mod <== no parse pattern found for "end module test_fparser_kernel_mod" in 'BeginSource' block.
```
The second method with the step-by-step commands to create reader and parser objects from `fparser.api.parse` works fine.
- When an fparser installation is hacked to set `ignore_comments` to `False` in `fparser.api.get_reader` and `fparser.api.parse` functions , the first method, a direct call to `fparser.api.parse` function works fine. The second method with the step-by-step commands to create instances of reader and parser objects also works fine if `ignore_comments = False` in the attached script. If it is `True`, however, it fails with the same error as the first method with the default `ignore_comments=False` setting in the `fparser.api` installed module.
When the [maximum depth of the Python interpreter stack](https://docs.python.org/3/library/sys.html#sys.setrecursionlimit) is increased from the default limit of 1000 both the direct call to `fparser.api.parse` and step-by-step approach work regardless of the `ignore_comments` setting in fparser installation and the test script (demonstrated by enbling the commented line `sys.setrecursionlimit(1100)`).
Parsing the offending kernel by fparser2 (`fparser2 test_fparser_kernel_mod.f90`) works fine.
|
0.0
|
e5a314418bd65a42fff85e8ba4825a27a0cea21c
|
[
"src/fparser/common/tests/test_readfortran.py::test_many_comments"
] |
[
"src/fparser/common/tests/test_readfortran.py::test_empty_line_err",
"src/fparser/common/tests/test_readfortran.py::test_111fortranreaderbase",
"src/fparser/common/tests/test_readfortran.py::test_include_not_found",
"src/fparser/common/tests/test_readfortran.py::test_base_next_good_include",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_info",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_error",
"src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_warning",
"src/fparser/common/tests/test_readfortran.py::test_base_handle_multilines",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_nonlabel",
"src/fparser/common/tests/test_readfortran.py::test_base_fixed_continuation",
"src/fparser/common/tests/test_readfortran.py::test_base_free_continuation",
"src/fparser/common/tests/test_readfortran.py::test_include1",
"src/fparser/common/tests/test_readfortran.py::test_include2",
"src/fparser/common/tests/test_readfortran.py::test_include3",
"src/fparser/common/tests/test_readfortran.py::test_include4",
"src/fparser/common/tests/test_readfortran.py::test_include5",
"src/fparser/common/tests/test_readfortran.py::test_include6[True]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[True]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[True]",
"src/fparser/common/tests/test_readfortran.py::test_include6[False]",
"src/fparser/common/tests/test_readfortran.py::test_get_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_put_item_include[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_put_item[False]",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line1",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line2",
"src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line3",
"src/fparser/common/tests/test_readfortran.py::test_filename_reader",
"src/fparser/common/tests/test_readfortran.py::test_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_none_in_fifo",
"src/fparser/common/tests/test_readfortran.py::test_bad_file_reader",
"src/fparser/common/tests/test_readfortran.py::test_string_reader",
"src/fparser/common/tests/test_readfortran.py::test_inherited_f77",
"src/fparser/common/tests/test_readfortran.py::test_pyf",
"src/fparser/common/tests/test_readfortran.py::test_fix90",
"src/fparser/common/tests/test_readfortran.py::test_utf_char_in_code",
"src/fparser/common/tests/test_readfortran.py::test_extract_label",
"src/fparser/common/tests/test_readfortran.py::test_extract_construct_name",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#include",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#define",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#ifdef",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#if",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[abc",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[\"#\"-False]",
"src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[!",
"src/fparser/common/tests/test_readfortran.py::test_reader_cpp_directives",
"src/fparser/common/tests/test_readfortran.py::test_multiline_cpp_directives",
"src/fparser/common/tests/test_readfortran.py::test_single_comment",
"src/fparser/common/tests/test_readfortran.py::test_comments_within_continuation",
"src/fparser/common/tests/test_readfortran.py::test_single_blank_line[\\n]",
"src/fparser/common/tests/test_readfortran.py::test_single_blank_line[",
"src/fparser/common/tests/test_readfortran.py::test_multiple_blank_lines",
"src/fparser/common/tests/test_readfortran.py::test_blank_lines_within_continuation"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-01-15 00:11:05+00:00
|
bsd-3-clause
| 5,728 |
|
stfc__fparser-289
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de0a4d9..58aa14c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,7 +15,11 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
-20/01/2021 PR #286 FOR #284. Adds checking for datatype of *_Expr classes.
+20/01/2021 PR #289 for #288. Bug fix for matching expressions containing
+ real literals with signed exponents. This bug was introduced
+ by #285.
+
+20/01/2021 PR #286 for #284. Adds checking for datatype of *_Expr classes.
18/01/2021 PR #287 for #280. Fixes overly-deep recursion when reading
multi-line comments.
diff --git a/doc/developers_guide.rst b/doc/developers_guide.rst
index 5120e64..b34125b 100644
--- a/doc/developers_guide.rst
+++ b/doc/developers_guide.rst
@@ -1,4 +1,4 @@
-.. Copyright (c) 2017-2020 Science and Technology Facilities Council.
+.. Copyright (c) 2017-2021 Science and Technology Facilities Council.
All rights reserved.
@@ -818,6 +818,118 @@ a valid Fortran program.
# +++++++++++++
# TBD
+Expression matching
++++++++++++++++++++
+
+The Fortran2003 rules specify a hierarchy of expressions (specified in
+levels). In summary::
+
+ R722 expr is [ expr defined-binary-op ] level-5-expr
+ R717 level-5-expr is [ level-5-expr equiv-op ] equiv-operand
+ R716 equiv-operand is [ equiv-operand or-op ] or-operand
+ R715 or-operand is [ or-operand and-op ] and-operand
+ R714 and-operand is [ not-op ] level-4-expr
+ R712 level-4-expr is [ level-3-expr rel-op ] level-3-expr
+ R710 level-3-expr is [ level-3-expr concat-op ] level-2-expr
+ R706 level-2-expr is [[level-2-expr] add_op ] add-operand
+ R705 add-operand is [ add-operand mult-op ] mult-operand
+ R704 mult-operand is level-1-expr [ power-op mult-operand ]
+ R702 level-1-expr is [ defined-unary-op ] primary
+
+As can hopefully be seen, the "top level" rule is `expr`, this depends
+on a `level-5_expr`, which depends on an `equiv-operand` and so on in
+a hierarchy in the order listed.
+
+Fparser2 naturally follows this hierarchy, attempting to match in the
+order specified. This works well apart from one case, which is the
+matching of a Level-2 expression::
+
+ R706 level-2-expr is [[level-2-expr] add_op ] add-operand
+
+The problem is to do with falsely matching an exponent in a
+literal. Take the following example::
+
+ a - 1.0e-1
+
+When searching for a match, the following pattern is a valid candidate
+and will be the candidate used in fparser2 as fparser2 matches from the
+right hand side of a string by default::
+
+ level-2-expr = "a - 1.0e"
+ add-op = "-"
+ add-operand = "1"
+
+As expected, this would fail to match, due to the level-2 expression
+("a - 1.0e") being invalid. However, once R706 failed to match it
+would not be called again as fparser2 follows the rule hierarchy
+mentioned earlier. Therefore fparser2 would fail to match this string.
+
+To solve the problem for this specific case fparser2 includes
+additional code when implementing R706. There is an optional `is_add`
+argument in `BinaryOpBase` which is set to `True` in the
+`Level_2_Expr` class. This argument causes the `rsplit` method in the
+`pattern` instance to try to match a real literal constant on the
+right hand side of the string. If a literal constant exists then the
+exponent is ignored and the correct `+` or `-` is matched
+successfully::
+
+ level-2-expr = "a"
+ add-op = "-"
+ add-operand = "1.0e-1"
+
+However, this aproach only works if the real literal constant is on
+the right hand side of the string. Consider::
+
+ a - 1.0e-1 * b
+
+In this case the attempted match would be::
+
+ level-2-expr = "a - 1.0e"
+ add-op = "-"
+ add-operand = "1 * b"
+
+This would fail as `level-2-expr` is not valid and fparser2 would
+proceed to try to match with::
+
+ R705 add-operand is [ add-operand mult-op ] mult-operand
+
+This would attempt to match the following::
+
+ add-operand = "a - 1.0e-1"
+ mult-op = "*"
+ mult-operand = "b"
+
+This looks good, but unfortunately the `add-operand` part of the
+string ("a - 1.0e-1") would fail to match as R705 is lower in the
+hierarchy than R706, so R706 will not be called again.
+
+To solve this problem, R705 has been modified in the fparser2 implementation to::
+
+ R705 add-operand is [ level-2-expr mult-op ] mult-operand
+
+By replacing `add-operand` with `level-2-expr` we allow the "a -
+1.0e-1" to be matched with R706, i.e. we allow fparser2 to jump back up
+the rule hierarchy to fix the fallout from missing the original match.
+
+We now end up with something that can be matched correctly due to the
+`is_add` fix in rule R706.
+
+In combination these two modifications can cope with the problem of
+falsely matching an exponent in a literal.
+
+There are at least two other potential solutions which are probably
+preferable to the current solution, with the 2nd likely to be the most
+robust.
+
+1: R706 could be implemented so that it never matched an exponent in a
+literal. This would require a robust way of determining whether the
+"-" or "+" was an exponent in a literal.
+
+2: R706 could be implemented so that it tried to match a second time
+if the first match failed, using the next "+" or "-" operator found in
+the string to the left of the first one.
+
+
Continuous Integration
----------------------
diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py
index 2f505d7..a0f0c58 100644
--- a/src/fparser/two/Fortran2003.py
+++ b/src/fparser/two/Fortran2003.py
@@ -4747,19 +4747,53 @@ class Mult_Operand(BinaryOpBase): # R704
match = staticmethod(match)
-class Add_Operand(BinaryOpBase): # R705
- """
- <add-operand> = [ <add-operand> <mult-op> ] <mult-operand>
- <mult-op> = *
- | /
- """
+class Add_Operand(BinaryOpBase): # pylint: disable=invalid-name
+ '''Fortran 2003 rule R705
+
+ add-operand is [ add-operand mult-op ] mult-operand
+
+ Rule R705 is implemented in two parts, the first with the optional
+ part included (in the match method for this class) and the second
+ without the optional part (specified in subclass_names).
+
+ Note rule R708 (mult-op is * or /) is implemented directly here as
+ the mult_op pattern.
+
+ Rule R705 specifies matching using 'add-operand', however this
+ implementation uses Level_2_Expr instead. The reason for this is
+ due to the potential to accidentally match a negative exponent as
+ the minus sign in a level-2-expr. If this happens then it is
+ possible to end up matching a * or / (a level 1 expression) before
+ matching a valid + or - which would normally result in no match
+ overall as * or / are matched after + or -. By matching with
+ Level_2_Expr, this allows us to match with a * or / and then a +
+ or - afterwards. A particular example is "a + 1.0e-1 * c", where
+ (rightly) failing to match on the "-" leads us to try to match on
+ the "*" which then fails to match on the + (as + and - have
+ already been tested).
+
+ '''
subclass_names = ['Mult_Operand']
- use_names = ['Add_Operand', 'Mult_Operand']
+ use_names = ['Level_2_Expr', 'Mult_Operand']
+ @staticmethod
def match(string):
- return BinaryOpBase.match(
- Add_Operand, pattern.mult_op.named(), Mult_Operand, string)
- match = staticmethod(match)
+ '''Implement the matching for the add-operand rule. Makes use of the
+ pre-defined mult_op pattern and the BinaryOpBase baseclass.
+
+ :param str string: the string to match.
+
+ :returns: a tuple of size 3 containing an fparser2 class \
+ instance matching a level-2-expr expression, a string \
+ containing the matched operator and an fparser2 class \
+ instance matching a mult-operand if there is a match, or \
+ None if there is not.
+ :rtype: (subclass of :py:class:`fparser.two.utils.Base`, str, \
+ subclass of :py:class:`fparser.two.utils.Base`) or NoneType
+
+ '''
+ return BinaryOpBase.match(
+ Level_2_Expr, pattern.mult_op.named(), Mult_Operand, string)
class Level_2_Expr(BinaryOpBase): # R706
@@ -4792,9 +4826,9 @@ class Level_2_Unary_Expr(UnaryOpBase): # R706.c
pattern.add_op.named(), Add_Operand, string)
match = staticmethod(match)
-# R707: <power-op> = **
-# R708: <mult-op> = * | /
-# R709: <add-op> = + | -
+# R707: power-op is **
+# R708: mult-op is * or /
+# R709: add-op is + or -
class Level_3_Expr(BinaryOpBase): # R710
|
stfc/fparser
|
3e2774fabf33079ee81119139dc7ac17c9e4454e
|
diff --git a/src/fparser/two/tests/fortran2003/test_add_operand_r705.py b/src/fparser/two/tests/fortran2003/test_add_operand_r705.py
new file mode 100644
index 0000000..1775885
--- /dev/null
+++ b/src/fparser/two/tests/fortran2003/test_add_operand_r705.py
@@ -0,0 +1,107 @@
+# Copyright (c) 2021 Science and Technology Facilities Council
+
+# All rights reserved.
+
+# Modifications made as part of the fparser project are distributed
+# under the following license:
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+
+# 3. Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''Test Fortran 2003 rule R705 : This file tests support for the
+Add_Operand class.
+
+'''
+
+import pytest
+from fparser.two.utils import NoMatchError
+from fparser.two.Fortran2003 import Add_Operand
+from fparser.two.parser import ParserFactory
+# This is required to setup the fortran2003 classes (when matching
+# with Add_Operand)
+_ = ParserFactory().create(std="f2003")
+
+
[email protected]("string,str_repr", [
+ ("a ** b", "Mult_Operand(Name('a'), '**', Name('b'))"),
+ (".DEFINED. a", "Level_1_Expr('.DEFINED.', Name('a'))"),
+ ("1.0", "Real_Literal_Constant('1.0', None)"),
+ ("(a + b)", "Parenthesis('(', Level_2_Expr(Name('a'), '+', "
+ "Name('b')), ')')")])
+def test_mult(string, str_repr):
+ '''Test for a successful match with a valid mult-operand string'''
+ result = Add_Operand(string)
+ assert str(result) == string
+ assert repr(result) == str_repr
+
+
+def test_mult_fail():
+ '''Test for a failure to match an invalid multi-operand string'''
+ with pytest.raises(NoMatchError) as info:
+ Add_Operand("a .and. b")
+ assert "Add_Operand: 'a .and. b'" in str(info.value)
+
+
[email protected]("string,str_repr", [
+ ("a * b", "Add_Operand(Name('a'), '*', Name('b'))"),
+ ("a / b", "Add_Operand(Name('a'), '/', Name('b'))"),
+ ("a * b * c", "Add_Operand(Add_Operand(Name('a'), '*', Name('b')), "
+ "'*', Name('c'))"),
+ ("a * b / c", "Add_Operand(Add_Operand(Name('a'), '*', Name('b')), "
+ "'/', Name('c'))")])
+def test_add_operand(string, str_repr):
+ '''Test for a successful match with a valid add_operand'''
+ result = Add_Operand(string)
+ assert str(result) == string
+ assert repr(result) == str_repr
+
+
[email protected]("string,str_repr", [
+ ("a + b * c", "Add_Operand(Level_2_Expr(Name('a'), '+', Name('b')), "
+ "'*', Name('c'))"),
+ ("a + 1.0E-1 * c", "Add_Operand(Level_2_Expr(Name('a'), '+', "
+ "Real_Literal_Constant('1.0E-1', None)), '*', Name('c'))")])
+def test_level_2_match(string, str_repr):
+ '''Test that the level_2_expr class match allows a "+" or "-" operator
+ to be matched after a "*" or "/" operator if the former is to the
+ left of the latter. This would not be the case according to the
+ Fortran2003 rules, however it is needed to recover from a false
+ match on the '-' of an exponent.
+
+ '''
+ result = Add_Operand(string)
+ assert str(result) == string
+ assert repr(result) == str_repr
+
+
[email protected]("string", ["a + b", "_ * b", "a * _",
+ "a * b + c"])
+def test_add_operand_fail(string):
+ '''Test for a failure to match an invalid add-operand string'''
+ with pytest.raises(NoMatchError) as info:
+ Add_Operand(string)
+ assert "Add_Operand: '{0}'".format(string) in str(info.value)
diff --git a/src/fparser/two/tests/test_fortran2003.py b/src/fparser/two/tests/test_fortran2003.py
index 92fb75d..de88187 100644
--- a/src/fparser/two/tests/test_fortran2003.py
+++ b/src/fparser/two/tests/test_fortran2003.py
@@ -1797,27 +1797,6 @@ def test_mult_operand(): # R704
assert str(obj) == '0.0E-1'
-def test_add_operand(): # R705
-
- tcls = Add_Operand
- obj = tcls('a*b')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'a * b'
- assert repr(obj) == "Add_Operand(Name('a'), '*', Name('b'))"
-
- obj = tcls('a/b')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'a / b'
-
- obj = tcls('a**b')
- assert isinstance(obj, Mult_Operand), repr(obj)
- assert str(obj) == 'a ** b'
-
- obj = tcls('0.0E-1')
- assert isinstance(obj, Real_Literal_Constant), repr(obj)
- assert str(obj) == '0.0E-1'
-
-
def test_level_2_expr(): # R706
tcls = Level_2_Expr
|
Expressions containing -ve exponents cannot be parsed
master is currently broken. e.g. the Fortran `zMv = zSST+1.33d-3*zSST` causes a syntax error. If I change the numerical constant to `1.33d3` instead then all is fine. This may be related to the recent bug fix for the slow parsing of expressions @rupertford?
|
0.0
|
3e2774fabf33079ee81119139dc7ac17c9e4454e
|
[
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_level_2_match[a"
] |
[
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_mult[a",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_mult[.DEFINED.",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_mult[1.0-Real_Literal_Constant('1.0',",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_mult[(a",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_mult_fail",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_add_operand[a",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_add_operand_fail[a",
"src/fparser/two/tests/fortran2003/test_add_operand_r705.py::test_add_operand_fail[_",
"src/fparser/two/tests/test_fortran2003.py::test_specification_part",
"src/fparser/two/tests/test_fortran2003.py::test_constant",
"src/fparser/two/tests/test_fortran2003.py::test_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_value",
"src/fparser/two/tests/test_fortran2003.py::test_intrinsic_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_signed_int_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_int_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_binary_constant",
"src/fparser/two/tests/test_fortran2003.py::test_octal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_hex_constant",
"src/fparser/two/tests/test_fortran2003.py::test_signed_real_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_real_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_char_selector",
"src/fparser/two/tests/test_fortran2003.py::test_complex_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_name",
"src/fparser/two/tests/test_fortran2003.py::test_length_selector",
"src/fparser/two/tests/test_fortran2003.py::test_char_length",
"src/fparser/two/tests/test_fortran2003.py::test_logical_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_end_type_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_sequence_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_decl",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_decl",
"src/fparser/two/tests/test_fortran2003.py::test_proc_component_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_private_components_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_bound_procedure_part",
"src/fparser/two/tests/test_fortran2003.py::test_proc_binding_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_generic_binding",
"src/fparser/two/tests/test_fortran2003.py::test_final_binding",
"src/fparser/two/tests/test_fortran2003.py::test_derived_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_spec",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_structure_constructor",
"src/fparser/two/tests/test_fortran2003.py::test_component_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_enum_def",
"src/fparser/two/tests/test_fortran2003.py::test_enum_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_array_constructor",
"src/fparser/two/tests/test_fortran2003.py::test_ac_spec",
"src/fparser/two/tests/test_fortran2003.py::test_ac_value_list",
"src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do_control",
"src/fparser/two/tests/test_fortran2003.py::test_type_declaration_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_declaration_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_dimension_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_intent_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_entity_decl",
"src/fparser/two/tests/test_fortran2003.py::test_target_entity_decl",
"src/fparser/two/tests/test_fortran2003.py::test_access_spec",
"src/fparser/two/tests/test_fortran2003.py::test_language_binding_spec",
"src/fparser/two/tests/test_fortran2003.py::test_explicit_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_upper_bound",
"src/fparser/two/tests/test_fortran2003.py::test_assumed_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_deferred_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_assumed_size_spec",
"src/fparser/two/tests/test_fortran2003.py::test_access_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_data_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_data_stmt_set",
"src/fparser/two/tests/test_fortran2003.py::test_data_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_dimension_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_intent_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_optional_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_parameter_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_named_constant_def",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_decl",
"src/fparser/two/tests/test_fortran2003.py::test_protected_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_save_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_saved_entity",
"src/fparser/two/tests/test_fortran2003.py::test_target_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_value_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_volatile_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_implicit_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_implicit_spec",
"src/fparser/two/tests/test_fortran2003.py::test_letter_spec",
"src/fparser/two/tests/test_fortran2003.py::test_namelist_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_equivalence_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_common_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_common_block_object",
"src/fparser/two/tests/test_fortran2003.py::test_substring",
"src/fparser/two/tests/test_fortran2003.py::test_substring_range",
"src/fparser/two/tests/test_fortran2003.py::test_part_ref",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_inquiry",
"src/fparser/two/tests/test_fortran2003.py::test_array_section",
"src/fparser/two/tests/test_fortran2003.py::test_section_subscript",
"src/fparser/two/tests/test_fortran2003.py::test_section_subscript_list",
"src/fparser/two/tests/test_fortran2003.py::test_subscript_triplet",
"src/fparser/two/tests/test_fortran2003.py::test_allocate_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_alloc_opt",
"src/fparser/two/tests/test_fortran2003.py::test_nullify_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_deallocate_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_level_1_expr",
"src/fparser/two/tests/test_fortran2003.py::test_mult_operand",
"src/fparser/two/tests/test_fortran2003.py::test_level_2_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_2_unary_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_3_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_4_expr",
"src/fparser/two/tests/test_fortran2003.py::test_and_operand",
"src/fparser/two/tests/test_fortran2003.py::test_or_operand",
"src/fparser/two/tests/test_fortran2003.py::test_equiv_operand",
"src/fparser/two/tests/test_fortran2003.py::test_level_5_expr",
"src/fparser/two/tests/test_fortran2003.py::test_expr",
"src/fparser/two/tests/test_fortran2003.py::test_logical_initialization_expr",
"src/fparser/two/tests/test_fortran2003.py::test_assignment_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_assignment_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_proc_component_ref",
"src/fparser/two/tests/test_fortran2003.py::test_where_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_where_construct_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_forall_construct",
"src/fparser/two/tests/test_fortran2003.py::test_forall_triplet_spec",
"src/fparser/two/tests/test_fortran2003.py::test_if_nonblock_do",
"src/fparser/two/tests/test_fortran2003.py::test_case_selector",
"src/fparser/two/tests/test_fortran2003.py::test_associate_construct",
"src/fparser/two/tests/test_fortran2003.py::test_select_type_construct",
"src/fparser/two/tests/test_fortran2003.py::test_select_type_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_guard_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_label_do_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_loop_control",
"src/fparser/two/tests/test_fortran2003.py::test_continue_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_stop_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_io_unit",
"src/fparser/two/tests/test_fortran2003.py::test_read_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_write_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_print_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_io_control_spec",
"src/fparser/two/tests/test_fortran2003.py::test_io_control_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_format",
"src/fparser/two/tests/test_fortran2003.py::test_io_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_io_implied_do_control",
"src/fparser/two/tests/test_fortran2003.py::test_wait_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_wait_spec",
"src/fparser/two/tests/test_fortran2003.py::test_backspace_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_endfile_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_rewind_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_position_spec",
"src/fparser/two/tests/test_fortran2003.py::test_flush_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_flush_spec",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_spec",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_open_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_connect_spec",
"src/fparser/two/tests/test_fortran2003.py::test_connect_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_format_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_format_specification",
"src/fparser/two/tests/test_fortran2003.py::test_format_item",
"src/fparser/two/tests/test_fortran2003.py::test_data_edit_desc",
"src/fparser/two/tests/test_fortran2003.py::test_format_item_list",
"src/fparser/two/tests/test_fortran2003.py::test_main_program0",
"src/fparser/two/tests/test_fortran2003.py::test_module",
"src/fparser/two/tests/test_fortran2003.py::test_module_subprogram_part",
"src/fparser/two/tests/test_fortran2003.py::test_module_nature",
"src/fparser/two/tests/test_fortran2003.py::test_rename",
"src/fparser/two/tests/test_fortran2003.py::test_interface_block",
"src/fparser/two/tests/test_fortran2003.py::test_interface_specification",
"src/fparser/two/tests/test_fortran2003.py::test_interface_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_end_interface_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_interface_body",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_body",
"src/fparser/two/tests/test_fortran2003.py::test_function_body",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_generic_spec",
"src/fparser/two/tests/test_fortran2003.py::test_dtio_generic_spec",
"src/fparser/two/tests/test_fortran2003.py::test_import_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_external_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_declaration_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[private-Access_Spec-PRIVATE]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[public-Access_Spec-PUBLIC]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c)-Language_Binding_Spec-BIND(C)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c,",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(in)-Proc_Attr_Spec-INTENT(IN)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(out)-Proc_Attr_Spec-INTENT(OUT)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(inout)-Proc_Attr_Spec-INTENT(INOUT)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[optional-Proc_Attr_Spec-OPTIONAL]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[pointer-Proc_Attr_Spec-POINTER]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[protected-Proc_Attr_Spec-PROTECTED]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[save-Proc_Attr_Spec-SAVE]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_decl",
"src/fparser/two/tests/test_fortran2003.py::test_intrinsic_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_function_reference",
"src/fparser/two/tests/test_fortran2003.py::test_call_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_designator",
"src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec",
"src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_alt_return_spec",
"src/fparser/two/tests/test_fortran2003.py::test_function_subprogram",
"src/fparser/two/tests/test_fortran2003.py::test_function_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_dummy_arg_name",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer-Intrinsic_Type_Spec-INTEGER]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[real-Intrinsic_Type_Spec-REAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[double",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[complex-Intrinsic_Type_Spec-COMPLEX]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[character-Intrinsic_Type_Spec-CHARACTER]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[logical-Intrinsic_Type_Spec-LOGICAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[type(foo)-Declaration_Type_Spec-TYPE(foo)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(bar)-Declaration_Type_Spec-CLASS(bar)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(*)-Declaration_Type_Spec-CLASS(*)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[elemental-Prefix_Spec-ELEMENTAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[impure-Prefix_Spec-IMPURE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[module-Prefix_Spec-MODULE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[pure-Prefix_Spec-PURE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[recursive-Prefix_Spec-RECURSIVE]",
"src/fparser/two/tests/test_fortran2003.py::test_suffix",
"src/fparser/two/tests/test_fortran2003.py::test_end_function_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_subprogram",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_dummy_arg",
"src/fparser/two/tests/test_fortran2003.py::test_end_subroutine_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_entry_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_return_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_contains"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-01-19 01:58:04+00:00
|
bsd-3-clause
| 5,729 |
|
stfc__fparser-311
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dfd3451..5aca068 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,8 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
+15/03/2022 PR #311 for #310. Allows symbol table scope to be None.
+
08/12/2021 PR #293 towards #201. Initial symbol-table support added.
02/12/2021 PR #305 for #304. Fix failing build of documentation on RTD.
diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py
index 02f15c2..d0e1d53 100644
--- a/src/fparser/two/Fortran2003.py
+++ b/src/fparser/two/Fortran2003.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-# Modified work Copyright (c) 2017-2021 Science and Technology
+# Modified work Copyright (c) 2017-2022 Science and Technology
# Facilities Council.
# Original work Copyright (c) 1999-2008 Pearu Peterson
@@ -2668,7 +2668,7 @@ class Type_Declaration_Stmt(Type_Declaration_StmtBase): # R501
'''
Attempts to match the supplied string as a type declaration. If the
match is successful the declared symbols are added to the symbol table
- of the current scope.
+ of the current scope (if there is one).
:param str string: the string to match.
@@ -2684,7 +2684,7 @@ class Type_Declaration_Stmt(Type_Declaration_StmtBase): # R501
# symbol table of the current scoping region.
table = SYMBOL_TABLES.current_scope
- if isinstance(result[0], Intrinsic_Type_Spec):
+ if table and isinstance(result[0], Intrinsic_Type_Spec):
# We have a definition of symbol(s) of intrinsic type
decl_list = walk(result, Entity_Decl)
for decl in decl_list:
@@ -9293,7 +9293,8 @@ class Use_Stmt(StmtBase): # pylint: disable=invalid-name
def match(string):
'''
Wrapper for the match method that captures any successfully-matched
- use statements in the symbol table associated with the current scope.
+ use statements in the symbol table associated with the current scope
+ (if there is one).
:param str string: Fortran code to check for a match.
@@ -9308,12 +9309,13 @@ class Use_Stmt(StmtBase): # pylint: disable=invalid-name
result = Use_Stmt._match(string)
if result:
table = SYMBOL_TABLES.current_scope
- only_list = None
- # TODO #201 we currently ignore any symbol renaming here
- if isinstance(result[4], Only_List):
- names = walk(result[4], Name)
- only_list = [name.string for name in names]
- table.add_use_symbols(str(result[2]), only_list)
+ if table:
+ only_list = None
+ # TODO #201 we currently ignore any symbol renaming here
+ if isinstance(result[4], Only_List):
+ names = walk(result[4], Name)
+ only_list = [name.string for name in names]
+ table.add_use_symbols(str(result[2]), only_list)
return result
@@ -10281,7 +10283,9 @@ class Intrinsic_Function_Reference(CallBase): # No explicit rule
table.lookup(function_name)
# We found a matching name so refuse to match this intrinsic.
return None
- except KeyError:
+ except (KeyError, AttributeError):
+ # There is either no matching name in the table or we have
+ # no current scoping region.
pass
# This if/else will not be needed once issue #170 has been
|
stfc/fparser
|
e0b14f895f70a368ec83acc9adbb6fe17080392e
|
diff --git a/src/fparser/two/tests/fortran2003/test_intrinsics.py b/src/fparser/two/tests/fortran2003/test_intrinsics.py
index 5e42c1b..92d8f29 100644
--- a/src/fparser/two/tests/fortran2003/test_intrinsics.py
+++ b/src/fparser/two/tests/fortran2003/test_intrinsics.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2019-2021, Science and Technology Facilities Council.
+# Copyright (c) 2019-2022, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -105,18 +105,26 @@ def test_intrinsic_name_case_insensitive(f2003_create):
# class intrinsic_function_reference
[email protected]("fake_symbol_table")
-def test_intrinsic_function_reference_generic(f2003_create):
[email protected]("f2003_create")
+def test_intrinsic_function_reference_generic():
'''Test that class Intrinsic_Function_Reference correctly matches a
- generic intrinsic with a valid number of arguments.
+ generic intrinsic with a valid number of arguments. We test both
+ with and without the existance of a symbol table.
'''
result = Intrinsic_Function_Reference("SIN(A)")
assert isinstance(result, Intrinsic_Function_Reference)
assert str(result) == "SIN(A)"
+ # Repeat when there is a scoping region.
+ SYMBOL_TABLES.enter_scope("test_scope")
+ result = Intrinsic_Function_Reference("SIN(A)")
+ assert isinstance(result, Intrinsic_Function_Reference)
+ assert str(result) == "SIN(A)"
+ table = SYMBOL_TABLES.current_scope
+ assert "sin" not in table._data_symbols
+ SYMBOL_TABLES.exit_scope()
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference(f2003_create):
'''Test that class Intrinsic_Function_Reference correctly matches a
specific intrinsic with a valid number of arguments.
@@ -127,7 +135,6 @@ def test_intrinsic_function_reference(f2003_create):
assert str(result) == "DSIN(A)"
[email protected]("fake_symbol_table")
def test_intrinsic_function_nomatch(f2003_create):
'''Test that class Intrinsic_Function_Reference raises the expected
exception if there is no match.
@@ -137,7 +144,6 @@ def test_intrinsic_function_nomatch(f2003_create):
_ = Intrinsic_Function_Reference("NO_MATCH(A)")
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_multi_args(f2003_create):
'''Test that class Intrinsic_Function_Reference correctly matches a
generic intrinsic which accepts more than one argument (two in
@@ -149,7 +155,6 @@ def test_intrinsic_function_reference_multi_args(f2003_create):
assert str(result) == "MATMUL(A, B)"
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_zero_args(f2003_create):
'''Test that class Intrinsic_Function_Reference correctly matches a
generic intrinsic which accepts zero arguments.
@@ -160,7 +165,6 @@ def test_intrinsic_function_reference_zero_args(f2003_create):
assert str(result) == "COMMAND_ARGUMENT_COUNT()"
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_range_args(f2003_create):
'''Test that class Intrinsic_Function_Reference correctly matches a
generic intrinsic which accepts a range of number of arguments.
@@ -172,7 +176,6 @@ def test_intrinsic_function_reference_range_args(f2003_create):
assert str(result) == "SYSTEM_CLOCK({0})".format(args)
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_unlimited_args(f2003_create):
'''Test that class Intrinsic_Function_Reference correctly matches a
generic intrinsic which accepts an unlimitednumber of arguments.
@@ -184,7 +187,6 @@ def test_intrinsic_function_reference_unlimited_args(f2003_create):
assert str(result) == "MAX({0})".format(args)
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_error1(f2003_create):
'''Test that class Intrinsic_Function_Reference raises the expected
exception when the valid min and max args are equal (2 in this case)
@@ -202,7 +204,6 @@ def test_intrinsic_function_reference_error1(f2003_create):
"" in str(excinfo.value))
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_error2(f2003_create):
'''Test that class Intrinsic_Function_Reference raises the expected
exception when the valid min args is less than the valid max args
@@ -220,7 +221,6 @@ def test_intrinsic_function_reference_error2(f2003_create):
"" in str(excinfo.value))
[email protected]("fake_symbol_table")
def test_intrinsic_function_reference_error3(f2003_create):
'''Test that class Intrinsic_Function_Reference raises the expected
exception when the number of arguments is unlimited.
diff --git a/src/fparser/two/tests/fortran2003/test_type_decl_stmt_r501.py b/src/fparser/two/tests/fortran2003/test_type_decl_stmt_r501.py
new file mode 100644
index 0000000..9de7c08
--- /dev/null
+++ b/src/fparser/two/tests/fortran2003/test_type_decl_stmt_r501.py
@@ -0,0 +1,116 @@
+# Copyright (c) 2022 Science and Technology Facilities Council.
+
+# All rights reserved.
+
+# Modifications made as part of the fparser project are distributed
+# under the following license:
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+
+# 3. Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+'''
+pytest tests for Fortran2003 rule R501 - Type Declaration Statement.
+
+TODO #318 - these tests need extending to fully cover the
+Fortran2003.Type_Declaration_Stmtclass. They will also need to be
+extended as part of #259 as that will add support for the various
+constraints that apply to R501.
+
+'''
+
+import pytest
+from fparser.two import Fortran2003
+from fparser.two.symbol_table import SYMBOL_TABLES
+
+
[email protected]("f2003_create")
[email protected]("table_name", ["", "test_mod"])
+def test_type_declaration_stmt(table_name):
+ ''' Various tests for the type declaration statement (R501). We test both
+ with and without an existing scoping region. '''
+ if table_name:
+ SYMBOL_TABLES.enter_scope(table_name)
+ table = SYMBOL_TABLES.current_scope
+
+ tcls = Fortran2003.Type_Declaration_Stmt
+ obj = tcls('integer a')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'INTEGER :: a'
+ assert (repr(obj) ==
+ "Type_Declaration_Stmt(Intrinsic_Type_Spec('INTEGER', "
+ "None), None, Entity_Decl_List(',', (Entity_Decl(Name('a'), None, "
+ "None, None),)))")
+ if table:
+ assert "a" in table._data_symbols
+
+ obj = tcls('integer ,dimension(2):: b*3')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'INTEGER, DIMENSION(2) :: b*3'
+ if table:
+ assert "b" in table._data_symbols
+
+ obj = tcls('real c')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'REAL :: c'
+ assert (repr(obj) ==
+ "Type_Declaration_Stmt(Intrinsic_Type_Spec('REAL', None), None, "
+ "Entity_Decl_List(',', (Entity_Decl(Name('c'), None, None, "
+ "None),)))")
+ if table:
+ assert "c" in table._data_symbols
+
+ obj = tcls('REAL D( LDA, * ), E( LDB, * )')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'REAL :: D(LDA, *), E(LDB, *)'
+ if table:
+ assert "d" in table._data_symbols
+ assert "e" in table._data_symbols
+
+ obj = tcls('DOUBLE PRECISION ALPHA, BETA')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'DOUBLE PRECISION :: ALPHA, BETA'
+ if table:
+ assert "alpha" in table._data_symbols
+ assert "beta" in table._data_symbols
+
+ obj = tcls('logical,parameter:: T=.true.')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'LOGICAL, PARAMETER :: T = .TRUE.'
+ if table:
+ assert "t" in table._data_symbols
+
+ obj = tcls('character(n),private:: x(n)')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'CHARACTER(LEN = n), PRIVATE :: x(n)'
+ if table:
+ assert "x" in table._data_symbols
+
+ obj = tcls('character(lenmax),private:: y(n)')
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == 'CHARACTER(LEN = lenmax), PRIVATE :: y(n)'
+ if table:
+ assert "y" in table._data_symbols
diff --git a/src/fparser/two/tests/fortran2003/test_usestmt_r1109.py b/src/fparser/two/tests/fortran2003/test_usestmt_r1109.py
index 52ceba6..8c841a2 100644
--- a/src/fparser/two/tests/fortran2003/test_usestmt_r1109.py
+++ b/src/fparser/two/tests/fortran2003/test_usestmt_r1109.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2018-2021 Science and Technology Facilities Council
+# Copyright (c) 2018-2022 Science and Technology Facilities Council.
# All rights reserved.
@@ -40,6 +40,7 @@ Use statement.
import pytest
from fparser.api import get_reader
from fparser.two.Fortran2003 import Use_Stmt
+from fparser.two.symbol_table import SYMBOL_TABLES
from fparser.two.utils import NoMatchError, InternalError
# match() use ...
@@ -48,7 +49,6 @@ from fparser.two.utils import NoMatchError, InternalError
# match() 'use x'. Use both string and reader input here, but from
# here on we will just use string input as that is what is passed to
# the match() method
[email protected]("fake_symbol_table")
def test_use(f2003_create):
'''Check that a basic use is parsed correctly. Input separately as a
string and as a reader object
@@ -67,7 +67,6 @@ def test_use(f2003_create):
# match() 'use :: x'
[email protected]("fake_symbol_table")
def test_use_colons(f2003_create):
'''Check that a basic use with '::' is parsed correctly.'''
line = "use :: my_model"
@@ -77,7 +76,6 @@ def test_use_colons(f2003_create):
# match() 'use, nature :: x'
[email protected]("fake_symbol_table")
def test_use_nature(f2003_create):
'''Check that a use with a 'nature' specification is parsed correctly.'''
line = "use, intrinsic :: my_model"
@@ -89,7 +87,6 @@ def test_use_nature(f2003_create):
# match() 'use x, rename'
[email protected]("fake_symbol_table")
def test_use_rename(f2003_create):
'''Check that a use with a nename clause is parsed correctly.'''
line = "use my_module, name=>new_name"
@@ -101,10 +98,9 @@ def test_use_rename(f2003_create):
# match() 'use x, only: y'
[email protected]("fake_symbol_table")
def test_use_only(f2003_create):
'''Check that a use statement is parsed correctly when there is an
- only clause.
+ only clause. Test both with and without a scoping region.
'''
line = "use my_model, only: name"
@@ -113,10 +109,16 @@ def test_use_only(f2003_create):
assert repr(ast) == (
"Use_Stmt(None, None, Name('my_model'), ', ONLY:', Only_List(',', "
"(Name('name'),)))")
+ # Repeat when there is a scoping region.
+ SYMBOL_TABLES.enter_scope("test_scope")
+ ast = Use_Stmt(line)
+ table = SYMBOL_TABLES.current_scope
+ assert "my_model" in table._modules
+ assert table._modules["my_model"] == ["name"]
+ SYMBOL_TABLES.exit_scope()
# match() 'use x, only:'
[email protected]("fake_symbol_table")
def test_use_only_empty(f2003_create):
'''Check that a use statement is parsed correctly when there is an
only clause without any content.
@@ -130,7 +132,6 @@ def test_use_only_empty(f2003_create):
# match() ' use , nature :: x , name=>new_name'
[email protected]("fake_symbol_table")
def test_use_spaces_1(f2003_create):
'''Check that a use statement with spaces works correctly with
renaming.
@@ -145,7 +146,6 @@ def test_use_spaces_1(f2003_create):
# match() ' use , nature :: x , only : name'
[email protected]("fake_symbol_table")
def test_use_spaces_2(f2003_create):
'''Check that a use statement with spaces works correctly with an only
clause.
@@ -160,7 +160,6 @@ def test_use_spaces_2(f2003_create):
# match() mixed case
[email protected]("fake_symbol_table")
def test_use_mixed_case(f2003_create):
'''Check that a use statement with mixed case keywords ('use' and
'only') works as expected.
@@ -190,7 +189,6 @@ def test_syntaxerror(f2003_create):
# match() Internal errors
[email protected]("fake_symbol_table")
def test_use_internal_error1(f2003_create):
'''Check that an internal error is raised if the length of the Items
list is not 5 as the str() method assumes that it is.
@@ -204,7 +202,6 @@ def test_use_internal_error1(f2003_create):
assert "should be of size 5 but found '4'" in str(excinfo.value)
[email protected]("fake_symbol_table")
def test_use_internal_error2(f2003_create):
'''Check that an internal error is raised if the module name (entry 2
of Items) is empty or None as the str() method assumes that it is
@@ -221,7 +218,6 @@ def test_use_internal_error2(f2003_create):
"empty") in str(excinfo.value)
[email protected]("fake_symbol_table")
def test_use_internal_error3(f2003_create):
'''Check that an internal error is raised if entry 3 of Items is
'None' as the str() method assumes it is a (potentially empty)
diff --git a/src/fparser/two/tests/test_fortran2003.py b/src/fparser/two/tests/test_fortran2003.py
index 90b3f1b..839f18a 100644
--- a/src/fparser/two/tests/test_fortran2003.py
+++ b/src/fparser/two/tests/test_fortran2003.py
@@ -1,4 +1,4 @@
-# Modified work Copyright (c) 2017-2021 Science and Technology
+# Modified work Copyright (c) 2017-2022 Science and Technology
# Facilities Council.
# Original work Copyright (c) 1999-2008 Pearu Peterson
#
@@ -125,7 +125,6 @@ def _repr_utf(anobj):
#
[email protected]("fake_symbol_table")
def test_specification_part():
''' Tests for parsing specification-part (R204). '''
reader = get_reader('''\
@@ -981,51 +980,6 @@ def test_ac_implied_do_control(): # R471
#
[email protected]("fake_symbol_table")
-def test_type_declaration_stmt():
- ''' Various tests for the type declaration statement (R501). '''
- tcls = Type_Declaration_Stmt
- obj = tcls('integer a')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'INTEGER :: a'
- assert (_repr_utf(obj) ==
- "Type_Declaration_Stmt(Intrinsic_Type_Spec('INTEGER', "
- "None), None, Entity_Decl_List(',', (Entity_Decl(Name('a'), None, "
- "None, None),)))")
-
- obj = tcls('integer ,dimension(2):: b*3')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'INTEGER, DIMENSION(2) :: b*3'
-
- obj = tcls('real c')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'REAL :: c'
- assert (_repr_utf(obj) ==
- "Type_Declaration_Stmt(Intrinsic_Type_Spec('REAL', None), None, "
- "Entity_Decl_List(',', (Entity_Decl(Name('c'), None, None, "
- "None),)))")
-
- obj = tcls('REAL D( LDA, * ), E( LDB, * )')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'REAL :: D(LDA, *), E(LDB, *)'
-
- obj = tcls('DOUBLE PRECISION ALPHA, BETA')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'DOUBLE PRECISION :: ALPHA, BETA'
-
- obj = tcls('logical,parameter:: T=.true.')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'LOGICAL, PARAMETER :: T = .TRUE.'
-
- obj = tcls('character(n),private:: x(n)')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'CHARACTER(LEN = n), PRIVATE :: x(n)'
-
- obj = tcls('character(lenmax),private:: y(n)')
- assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'CHARACTER(LEN = lenmax), PRIVATE :: y(n)'
-
-
def test_declaration_type_spec(): # R502
tcls = Declaration_Type_Spec
|
Allow for matching of isolated code fragments (i.e. with no associated scoping region)
Testing PSyclone with master of fparser has revealed that the new symbol-table functionality causes problems - whenever fparser is used to parse just a fragment (e.g. by calling `match` directly) then there is no associated scoping region and `SYMBOL_TABLES.current_scope` (correctly) returns None. We just need to allow for this in the three places where `current_scope` is used.
|
0.0
|
e0b14f895f70a368ec83acc9adbb6fe17080392e
|
[
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_generic",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_multi_args",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_zero_args",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_range_args",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_unlimited_args",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_error1",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_error2",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_reference_error3",
"src/fparser/two/tests/fortran2003/test_type_decl_stmt_r501.py::test_type_declaration_stmt[]",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_colons",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_nature",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_rename",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_only",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_only_empty",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_spaces_1",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_spaces_2",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_mixed_case",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_internal_error1",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_internal_error2",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_use_internal_error3",
"src/fparser/two/tests/test_fortran2003.py::test_specification_part"
] |
[
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_recognised",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_error",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_name_generic",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_name_specific",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_name_invalid",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_name_case_insensitive",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_function_nomatch",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_intrinsic_inside_intrinsic",
"src/fparser/two/tests/fortran2003/test_intrinsics.py::test_shadowed_intrinsic",
"src/fparser/two/tests/fortran2003/test_type_decl_stmt_r501.py::test_type_declaration_stmt[test_mod]",
"src/fparser/two/tests/fortran2003/test_usestmt_r1109.py::test_syntaxerror",
"src/fparser/two/tests/test_fortran2003.py::test_constant",
"src/fparser/two/tests/test_fortran2003.py::test_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_value",
"src/fparser/two/tests/test_fortran2003.py::test_intrinsic_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_signed_int_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_int_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_binary_constant",
"src/fparser/two/tests/test_fortran2003.py::test_octal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_hex_constant",
"src/fparser/two/tests/test_fortran2003.py::test_signed_real_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_real_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_char_selector",
"src/fparser/two/tests/test_fortran2003.py::test_complex_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_name",
"src/fparser/two/tests/test_fortran2003.py::test_length_selector",
"src/fparser/two/tests/test_fortran2003.py::test_char_length",
"src/fparser/two/tests/test_fortran2003.py::test_logical_literal_constant",
"src/fparser/two/tests/test_fortran2003.py::test_type_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_end_type_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_sequence_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_decl",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_decl",
"src/fparser/two/tests/test_fortran2003.py::test_proc_component_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_private_components_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_bound_procedure_part",
"src/fparser/two/tests/test_fortran2003.py::test_proc_binding_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_generic_binding",
"src/fparser/two/tests/test_fortran2003.py::test_final_binding",
"src/fparser/two/tests/test_fortran2003.py::test_derived_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_spec",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_structure_constructor",
"src/fparser/two/tests/test_fortran2003.py::test_component_spec",
"src/fparser/two/tests/test_fortran2003.py::test_component_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_enum_def",
"src/fparser/two/tests/test_fortran2003.py::test_enum_def_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_array_constructor",
"src/fparser/two/tests/test_fortran2003.py::test_ac_spec",
"src/fparser/two/tests/test_fortran2003.py::test_ac_value_list",
"src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do_control",
"src/fparser/two/tests/test_fortran2003.py::test_declaration_type_spec",
"src/fparser/two/tests/test_fortran2003.py::test_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_dimension_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_intent_attr_spec",
"src/fparser/two/tests/test_fortran2003.py::test_entity_decl",
"src/fparser/two/tests/test_fortran2003.py::test_target_entity_decl",
"src/fparser/two/tests/test_fortran2003.py::test_access_spec",
"src/fparser/two/tests/test_fortran2003.py::test_language_binding_spec",
"src/fparser/two/tests/test_fortran2003.py::test_explicit_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_upper_bound",
"src/fparser/two/tests/test_fortran2003.py::test_assumed_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_deferred_shape_spec",
"src/fparser/two/tests/test_fortran2003.py::test_assumed_size_spec",
"src/fparser/two/tests/test_fortran2003.py::test_access_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_data_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_data_stmt_set",
"src/fparser/two/tests/test_fortran2003.py::test_data_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_dimension_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_intent_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_optional_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_parameter_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_named_constant_def",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_decl",
"src/fparser/two/tests/test_fortran2003.py::test_protected_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_save_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_saved_entity",
"src/fparser/two/tests/test_fortran2003.py::test_target_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_value_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_volatile_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_implicit_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_implicit_spec",
"src/fparser/two/tests/test_fortran2003.py::test_letter_spec",
"src/fparser/two/tests/test_fortran2003.py::test_namelist_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_equivalence_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_common_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_common_block_object",
"src/fparser/two/tests/test_fortran2003.py::test_substring",
"src/fparser/two/tests/test_fortran2003.py::test_substring_range",
"src/fparser/two/tests/test_fortran2003.py::test_part_ref",
"src/fparser/two/tests/test_fortran2003.py::test_type_param_inquiry",
"src/fparser/two/tests/test_fortran2003.py::test_array_section",
"src/fparser/two/tests/test_fortran2003.py::test_section_subscript",
"src/fparser/two/tests/test_fortran2003.py::test_section_subscript_list",
"src/fparser/two/tests/test_fortran2003.py::test_subscript_triplet",
"src/fparser/two/tests/test_fortran2003.py::test_allocate_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_alloc_opt",
"src/fparser/two/tests/test_fortran2003.py::test_nullify_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_deallocate_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_level_1_expr",
"src/fparser/two/tests/test_fortran2003.py::test_mult_operand",
"src/fparser/two/tests/test_fortran2003.py::test_level_2_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_2_unary_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_3_expr",
"src/fparser/two/tests/test_fortran2003.py::test_level_4_expr",
"src/fparser/two/tests/test_fortran2003.py::test_and_operand",
"src/fparser/two/tests/test_fortran2003.py::test_or_operand",
"src/fparser/two/tests/test_fortran2003.py::test_equiv_operand",
"src/fparser/two/tests/test_fortran2003.py::test_level_5_expr",
"src/fparser/two/tests/test_fortran2003.py::test_expr",
"src/fparser/two/tests/test_fortran2003.py::test_logical_initialization_expr",
"src/fparser/two/tests/test_fortran2003.py::test_assignment_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_pointer_assignment_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_proc_component_ref",
"src/fparser/two/tests/test_fortran2003.py::test_where_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_where_construct_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_forall_construct",
"src/fparser/two/tests/test_fortran2003.py::test_forall_triplet_spec",
"src/fparser/two/tests/test_fortran2003.py::test_if_nonblock_do",
"src/fparser/two/tests/test_fortran2003.py::test_case_selector",
"src/fparser/two/tests/test_fortran2003.py::test_associate_construct",
"src/fparser/two/tests/test_fortran2003.py::test_select_type_construct",
"src/fparser/two/tests/test_fortran2003.py::test_select_type_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_type_guard_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_label_do_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_loop_control",
"src/fparser/two/tests/test_fortran2003.py::test_continue_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_stop_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_io_unit",
"src/fparser/two/tests/test_fortran2003.py::test_read_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_print_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_format",
"src/fparser/two/tests/test_fortran2003.py::test_io_implied_do",
"src/fparser/two/tests/test_fortran2003.py::test_io_implied_do_control",
"src/fparser/two/tests/test_fortran2003.py::test_wait_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_wait_spec",
"src/fparser/two/tests/test_fortran2003.py::test_backspace_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_endfile_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_rewind_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_position_spec",
"src/fparser/two/tests/test_fortran2003.py::test_flush_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_flush_spec",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_spec",
"src/fparser/two/tests/test_fortran2003.py::test_inquire_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_open_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_connect_spec",
"src/fparser/two/tests/test_fortran2003.py::test_connect_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_format_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_format_specification",
"src/fparser/two/tests/test_fortran2003.py::test_format_item",
"src/fparser/two/tests/test_fortran2003.py::test_data_edit_desc",
"src/fparser/two/tests/test_fortran2003.py::test_format_item_list",
"src/fparser/two/tests/test_fortran2003.py::test_main_program0",
"src/fparser/two/tests/test_fortran2003.py::test_invalid_main_program0",
"src/fparser/two/tests/test_fortran2003.py::test_module",
"src/fparser/two/tests/test_fortran2003.py::test_module_subprogram_part",
"src/fparser/two/tests/test_fortran2003.py::test_module_nature",
"src/fparser/two/tests/test_fortran2003.py::test_rename",
"src/fparser/two/tests/test_fortran2003.py::test_interface_block",
"src/fparser/two/tests/test_fortran2003.py::test_interface_specification",
"src/fparser/two/tests/test_fortran2003.py::test_interface_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_end_interface_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_interface_body",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_body",
"src/fparser/two/tests/test_fortran2003.py::test_function_body",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_generic_spec",
"src/fparser/two/tests/test_fortran2003.py::test_dtio_generic_spec",
"src/fparser/two/tests/test_fortran2003.py::test_import_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_external_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_declaration_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[private-Access_Spec-PRIVATE]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[public-Access_Spec-PUBLIC]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c)-Language_Binding_Spec-BIND(C)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c,",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(in)-Proc_Attr_Spec-INTENT(IN)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(out)-Proc_Attr_Spec-INTENT(OUT)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(inout)-Proc_Attr_Spec-INTENT(INOUT)]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[optional-Proc_Attr_Spec-OPTIONAL]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[pointer-Proc_Attr_Spec-POINTER]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[protected-Proc_Attr_Spec-PROTECTED]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[save-Proc_Attr_Spec-SAVE]",
"src/fparser/two/tests/test_fortran2003.py::test_proc_decl",
"src/fparser/two/tests/test_fortran2003.py::test_intrinsic_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_function_reference",
"src/fparser/two/tests/test_fortran2003.py::test_call_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_procedure_designator",
"src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec",
"src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec_list",
"src/fparser/two/tests/test_fortran2003.py::test_alt_return_spec",
"src/fparser/two/tests/test_fortran2003.py::test_function_subprogram",
"src/fparser/two/tests/test_fortran2003.py::test_function_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_dummy_arg_name",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer-Intrinsic_Type_Spec-INTEGER]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[real-Intrinsic_Type_Spec-REAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[double",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[complex-Intrinsic_Type_Spec-COMPLEX]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[character-Intrinsic_Type_Spec-CHARACTER]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[logical-Intrinsic_Type_Spec-LOGICAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[type(foo)-Declaration_Type_Spec-TYPE(foo)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(bar)-Declaration_Type_Spec-CLASS(bar)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(*)-Declaration_Type_Spec-CLASS(*)]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[elemental-Prefix_Spec-ELEMENTAL]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[impure-Prefix_Spec-IMPURE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[module-Prefix_Spec-MODULE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[pure-Prefix_Spec-PURE]",
"src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[recursive-Prefix_Spec-RECURSIVE]",
"src/fparser/two/tests/test_fortran2003.py::test_suffix",
"src/fparser/two/tests/test_fortran2003.py::test_end_function_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_subprogram",
"src/fparser/two/tests/test_fortran2003.py::test_subroutine_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_dummy_arg",
"src/fparser/two/tests/test_fortran2003.py::test_end_subroutine_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_entry_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_return_stmt",
"src/fparser/two/tests/test_fortran2003.py::test_contains"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-08 16:47:00+00:00
|
bsd-3-clause
| 5,730 |
|
stfc__fparser-317
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26cb232..fdd5c20 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,9 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
+23/03/2022 PR #317 for #316. Fixes the creation of symbol table entries
+ in the F2008 parser.
+
21/03/2022 PR #315 for #314. Adds support for the F2008 Error_Stop_Stmt.
## Release 0.0.14 (16/03/2022) ##
diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py
index 5ebe5d9..36af7ac 100644
--- a/src/fparser/two/Fortran2003.py
+++ b/src/fparser/two/Fortran2003.py
@@ -2664,21 +2664,30 @@ class Type_Declaration_Stmt(Type_Declaration_StmtBase): # R501
use_names = ['Declaration_Type_Spec', 'Attr_Spec_List', 'Entity_Decl_List']
@staticmethod
- def match(string):
+ def get_attr_spec_list_cls():
+ '''Return the type used to match the attr-spec-list
+
+ This method allows to overwrite the type used in :py:meth:`match`
+ in derived classes
+ (e.g., :py:class:`fparser.two.Fortran2008.Type_Declaration_Stmt`).
+
+ This cannot be implemented as an attribute because the relevant type
+ :class:`Attr_Spec_List` is auto-generated at the end of the file
+ using the :attr:`use_names` property of the class.
+
'''
- Attempts to match the supplied string as a type declaration. If the
- match is successful the declared symbols are added to the symbol table
- of the current scope (if there is one).
+ return Attr_Spec_List
- :param str string: the string to match.
+ @staticmethod
+ def add_to_symbol_table(result):
+ '''Capture the declared symbols in the symbol table of the current
+ scoping region
- :returns: 3-tuple containing the matched declaration.
- :rtype: (Declaration_Type_Spec, Attr_Spec_List or NoneType, \
+ :param result: the declared type, attributes and entities or None
+ :type result: `NoneType` or \
+ (Declaration_Type_Spec, Attr_Spec_List or NoneType, \
Entity_Decl_List)
-
'''
- result = Type_Declaration_StmtBase.match(
- Declaration_Type_Spec, Attr_Spec_List, Entity_Decl_List, string)
if result:
# We matched a declaration - capture the declared symbols in the
# symbol table of the current scoping region.
@@ -2692,6 +2701,28 @@ class Type_Declaration_Stmt(Type_Declaration_StmtBase): # R501
# type rather than a string.
table.add_data_symbol(decl.items[0].string, str(result[0]))
# TODO #201 support symbols that are not of intrinsic type.
+
+ @classmethod
+ def match(cls, string):
+ '''
+ Attempts to match the supplied string as a type declaration. If the
+ match is successful the declared symbols are added to the symbol table
+ of the current scope (if there is one).
+
+ Note that this is implemented as a class method to allow parameterizing
+ the type used to match attr-spec-list via :py:meth:`get_attr_spec_list_cls`.
+
+ :param str string: the string to match.
+
+ :returns: 3-tuple containing the matched declaration.
+ :rtype: (Declaration_Type_Spec, Attr_Spec_List or NoneType, \
+ Entity_Decl_List)
+
+ '''
+ result = Type_Declaration_StmtBase.match(
+ Declaration_Type_Spec, cls.get_attr_spec_list_cls(), Entity_Decl_List,
+ string)
+ cls.add_to_symbol_table(result)
return result
@staticmethod
diff --git a/src/fparser/two/Fortran2008.py b/src/fparser/two/Fortran2008.py
index 4792876..2aeb8cb 100644
--- a/src/fparser/two/Fortran2008.py
+++ b/src/fparser/two/Fortran2008.py
@@ -356,11 +356,8 @@ class Type_Declaration_Stmt(Type_Declaration_Stmt_2003): # R501
entity-decl-list
The implementation of this rule does not add anything to the Fortran 2003
- variant but reimplements the match method identical to Fortran 2003 as
- otherwise the generated Fortran 2008 variant of `Attr_Spec_List` would not
- be used. Unfortunately, the required `attr_spec_list_cls` can not simply be
- provided as a class property since the relevant class is only generated
- at the end of this file using the `use_names` class property of this class.
+ variant but overwrites :py:meth:`get_attr_spec_list_cls` to use
+ the Fortran 2008 variant of :py:class:`Attr_Spec_List`.
Associated constraints are:
@@ -378,23 +375,13 @@ class Type_Declaration_Stmt(Type_Declaration_Stmt_2003): # R501
'''
@staticmethod
- def match(string):
- '''Implements the matching of a type declaration statement.
+ def get_attr_spec_list_cls():
+ '''Return the type used to match the attr-spec-list
- :param str string: the reader or string to match as a type \
- declaration statement.
-
- :return: a 3-tuple containing declaration type specification, \
- attributespecification and entity declaration list \
- if there is a match or None if there is no match.
- :rtype: `NoneType` or \
- (:py:class:`fparser.two.Fortran2003.Declaration_Type_Spec`, \
- :py:class:`fparser.two.Fortran2008.Attr_Spec_List`, \
- :py:class:`fparser.two.Fortran2003.Entity_Decl_List`)
+ This overwrites the Fortran 2003 type with the Fortran 2008 variant.
'''
- return Type_Declaration_StmtBase.match(
- Declaration_Type_Spec, Attr_Spec_List, Entity_Decl_List, string)
+ return Attr_Spec_List
class Codimension_Attr_Spec(WORDClsBase): # R502.d
|
stfc/fparser
|
f4cd27e620ea2a927ea309a1e20fdc0aa3f5f4a4
|
diff --git a/src/fparser/two/tests/fortran2008/test_type_declaration_stmt_r501.py b/src/fparser/two/tests/fortran2008/test_type_declaration_stmt_r501.py
index bbaa2f9..17b5cff 100644
--- a/src/fparser/two/tests/fortran2008/test_type_declaration_stmt_r501.py
+++ b/src/fparser/two/tests/fortran2008/test_type_declaration_stmt_r501.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2020 Science and Technology Facilities Council
+# Copyright (c) 2020-2022 Science and Technology Facilities Council.
# All rights reserved.
@@ -39,9 +39,15 @@
'''
+import pytest
+from fparser.two.Fortran2003 import Intrinsic_Function_Reference
from fparser.two.Fortran2008 import Type_Declaration_Stmt
+from fparser.two.symbol_table import SYMBOL_TABLES
+from fparser.two.utils import walk
+from fparser.api import get_reader
[email protected]("fake_symbol_table")
def test_type_declaration_stmt(): # R501
'''
Tests copied from Fortran 2003.
@@ -56,21 +62,21 @@ def test_type_declaration_stmt(): # R501
"None), None, Entity_Decl_List(',', (Entity_Decl(Name('a'), None, "
"None, None),)))")
- obj = tcls('integer ,dimension(2):: a*3')
+ obj = tcls('integer ,dimension(2):: b*3')
assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'INTEGER, DIMENSION(2) :: a*3'
+ assert str(obj) == 'INTEGER, DIMENSION(2) :: b*3'
- obj = tcls('real a')
+ obj = tcls('real c')
assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'REAL :: a'
+ assert str(obj) == 'REAL :: c'
assert (repr(obj) ==
"Type_Declaration_Stmt(Intrinsic_Type_Spec('REAL', None), None, "
- "Entity_Decl_List(',', (Entity_Decl(Name('a'), None, None, "
+ "Entity_Decl_List(',', (Entity_Decl(Name('c'), None, None, "
"None),)))")
- obj = tcls('REAL A( LDA, * ), B( LDB, * )')
+ obj = tcls('REAL D( LDA, * ), E( LDB, * )')
assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'REAL :: A(LDA, *), B(LDB, *)'
+ assert str(obj) == 'REAL :: D(LDA, *), E(LDB, *)'
obj = tcls('DOUBLE PRECISION ALPHA, BETA')
assert isinstance(obj, tcls), repr(obj)
@@ -84,6 +90,28 @@ def test_type_declaration_stmt(): # R501
assert isinstance(obj, tcls), repr(obj)
assert str(obj) == 'CHARACTER(LEN = n), PRIVATE :: x(n)'
- obj = tcls('character(lenmax),private:: x(n)')
+ obj = tcls('character(lenmax),private:: y(n)')
assert isinstance(obj, tcls), repr(obj)
- assert str(obj) == 'CHARACTER(LEN = lenmax), PRIVATE :: x(n)'
+ assert str(obj) == 'CHARACTER(LEN = lenmax), PRIVATE :: y(n)'
+
+
+def test_shadowed_intrinsic(f2008_parser):
+ ''' Check that a locally-defined symbol that shadows (overwrites) a
+ Fortran intrinsic is correctly identified. '''
+ tree = f2008_parser(get_reader('''\
+module my_mod
+ use some_mod
+ real :: dot_product(2,2)
+contains
+ subroutine my_sub()
+ real :: result
+ result = dot_product(1,1)
+ end subroutine my_sub
+end module my_mod
+ '''))
+ tables = SYMBOL_TABLES
+ # We should not have an intrinsic-function reference in the parse tree
+ assert not walk(tree, Intrinsic_Function_Reference)
+ table = tables.lookup("my_mod")
+ sym = table.children[0].lookup("dot_product")
+ assert sym.primitive_type == "real"
|
Shadowed intrinsics fail in F2008 mode
The fantastic new symbol table (many, many thanks!) resolves the problem with local declarations shadowing intrinsics. However, this seems to only work in f2003 mode and the problem persists in f2008 mode. Unfortunately, it's unclear to me what is the reason for this.
To reproduce:
1) Duplicate `test_intrinsics.py` using `f2008_create`/`f2008_parser` fixtures makes `test_shadowed_intrinsic` fail.
2) For a full example, you can use [ecrad](https://github.com/ecmwf-ifs/ecrad/blob/0fb57d1a3c0b623a83e1b73b04cc73f5374c9e6c/ifsrrtm/srtm_spcvrt_mcica.F90#L256) (requires commenting the optimization pragma on l.2):
```
> fparser2 ecrad/master/ifsrrtm/srtm_spcvrt_mcica.F90
... parses without problems ...
> fparser2 --std=f2008 ecrad/master/ifsrrtm/srtm_spcvrt_mcica.F90
Syntax error: at line 256
>>> JL=INDEX(IC)
Intrinsic 'INDEX' expects between 2 and 4 args but found 1.
```
|
0.0
|
f4cd27e620ea2a927ea309a1e20fdc0aa3f5f4a4
|
[
"src/fparser/two/tests/fortran2008/test_type_declaration_stmt_r501.py::test_shadowed_intrinsic"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-10 17:50:52+00:00
|
bsd-3-clause
| 5,731 |
|
stfc__fparser-351
|
diff --git a/src/fparser/two/symbol_table.py b/src/fparser/two/symbol_table.py
index a0d6876..c7de860 100644
--- a/src/fparser/two/symbol_table.py
+++ b/src/fparser/two/symbol_table.py
@@ -1,7 +1,7 @@
# -----------------------------------------------------------------------------
# BSD 3-Clause License
#
-# Copyright (c) 2021, Science and Technology Facilities Council.
+# Copyright (c) 2021-2022, Science and Technology Facilities Council.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -59,6 +59,9 @@ class SymbolTables():
self._scoping_unit_classes = []
# The symbol table of the current scope
self._current_scope = None
+ # Whether or not we enable consistency checks in the symbol tables
+ # that are created.
+ self._enable_checks = False
def __str__(self):
result = ("SymbolTables: {0} tables\n"
@@ -66,6 +69,16 @@ class SymbolTables():
len(self._symbol_tables)))
return result + "\n".join(sorted(self._symbol_tables.keys()))
+ def enable_checks(self, value):
+ '''
+ Sets whether or not to enable consistency checks in every symbol
+ table that is created during a parse.
+
+ :param bool value: whether or not checks are enabled.
+
+ '''
+ self._enable_checks = value
+
def clear(self):
'''
Deletes any stored SymbolTables but retains the stored list of
@@ -93,7 +106,7 @@ class SymbolTables():
raise SymbolTableError(
"The table of top-level (un-nested) symbol tables already "
"contains an entry for '{0}'".format(lower_name))
- table = SymbolTable(lower_name)
+ table = SymbolTable(lower_name, checking_enabled=self._enable_checks)
self._symbol_tables[lower_name] = table
return table
@@ -135,7 +148,7 @@ class SymbolTables():
if not isinstance(value, list):
raise TypeError("Supplied value must be a list but got '{0}'".
format(type(value).__name__))
- if not all([isinstance(item, type) for item in value]):
+ if not all(isinstance(item, type) for item in value):
raise TypeError("Supplied list must contain only classes but "
"got: {0}".format(value))
self._scoping_unit_classes = value
@@ -173,7 +186,8 @@ class SymbolTables():
else:
# We are already inside a scoping region so create a new table
# and setup its parent/child connections.
- table = SymbolTable(lname, parent=self._current_scope)
+ table = SymbolTable(lname, parent=self._current_scope,
+ checking_enabled=self._enable_checks)
self._current_scope.add_child(table)
# Finally, make this new table the current scope
@@ -242,10 +256,17 @@ class SymbolTable():
'''
Class implementing a single symbol table.
+ Since this functionality is not yet fully mature, checks that new symbols
+ don't clash with existing symbols are disabled by default.
+ Once #201 is complete it is planned to switch this so that the checks
+ are instead enabled by default.
+
:param str name: the name of this scope. Will be the name of the \
associated module or routine.
:param parent: the symbol table within which this one is nested (if any).
:type parent: :py:class:`fparser.two.symbol_table.SymbolTable.Symbol`
+ :param bool checking_enabled: whether or not validity checks are \
+ performed for symbols added to the table.
'''
# TODO #201 add support for other symbol properties (kind, shape
@@ -253,7 +274,7 @@ class SymbolTable():
# type checking for the various properties.
Symbol = namedtuple("Symbol", "name primitive_type")
- def __init__(self, name, parent=None):
+ def __init__(self, name, parent=None, checking_enabled=False):
self._name = name.lower()
# Symbols defined in this scope that represent data.
self._data_symbols = {}
@@ -263,6 +284,8 @@ class SymbolTable():
# value (if any) is set via setter method.
self._parent = None
self.parent = parent
+ # Whether or not to perform validity checks when symbols are added.
+ self._checking_enabled = checking_enabled
# Symbol tables nested within this one.
self._children = []
@@ -301,18 +324,23 @@ class SymbolTable():
raise TypeError(
"The primitive type of the symbol must be specified as a str "
"but got '{0}'".format(type(primitive_type).__name__))
+
lname = name.lower()
- if lname in self._data_symbols:
- raise SymbolTableError("Symbol table already contains a symbol for"
- " a variable with name '{0}'".format(name))
- if lname in self._modules:
- raise SymbolTableError("Symbol table already contains a use of a "
- "module with name '{0}'".format(name))
- for mod_name in self._modules:
- if self._modules[mod_name] and lname in self._modules[mod_name]:
+
+ if self._checking_enabled:
+ if lname in self._data_symbols:
+ raise SymbolTableError(
+ f"Symbol table already contains a symbol for"
+ f" a variable with name '{name}'")
+ if lname in self._modules:
raise SymbolTableError(
- "Symbol table already contains a use of a symbol named "
- "'{0}' from module '{1}'".format(name, mod_name))
+ f"Symbol table already contains a use of a "
+ f"module with name '{name}'")
+ for mod_name, var_list in self._modules.items():
+ if var_list and lname in var_list:
+ raise SymbolTableError(
+ f"Symbol table already contains a use of a symbol "
+ f"named '{name}' from module '{mod_name}'")
self._data_symbols[lname] = SymbolTable.Symbol(lname,
primitive_type.lower())
@@ -342,7 +370,7 @@ class SymbolTable():
raise TypeError("If present, the only_list must be a list but got "
"'{0}'".format(type(only_list).__name__))
if only_list and not all(
- [isinstance(item, str) for item in only_list]):
+ isinstance(item, str) for item in only_list):
raise TypeError("If present, the only_list must be a list of str "
"but got: {0}".format(
[type(item).__name__ for item in only_list]))
@@ -481,6 +509,7 @@ class SymbolTable():
current = current.parent
return current
+
#: The single, global container for all symbol tables constructed while
#: parsing.
SYMBOL_TABLES = SymbolTables()
|
stfc/fparser
|
ffee889cc3e646518f0bfdc422e0e74d924030ec
|
diff --git a/src/fparser/two/tests/test_symbol_table.py b/src/fparser/two/tests/test_symbol_table.py
index 879c6c0..06ef1d2 100644
--- a/src/fparser/two/tests/test_symbol_table.py
+++ b/src/fparser/two/tests/test_symbol_table.py
@@ -1,5 +1,5 @@
# -----------------------------------------------------------------------------
-# Copyright (c) 2021 Science and Technology Facilities Council
+# Copyright (c) 2021-2022 Science and Technology Facilities Council.
# All rights reserved.
#
# Modifications made as part of the fparser project are distributed
@@ -49,6 +49,8 @@ def test_basic_table():
assert table.name == "basic"
assert table.parent is None
assert table.children == []
+ # Consistency checking is disabled by default
+ assert table._checking_enabled is False
with pytest.raises(KeyError) as err:
table.lookup("missing")
assert "Failed to find symbol named 'missing'" in str(err.value)
@@ -57,11 +59,15 @@ def test_basic_table():
sym = table.lookup("var")
assert sym.name == "var"
assert table.lookup("VAR") is sym
+ # Check that we can enable consistency checking
+ table2 = SymbolTable("table2", checking_enabled=True)
+ assert table2._checking_enabled is True
def test_add_data_symbol():
- ''' Test that the add_data_symbol() method behaves as expected. '''
- table = SymbolTable("basic")
+ ''' Test that the add_data_symbol() method behaves as expected when
+ validation is enabled. '''
+ table = SymbolTable("basic", checking_enabled=True)
table.add_data_symbol("var", "integer")
sym = table.lookup("var")
assert sym.primitive_type == "integer"
@@ -90,6 +96,21 @@ def test_add_data_symbol():
"module 'mod1'" in str(err.value))
+def test_add_data_symbols_no_checks():
+ ''' Check that we can disable the checks in the
+ add_data_symbol() method. '''
+ table = SymbolTable("basic", checking_enabled=False)
+ table.add_data_symbol("var", "integer")
+ table.add_data_symbol("var", "real")
+ sym = table.lookup("var")
+ assert sym.primitive_type == "real"
+ table.add_use_symbols("mod1", ["var3"])
+ table.add_data_symbol("mod1", "real")
+ table.add_use_symbols("mod2", ["var3"])
+ table.add_data_symbol("var3", "real")
+ assert table.lookup("var3").primitive_type == "real"
+
+
def test_add_use_symbols():
''' Test that the add_use_symbols() method behaves as expected. '''
table = SymbolTable("basic")
diff --git a/src/fparser/two/tests/test_symbol_tables.py b/src/fparser/two/tests/test_symbol_tables.py
index c209ab4..e18f079 100644
--- a/src/fparser/two/tests/test_symbol_tables.py
+++ b/src/fparser/two/tests/test_symbol_tables.py
@@ -1,5 +1,5 @@
# -----------------------------------------------------------------------------
-# Copyright (c) 2021 Science and Technology Facilities Council
+# Copyright (c) 2021-2022 Science and Technology Facilities Council.
# All rights reserved.
#
# Modifications made as part of the fparser project are distributed
@@ -48,6 +48,7 @@ def test_construction_addition_removal():
tables = SymbolTables()
assert tables._current_scope is None
assert tables._symbol_tables == {}
+ assert tables._enable_checks is False
with pytest.raises(KeyError) as err:
tables.lookup("missing")
assert "missing" in str(err.value)
@@ -62,10 +63,16 @@ def test_construction_addition_removal():
"an entry for 'table1'" in str(err.value))
# Add a second table and then remove it
table2 = tables.add("taBLe2")
+ # Check that validation checks are disabled by default
+ assert table2._checking_enabled is False
assert tables.lookup("table2") is table2
tables.remove("table2")
with pytest.raises(KeyError) as err:
tables.lookup("table2")
+ # Turn on validation checking
+ tables.enable_checks(True)
+ table3 = tables.add("table3")
+ assert table3._checking_enabled is True
# Clear the stored symbol tables
tables.clear()
assert tables._current_scope is None
|
Allow symbol checks to be disabled
The new symbol table functionality is somewhat immature (it cannot cope with use association) and only works if the supplied source is valid Fortran, even if any pre-processor directives are ignored. These limitations mean that it can be tripped up in certain circumstances. While support for use association is planned (#201 and #349), there's no plan to handle CPP directives. Therefore we will allow the checking performed by the symbol table to be disabled at run time.
I'm not sure whether this will be best done by completely disabling the symbol table functionality or by only disabling the checks that a symbol does not already exist.
|
0.0
|
ffee889cc3e646518f0bfdc422e0e74d924030ec
|
[
"src/fparser/two/tests/test_symbol_table.py::test_basic_table",
"src/fparser/two/tests/test_symbol_table.py::test_add_data_symbol",
"src/fparser/two/tests/test_symbol_table.py::test_add_data_symbols_no_checks",
"src/fparser/two/tests/test_symbol_tables.py::test_construction_addition_removal"
] |
[
"src/fparser/two/tests/test_symbol_table.py::test_add_use_symbols",
"src/fparser/two/tests/test_symbol_table.py::test_add_use_symbols_errors",
"src/fparser/two/tests/test_symbol_table.py::test_str_method",
"src/fparser/two/tests/test_symbol_table.py::test_del_child",
"src/fparser/two/tests/test_symbol_table.py::test_parent_child",
"src/fparser/two/tests/test_symbol_table.py::test_root_property",
"src/fparser/two/tests/test_symbol_table.py::test_module_use",
"src/fparser/two/tests/test_symbol_table.py::test_module_use_with_only",
"src/fparser/two/tests/test_symbol_table.py::test_module_definition",
"src/fparser/two/tests/test_symbol_table.py::test_routine_in_module",
"src/fparser/two/tests/test_symbol_table.py::test_routine_in_prog",
"src/fparser/two/tests/test_symbol_tables.py::test_scoping_unit_classes_setter",
"src/fparser/two/tests/test_symbol_tables.py::test_str_method",
"src/fparser/two/tests/test_symbol_tables.py::test_nested_scoping",
"src/fparser/two/tests/test_symbol_tables.py::test_nested_removal"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-15 14:17:47+00:00
|
bsd-3-clause
| 5,732 |
|
stfc__fparser-356
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 40457c1..a0853d0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,8 @@ Modifications by (in alphabetical order):
20/06/2022 PR #345 - add fparser2 performance benchmark in the scripts folder.
+02/09/2022 PR #356 - add support for the mold allocate parameter.
+
## Release 0.0.16 (16/06/2022) ##
14/06/2022 PR #337 towards #312 (performance improvements). Removes some
diff --git a/doc/fparser2.rst b/doc/fparser2.rst
index 2404d23..dfbb20b 100644
--- a/doc/fparser2.rst
+++ b/doc/fparser2.rst
@@ -1,4 +1,4 @@
-.. Copyright (c) 2017-2020 Science and Technology Facilities Council.
+.. Copyright (c) 2017-2022 Science and Technology Facilities Council.
All rights reserved.
@@ -42,8 +42,8 @@ Fortran 2003. This is implemented in the Fortran2003.py `file`__ and
contains an entirely separate parser to fparser1 that includes rules
for Fortran 2003 syntax. Support for Fortran 2008 is being added in
the Fortran2008.py `file`__ which extends the Fortran2003 rules
-appropriately. At this time fparser2 supports submodules, co-arrays
-and the continguous keyword in Fortran2008.
+appropriately. At this time fparser2 supports submodules, co-arrays,
+the 'mold' argument to allocate and the 'contiguous' keyword in Fortran2008.
__ https://github.com/stfc/fparser/blob/master/src/fparser/two/Fortran2003.py
__ https://github.com/stfc/fparser/blob/master/src/fparser/two/Fortran2008.py
diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py
index 518be7b..fd18b0c 100644
--- a/src/fparser/two/Fortran2003.py
+++ b/src/fparser/two/Fortran2003.py
@@ -4805,8 +4805,43 @@ class Vector_Subscript(Base): # R622
class Allocate_Stmt(StmtBase): # R623
"""
- <allocate-stmt> = ALLOCATE ( [ <type-spec> :: ] <allocation-list>
- [ , <alloc-opt-list> ] )
+ Fortran2003 rule R623
+ allocate-stmt is ALLOCATE ( [ type-spec :: ] allocation-list
+ [, alloc-opt-list ] )
+
+ Subject to the following constraints:
+
+ C622 (R629) Each allocate-object shall be a nonprocedure pointer or an
+ allocatable variable.
+ C623 (R623) If any allocate-object in the statement has a deferred type
+ parameter, either type-spec or SOURCE= shall appear.
+ C624 (R623) If a type-spec appears, it shall specify a type with which
+ each allocate-object is type compatible.
+ C625 (R623) If any allocate-object is unlimited polymorphic, either
+ type-spec or SOURCE= shall appear.
+ C626 (R623) A type-param-value in a type-spec shall be an asterisk if and
+ only if each allocate-object is a dummy argument for which the
+ corresponding type parameter is assumed.
+ C627 (R623) If a type-spec appears, the kind type parameter values of each
+ allocate-object shall be the same as the corresponding type
+ parameter values of the type-spec.
+ C628 (R628) An allocate-shape-spec-list shall appear if and only if the
+ allocate-object is an array.
+ C629 (R628) The number of allocate-shape-specs in an
+ allocate-shape-spec-list shall be the same as the rank of the
+ allocate-object.
+ C630 (R624) No alloc-opt shall appear more than once in a given
+ alloc-opt-list.
+ C631 (R623) If SOURCE= appears, type-spec shall not appear and
+ allocation-list shall contain only one allocate-object, which
+ shall be type compatible (5.1.1.2) with source-expr.
+ C632 (R623) The source-expr shall be a scalar or have the same rank as
+ allocate-object.
+ C633 (R623) Corresponding kind type parameters of allocate-object and
+ source-expr shall have the same values.
+
+ None of these constraints are currently applied - issue #355.
+
"""
subclass_names = []
@@ -4847,32 +4882,6 @@ class Allocate_Stmt(StmtBase): # R623
return "ALLOCATE(%s)" % (lst)
-class Alloc_Opt(KeywordValueBase): # R624
- """
- <alloc-opt> = STAT = <stat-variable>
- | ERRMSG = <errmsg-variable>
- | SOURCE = <source-expr>
- """
-
- subclass_names = []
- use_names = ["Stat_Variable", "Errmsg_Variable", "Source_Expr"]
-
- @staticmethod
- def match(string):
- for (k, v) in [
- ("STAT", Stat_Variable),
- ("ERRMSG", Errmsg_Variable),
- ("SOURCE", Source_Expr),
- ]:
- try:
- obj = KeywordValueBase.match(k, v, string, upper_lhs=True)
- except NoMatchError:
- obj = None
- if obj is not None:
- return obj
- return None
-
-
class Stat_Variable(Base): # R625
"""
<stat-variable> = <scalar-int-variable>
@@ -4897,6 +4906,31 @@ class Source_Expr(Base): # R627
subclass_names = ["Expr"]
+class Alloc_Opt(KeywordValueBase): # R624
+ """
+ <alloc-opt> = STAT = <stat-variable>
+ | ERRMSG = <errmsg-variable>
+ | SOURCE = <source-expr>
+ """
+
+ subclass_names = []
+ use_names = ["Stat_Variable", "Errmsg_Variable", "Source_Expr"]
+ #: The keywords tested for in the match() method.
+ _keyword_pairs = [
+ ("STAT", Stat_Variable),
+ ("ERRMSG", Errmsg_Variable),
+ ("SOURCE", Source_Expr),
+ ]
+
+ @classmethod
+ def match(cls, string):
+ for (k, v) in cls._keyword_pairs:
+ obj = KeywordValueBase.match(k, v, string, upper_lhs=True)
+ if obj is not None:
+ return obj
+ return None
+
+
class Allocation(CallBase): # R628
"""
<allocation> = <allocate-object> [ ( <allocate-shape-spec-list> ) ]
diff --git a/src/fparser/two/Fortran2008.py b/src/fparser/two/Fortran2008.py
index 5cad698..31a9646 100644
--- a/src/fparser/two/Fortran2008.py
+++ b/src/fparser/two/Fortran2008.py
@@ -90,6 +90,10 @@ from fparser.two.Fortran2003 import (
SequenceBase,
Base,
Specification_Part,
+ Stat_Variable,
+ Errmsg_Variable,
+ Source_Expr,
+ KeywordValueBase,
Module_Subprogram_Part,
Implicit_Part,
Implicit_Part_Stmt,
@@ -106,6 +110,8 @@ from fparser.two.Fortran2003 import (
from fparser.two.Fortran2003 import (
Program_Unit as Program_Unit_2003,
Attr_Spec as Attr_Spec_2003,
+ Alloc_Opt as Alloc_Opt_2003,
+ Allocate_Stmt as Allocate_Stmt_2003,
Type_Declaration_Stmt as Type_Declaration_Stmt_2003,
Component_Attr_Spec as Component_Attr_Spec_2003,
Data_Component_Def_Stmt as Data_Component_Def_Stmt_2003,
@@ -719,6 +725,42 @@ class Do_Term_Action_Stmt(Do_Term_Action_Stmt_2003): # R826
subclass_names = ["Action_Stmt_C816"]
+class Alloc_Opt(Alloc_Opt_2003):
+ """
+ Fortran2008 rule R627
+ alloc-opt is ERRMSG = errmsg-variable
+ or MOLD = source-expr
+ or SOURCE = source-expr
+ or STAT = stat-variable
+
+ Extends the Fortran2003 version of this class by updating the keyword
+ pairs (used in match) with support for MOLD.
+
+ """
+
+ _keyword_pairs = [
+ ("STAT", Stat_Variable),
+ ("ERRMSG", Errmsg_Variable),
+ ("SOURCE", Source_Expr),
+ ("MOLD", Source_Expr),
+ ]
+
+
+class Allocate_Stmt(Allocate_Stmt_2003): # R626
+ """
+ Fortran 2008 rule R626
+ allocate-stmt is ALLOCATE ( [ type-spec :: ] allocation-list
+ [, alloc-opt-list ] )
+
+ The implementation of this rule simply ensures that the Fortran2008 version
+ of Alloc_Opt is used.
+
+ """
+
+ subclass_names = []
+ use_names = ["Type_Spec", "Allocation_List", "Alloc_Opt_List"]
+
+
class If_Stmt(If_Stmt_2003): # R837
"""
Fortran 2008 rule R837
|
stfc/fparser
|
bf33c11e11114ee1f29349e833ae5594c53c6da7
|
diff --git a/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py b/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py
new file mode 100644
index 0000000..1290b23
--- /dev/null
+++ b/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py
@@ -0,0 +1,75 @@
+# This Python file uses the following encoding: utf-8
+# Copyright (c) 2022 Science and Technology Facilities Council.
+#
+# All rights reserved.
+#
+# Modifications made as part of the fparser project are distributed
+# under the following license:
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+""" pytest module for the Fortran2003 Allocate Statement - R263. """
+
+import pytest
+from fparser.two.utils import NoMatchError
+from fparser.two.Fortran2003 import Allocate_Stmt, Alloc_Opt
+
+
[email protected]("f2003_create")
+def test_allocate_stmt():
+ """Tests for the allocate statement: R623."""
+ tcls = Allocate_Stmt
+ obj = tcls("allocate(a,b)")
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == "ALLOCATE(a, b)"
+
+ obj = tcls("allocate(real::a)")
+ assert str(obj) == "ALLOCATE(REAL::a)"
+
+ obj = tcls("allocate(real(kind=8)::a, stat=b, source=c//d)")
+ assert str(obj) == "ALLOCATE(REAL(KIND = 8)::a, STAT = b, SOURCE = c // d)"
+
+
[email protected]("f2003_create")
+def test_alloc_opt():
+ """Tests for the various forms of alloc-opt: R624."""
+ tcls = Alloc_Opt
+ obj = tcls("stat=a")
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == "STAT = a"
+ assert repr(obj) == "Alloc_Opt('STAT', Name('a'))"
+ obj = tcls("errmsg=my_msg")
+ assert str(obj) == "ERRMSG = my_msg"
+ obj = tcls("source=b")
+ assert str(obj) == "SOURCE = b"
+ # Check for a failed match - use 'mold' as that's a Fortran2008 addition
+ # so should not match here.
+ with pytest.raises(NoMatchError):
+ tcls("MOLD=b")
+ with pytest.raises(NoMatchError):
+ tcls("value")
diff --git a/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py b/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py
new file mode 100644
index 0000000..914656c
--- /dev/null
+++ b/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py
@@ -0,0 +1,65 @@
+# Copyright (c) 2022 Science and Technology Facilities Council.
+
+# All rights reserved.
+
+# Modifications made as part of the fparser project are distributed
+# under the following license:
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+
+# 3. Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Test Fortran 2008 rule R627
+
+ alloc-opt is ERRMSG = errmsg-variable
+ or MOLD = source-expr
+ or SOURCE = source-expr
+ or STAT = stat-variable
+
+The only difference to 2003 is the addition of 'MOLD' so that's what we
+test for.
+
+"""
+
+import pytest
+from fparser.two.Fortran2008 import Allocate_Stmt, Alloc_Opt
+
+
[email protected]("f2008_create")
+def test_alloc_opt():
+ """Test that Alloc_Opt supports the F2008 addition of 'MOLD'."""
+ obj = Alloc_Opt("MOLD=c")
+ assert isinstance(obj, Alloc_Opt), repr(obj)
+ assert str(obj) == "MOLD = c"
+
+
[email protected]("f2008_create")
+def test_allocate_stmt():
+ """Check that the Fortran2008 version of allocate has picked up the
+ version of Alloc_Opt that supports MOLD."""
+ obj = Allocate_Stmt("allocate(b, mold=c)")
+ assert isinstance(obj, Allocate_Stmt), repr(obj)
+ assert str(obj) == "ALLOCATE(b, MOLD = c)"
|
Allocate with mold= parameter
This is valid Fortran, but not accepted by fparser:
```
subroutine a(b1)
integer, dimension(:,:), allocatable :: b1
integer, dimension(:,:), allocatable :: a1
allocate(a1, mold=b1)
end subroutine a
```
Supporting the `mold` argument makes it easier to create the kernel-extraction driver (since we can then allocate variables without having to analyse the number of dimensions). It's not urgent, since I have a work around.
|
0.0
|
bf33c11e11114ee1f29349e833ae5594c53c6da7
|
[
"src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py::test_allocate_stmt",
"src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py::test_alloc_opt",
"src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py::test_alloc_opt",
"src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py::test_allocate_stmt"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-17 14:08:07+00:00
|
bsd-3-clause
| 5,733 |
|
stfc__fparser-374
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c3f28e..558dbde 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,9 @@ Modifications by (in alphabetical order):
* P. Vitt, University of Siegen, Germany
* A. Voysey, UK Met Office
+12/09/2022 PR #374 for #373. Removes @staticmethod decorator added to
+ Stmt_Function_Stmt.tostr() in error.
+
05/09/2022 PR #372 fix for whitespace being lost when Format_Item_List is
contained within parentheses.
diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py
index 4621729..8b5b726 100644
--- a/src/fparser/two/Fortran2003.py
+++ b/src/fparser/two/Fortran2003.py
@@ -12060,7 +12060,6 @@ class Stmt_Function_Stmt(StmtBase): # R1238
return Function_Name(name), Dummy_Arg_Name_List(args), Scalar_Expr(expr)
return Function_Name(name), None, Scalar_Expr(expr)
- @staticmethod
def tostr(self):
if self.items[1] is None:
return "%s () = %s" % (self.items[0], self.items[2])
|
stfc/fparser
|
885a232de9e0929462b5039765d7ed5764d68fac
|
diff --git a/src/fparser/two/tests/fortran2003/test_stmt_function_stmt_r1238.py b/src/fparser/two/tests/fortran2003/test_stmt_function_stmt_r1238.py
new file mode 100644
index 0000000..cb19346
--- /dev/null
+++ b/src/fparser/two/tests/fortran2003/test_stmt_function_stmt_r1238.py
@@ -0,0 +1,77 @@
+# Copyright (c) 2022 Science and Technology Facilities Council
+
+# All rights reserved.
+
+# Modifications made as part of the fparser project are distributed
+# under the following license:
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+
+# 3. Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Test Fortran 2003 rule R1238 : This file tests support for the
+Stmt_Function_Stmt class.
+
+"""
+import pytest
+
+from fparser.two.Fortran2003 import Stmt_Function_Stmt
+from fparser.two.utils import NoMatchError
+
+
+def test_stmt_function_stmt():
+ """Test that the stmt_function_stmt class can be created, raises the
+ expected exception and outputs the expected string
+ representation.
+
+ """
+ tcls = Stmt_Function_Stmt
+
+ # no args
+ obj = tcls("a()=b")
+ assert isinstance(obj, tcls), repr(obj)
+ assert str(obj) == "a () = b"
+ assert obj.tostr() == "a () = b"
+
+ # args
+ obj = tcls("a(x)=b")
+ assert obj.tostr() == "a (x) = b"
+
+ with pytest.raises(NoMatchError) as info:
+ obj = tcls("hello")
+ assert "Stmt_Function_Stmt: 'hello'" in str(info.value)
+ with pytest.raises(NoMatchError) as info:
+ obj = tcls("a()=")
+ assert "Stmt_Function_Stmt: 'a()='" in str(info.value)
+ with pytest.raises(NoMatchError) as info:
+ obj = tcls("=a")
+ assert "Stmt_Function_Stmt: '=a'" in str(info.value)
+ with pytest.raises(NoMatchError) as info:
+ obj = tcls("a)=b")
+ assert "Stmt_Function_Stmt: 'a)=b'" in str(info.value)
+ with pytest.raises(NoMatchError) as info:
+ obj = tcls("()=b")
+ assert "Stmt_Function_Stmt: '()=b'" in str(info.value)
|
Remove staticmethod for tostr() in Stmt_Function_Stmt class
A spurious staticmethod decorator has been added to the tostr() method in the Stmt_Function_Stmt class in Fortran2003.py.
|
0.0
|
885a232de9e0929462b5039765d7ed5764d68fac
|
[
"src/fparser/two/tests/fortran2003/test_stmt_function_stmt_r1238.py::test_stmt_function_stmt"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-11 09:28:11+00:00
|
bsd-3-clause
| 5,734 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.