Dataset Viewer
repo
stringlengths 11
40
| pull_number
int64 2
1.11k
| instance_id
stringlengths 15
44
| issue_numbers
stringlengths 5
14
| base_commit
stringlengths 40
40
| patch
stringlengths 261
698k
| test_patch
stringlengths 386
40.2k
| problem_statement
stringlengths 16
4.31k
| hints_text
stringclasses 12
values | created_at
stringdate 2016-03-01 00:28:06
2025-02-02 03:38:42
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
19.5k
| PASS_TO_PASS
sequencelengths 0
22k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
maykinmedia/django-log-outgoing-requests | 35 | maykinmedia__django-log-outgoing-requests-35 | ['34'] | 978b5938099a53ea7e452e9c957883aa66144dd6 | diff --git a/log_outgoing_requests/handlers.py b/log_outgoing_requests/handlers.py
index 4dbbca4..697b811 100644
--- a/log_outgoing_requests/handlers.py
+++ b/log_outgoing_requests/handlers.py
@@ -92,14 +92,18 @@ def emit(self, record: AnyLogRecord):
"url": request.url if request else "(unknown)",
"hostname": parsed_url.netloc if parsed_url else "(unknown)",
"params": parsed_url.params if parsed_url else "(unknown)",
- "status_code": response.status_code if response else None,
+ "status_code": response.status_code if response is not None else None,
"method": request.method if request else "(unknown)",
"timestamp": timestamp,
- "response_ms": int(response.elapsed.total_seconds() * 1000)
- if response
- else 0,
+ "response_ms": (
+ int(response.elapsed.total_seconds() * 1000)
+ if response is not None
+ else 0
+ ),
"req_headers": self.format_headers(scrubbed_req_headers),
- "res_headers": self.format_headers(response.headers if response else {}),
+ "res_headers": self.format_headers(
+ response.headers if response is not None else {}
+ ),
"trace": "\n".join(format_exception(exception)) if exception else "",
}
@@ -121,7 +125,7 @@ def emit(self, record: AnyLogRecord):
# check response
if (
- response
+ response is not None
and (
processed_response_body := process_body(response, config)
).allow_saving_to_db
diff --git a/log_outgoing_requests/utils.py b/log_outgoing_requests/utils.py
index be00f5b..6663613 100644
--- a/log_outgoing_requests/utils.py
+++ b/log_outgoing_requests/utils.py
@@ -113,9 +113,9 @@ def check_content_type(content_type: str) -> bool:
For patterns containing a wildcard ("text/*"), check if `content_type.pattern`
is a substring of any pattern contained in the list.
"""
- allowed_content_types: Iterable[
- ContentType
- ] = settings.LOG_OUTGOING_REQUESTS_CONTENT_TYPES
+ allowed_content_types: Iterable[ContentType] = (
+ settings.LOG_OUTGOING_REQUESTS_CONTENT_TYPES
+ )
regular_patterns = [
item.pattern for item in allowed_content_types if not item.pattern.endswith("*")
]
@@ -133,9 +133,9 @@ def get_default_encoding(content_type_pattern: str) -> str:
"""
Get the default encoding for the `ContentType` with the associated pattern.
"""
- allowed_content_types: Iterable[
- ContentType
- ] = settings.LOG_OUTGOING_REQUESTS_CONTENT_TYPES
+ allowed_content_types: Iterable[ContentType] = (
+ settings.LOG_OUTGOING_REQUESTS_CONTENT_TYPES
+ )
regular_types = [
item for item in allowed_content_types if not item.pattern.endswith("*")
| diff --git a/tests/conftest.py b/tests/conftest.py
index 0cf6fba..84041c1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -69,6 +69,25 @@ def request_mock_kwargs():
}
[email protected]
+def request_mock_kwargs_error():
+ return {
+ "url": "http://example.com:8000/some-path-that-doesnt-exist?version=2.0",
+ "status_code": 404,
+ "content": b"404 Not Found",
+ "request_headers": {
+ "Authorization": "test",
+ "Content-Type": "application/json",
+ "Content-Length": "24",
+ },
+ "headers": {
+ "Date": "Tue, 21 Mar 2023 15:24:08 GMT",
+ "Content-Type": "text/plain",
+ "Content-Length": "13",
+ },
+ }
+
+
@pytest.fixture
def request_mock_kwargs_binary():
return {
diff --git a/tests/test_logging.py b/tests/test_logging.py
index 9c62774..46030c0 100644
--- a/tests/test_logging.py
+++ b/tests/test_logging.py
@@ -1,6 +1,8 @@
"""Integration tests for the core functionality of the library"""
+import datetime
import logging
+from unittest.mock import patch
import pytest
import requests
@@ -10,6 +12,11 @@
from log_outgoing_requests.models import OutgoingRequestsLog
+def set_elapsed(response, *args, **kwargs):
+ response.elapsed = datetime.timedelta(seconds=2)
+ return response
+
+
#
# Local pytest fixtures
#
@@ -111,6 +118,53 @@ def test_data_is_saved(request_mock_kwargs, request_variants, expected_headers):
assert request_log.res_body_encoding == "utf-8"
[email protected]_db
+@freeze_time("2021-10-18 13:00:00")
+def test_data_is_saved_for_error_response(
+ request_mock_kwargs_error, request_variants, expected_headers
+):
+ for method, request_func, request_mock in request_variants:
+ request_mock(**request_mock_kwargs_error)
+ with patch(
+ "requests.sessions.default_hooks", return_value={"response": [set_elapsed]}
+ ):
+ response = request_func(
+ request_mock_kwargs_error["url"],
+ headers=request_mock_kwargs_error["request_headers"],
+ json={"test": "request data"},
+ )
+
+ assert response.status_code == 404
+
+ request_log = OutgoingRequestsLog.objects.last()
+
+ assert request_log.method == method
+ assert request_log.status_code == 404
+ assert request_log.hostname == "example.com:8000"
+ assert request_log.params == ""
+ assert request_log.query_params == "version=2.0"
+ assert request_log.response_ms == 2000
+ assert request_log.trace == ""
+ assert str(request_log) == "example.com:8000 at 2021-10-18 13:00:00+00:00"
+ assert (
+ request_log.timestamp.strftime("%Y-%m-%d %H:%M:%S") == "2021-10-18 13:00:00"
+ )
+ # headers
+ assert request_log.req_headers == expected_headers
+ assert (
+ request_log.res_headers == "Date: Tue, 21 Mar 2023 15:24:08 GMT\n"
+ "Content-Type: text/plain\nContent-Length: 13"
+ )
+ # request body
+ assert request_log.req_content_type == "application/json"
+ assert bytes(request_log.req_body) == b'{"test": "request data"}'
+ assert request_log.req_body_encoding == "utf-8"
+ # response body
+ assert request_log.res_content_type == "text/plain"
+ assert bytes(request_log.res_body) == b"404 Not Found"
+ assert request_log.res_body_encoding == "utf-8"
+
+
#
# test decoding of binary content
#
| Certain response values are not logged for responses with an error status code
Because the handler sets certain values (such as `status_code` and `response_ms`) after checking if the `response` is truthy, but error responses evaluate as `False`.
Code: https://github.com/maykinmedia/django-log-outgoing-requests/blob/main/log_outgoing_requests/handlers.py#L95
```
(Pdb) response
<Response [404]>
(Pdb) bool(response)
False
```
| 2024-02-08T15:24:25.000 | -1.0 | [
"tests/test_logging.py::test_data_is_saved_for_error_response"
] | [
"tests/test_logging.py::test_disable_save_body",
"tests/test_logging.py::test_decoding_of_binary_content[test\\x03\\xff\\xff{\\x03}-utf-8-test\\x03\\ufffd\\ufffd{\\x03}]",
"tests/test_logging.py::test_content_type_not_allowed",
"tests/test_logging.py::test_unexpected_exceptions_do_not_crash_entire_application",
"tests/test_logging.py::test_decoding_of_binary_content[test{\\x03\\xff\\xff\\x00d--test{\\x03\\ufffd\\ufffd\\x00d]",
"tests/test_logging.py::test_authorization_header_is_hidden",
"tests/test_logging.py::test_data_is_logged",
"tests/test_logging.py::test_log_only_once",
"tests/test_logging.py::test_data_is_saved",
"tests/test_logging.py::test_decoding_of_binary_content[test\\x03\\xff\\xff{\\x03}-utx-99-test\\x03\\ufffd\\ufffd{\\x03}]",
"tests/test_logging.py::test_content_length_exceeded",
"tests/test_logging.py::test_disable_save_db"
] |
|
maykinmedia/django-log-outgoing-requests | 16 | maykinmedia__django-log-outgoing-requests-16 | ['14'] | 3998158bd80bfb635e88dde18efbb8fceb5faf81 | diff --git a/log_outgoing_requests/admin.py b/log_outgoing_requests/admin.py
index a9f3b48..e9921b2 100644
--- a/log_outgoing_requests/admin.py
+++ b/log_outgoing_requests/admin.py
@@ -1,3 +1,5 @@
+from urllib.parse import urlparse
+
from django import forms
from django.contrib import admin
from django.utils.translation import gettext as _
@@ -12,7 +14,7 @@
class OutgoingRequestsLogAdmin(admin.ModelAdmin):
list_display = (
"hostname",
- "url",
+ "truncated_url",
"params",
"status_code",
"method",
@@ -93,6 +95,20 @@ def request_body(self, obj) -> str:
def response_body(self, obj) -> str:
return obj.response_body_decoded or "-"
+ def truncated_url(self, obj):
+ parsed_url = urlparse(obj.url)
+ path = parsed_url.path
+ max_length = 200
+ path_length = len(path)
+
+ if path_length <= max_length:
+ return path
+
+ half_length = (max_length - 3) // 2
+ left_half = path[:half_length]
+ right_half = path[-half_length:]
+ return left_half + " \u2026 " + right_half
+
class ConfigAdminForm(forms.ModelForm):
class Meta:
| diff --git a/tests/test_admin.py b/tests/test_admin.py
index 283b4d9..82ee05c 100644
--- a/tests/test_admin.py
+++ b/tests/test_admin.py
@@ -94,3 +94,40 @@ def test_admin_override_max_content_length(requests_mock, request_mock_kwargs):
request_log = OutgoingRequestsLog.objects.last()
assert request_log.res_body == b""
+
+
[email protected]_db
+def test_list_url_is_trucated_over_200_chars(admin_client):
+ OutgoingRequestsLog.objects.create(
+ id=1,
+ url="https://example.com/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t1u2v3w4x5y6z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s1t2u3v4w5x6y7z/some-path-3894ndjidjd93djjd3eu9jjddu9eu93j3e39ei9idjd3ddksdj9393/some-path/some-path-as-well/skdlkdlskdksdkd9828393jdd",
+ timestamp=timezone.now(),
+ )
+ url = reverse("admin:log_outgoing_requests_outgoingrequestslog_changelist")
+
+ response = admin_client.get(url)
+ html = response.content.decode("utf-8")
+ doc = PyQuery(html)
+ truncated_url = doc.find(".field-truncated_url").text()
+
+ assert (
+ truncated_url
+ == "/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t1u2v3w4x5y6z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s1t2u3v4w \u2026 d93djjd3eu9jjddu9eu93j3e39ei9idjd3ddksdj9393/some-path/some-path-as-well/skdlkdlskdksdkd9828393jdd"
+ )
+
+
[email protected]_db
+def test_list_url_is_not_trucated_under_200_chars(admin_client):
+ OutgoingRequestsLog.objects.create(
+ id=1,
+ url="https://example.com/a1b2c3d4e/some-path",
+ timestamp=timezone.now(),
+ )
+ url = reverse("admin:log_outgoing_requests_outgoingrequestslog_changelist")
+
+ response = admin_client.get(url)
+ html = response.content.decode("utf-8")
+ doc = PyQuery(html)
+ truncated_url = doc.find(".field-truncated_url").text()
+
+ assert truncated_url == "/a1b2c3d4e/some-path"
| Cut off the URL admin list field after 200 chars.
To prevent the other columns moving out of view:

Ideally, you can leave out the domain (since its already in the first column) and the URL path would be nicest if it looks like: `/some/very/very/very ... /very/long/path` (so elipses in the middle)
| 2023-07-28T07:46:09.000 | -1.0 | [
"tests/test_admin.py::test_list_url_is_not_trucated_under_200_chars",
"tests/test_admin.py::test_list_url_is_trucated_over_200_chars"
] | [
"tests/test_admin.py::test_admin_override_save_body",
"tests/test_admin.py::test_decoded_content_display",
"tests/test_admin.py::test_admin_override_db_save",
"tests/test_admin.py::test_admin_override_max_content_length"
] |
|
mateuszdrwal/challtools | 19 | mateuszdrwal__challtools-19 | ['3'] | 922e5bf9f39c84b006bbca3a50cc084460a5101d | diff --git a/challtools/codes.yml b/challtools/codes.yml
index 255c942..dfb4ea3 100755
--- a/challtools/codes.yml
+++ b/challtools/codes.yml
@@ -29,6 +29,16 @@ A006:
level: 4
formatted_message: 'The following custom service type contains a duplicate type (challenge.yml): "{type}".'
docs_message: A custom service type contains a duplicate type (challenge.yml)
+A007:
+ name: Missing predefined_service display format option
+ level: 4
+ formatted_message: 'The following predefined_service is missing a display format option (challenge.yml): {service}: "{option}".'
+ docs_message: A predefined_service is missing a display format option (challenge.yml)
+A008:
+ name: Missing service type
+ level: 4
+ formatted_message: 'The following predefined_service is referencing a missing service type (challenge.yml): "{service_type}".'
+ docs_message: A predefined_service is referencing a missing service type (challenge.yml)
# challtools messages
B001:
diff --git a/challtools/validator.py b/challtools/validator.py
index 9d9af04..188dc7c 100755
--- a/challtools/validator.py
+++ b/challtools/validator.py
@@ -4,6 +4,7 @@
from pathlib import Path
import pkg_resources
import yaml
+import re
from jsonschema import validate, ValidationError, Draft7Validator, validators
with pkg_resources.resource_stream("challtools", "codes.yml") as f:
@@ -191,6 +192,34 @@ def validate(self):
self._raise_code("A006", "custom_service_types", type=type_name)
type_names.add(type_name)
+ # A007 missing predefined_service display format option
+ service_types = [
+ {"type": "website", "display": "{url}"},
+ {"type": "tcp", "display": "nc {host} {port}"},
+ ] + self.normalized_config["custom_service_types"]
+ for predefined_service in self.normalized_config["predefined_services"]:
+ service_type = predefined_service["type"]
+ type_candidate = [
+ service for service in service_types if service["type"] == service_type
+ ]
+ # A008 missing service type
+ if not type_candidate:
+ self._raise_code(
+ "A008",
+ "predefined_services",
+ service_type=service_type,
+ )
+ continue
+ string = type_candidate[0]["display"]
+ for format_option in re.findall(r"(?<=\{)[^{}]+(?=\})", string):
+ if not format_option in predefined_service:
+ self._raise_code(
+ "A007",
+ "predefined_services",
+ service=service_type,
+ option=format_option,
+ )
+
### CTF config validation
# if no ctf config was provided to the validator we assume it does not exist and issue B001. not ideal as there might be other reasons for why the ctf config is not provided, but works for now
if self.ctf_config == None:
| diff --git a/tests/test_validator.py b/tests/test_validator.py
index 3321a53..04246c9 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -68,3 +68,58 @@ def test_invalid(self):
assert success
assert any([error["code"] == "A006" for error in errors])
+
+
+class Test_A007:
+ def test_valid(self):
+ config = get_min_valid_config()
+ config["custom_service_types"] = [
+ {"type": "ssh", "display": "ssh {user}@{host} -p {port}"}
+ ]
+ config["predefined_services"] = [
+ {"type": "ssh", "user": "root", "host": "127.0.0.1", "port": "12345"}
+ ]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert not any([error["code"] == "A007" for error in errors])
+
+ def test_invalid(self):
+ config = get_min_valid_config()
+ config["custom_service_types"] = [
+ {"type": "ssh", "display": "ssh {user}@{host} -p {port}"}
+ ]
+ config["predefined_services"] = [
+ {"type": "ssh", "user": "root", "host": "127.0.0.1"}
+ ]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert any([error["code"] == "A007" for error in errors])
+
+
+class Test_A008:
+ def test_valid(self):
+ config = get_min_valid_config()
+ config["custom_service_types"] = [{"type": "ssh", "display": "ssh display"}]
+ config["predefined_services"] = [{"type": "ssh"}]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert not any([error["code"] == "A008" for error in errors])
+
+ def test_invalid(self):
+ config = get_min_valid_config()
+ config["predefined_services"] = [{"type": "gopher"}]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert any([error["code"] == "A008" for error in errors])
| Check for duplicate yaml keys
Sometimes, the same key might be present in the challenge.yaml by mistake, which can cause issues. I don't believe pyyaml checks for this currently (a quick test returns the latest defined value), so this might be as simple as finding the option to enable it or having to subclass a loader.
| 2023-11-08T11:58:42.000 | -1.0 | [
"tests/test_validator.py::Test_A007::test_invalid",
"tests/test_validator.py::Test_A008::test_invalid"
] | [
"tests/test_validator.py::Test_A005::test_valid",
"tests/test_validator.py::Test_A006::test_invalid",
"tests/test_validator.py::Test_A005::test_warn",
"tests/test_validator.py::Test_A006::test_valid",
"tests/test_validator.py::Test_A002::test_invalid",
"tests/test_validator.py::Test_A007::test_valid",
"tests/test_validator.py::Test_A008::test_valid"
] |
|
maykinmedia/django-log-outgoing-requests | 28 | maykinmedia__django-log-outgoing-requests-28 | ['7'] | 272d3e933e9c9ed8ad9e1ca12d44dbc2fd0d1175 | diff --git a/docs/quickstart.rst b/docs/quickstart.rst
index e5c6770..fd65f13 100644
--- a/docs/quickstart.rst
+++ b/docs/quickstart.rst
@@ -85,6 +85,7 @@ you likely want to apply the following non-default settings:
LOG_OUTGOING_REQUESTS_DB_SAVE = True # save logs enabled/disabled based on the boolean value
LOG_OUTGOING_REQUESTS_DB_SAVE_BODY = True # save request/response body
LOG_OUTGOING_REQUESTS_EMIT_BODY = True # log request/response body
+ LOG_OUTGOING_REQUESTS_MAX_AGE = 1 # delete requests older than 1 day
.. note::
@@ -100,6 +101,9 @@ you likely want to apply the following non-default settings:
(which defines if/when database logging is reset after changes to the library config) should
be set to ``None``.
+ The library provides a Django management command as well as a Celery task to delete
+ logs which are older than a specified time (by default, 1 day).
+
See :ref:`reference_settings` for all available settings and their meaning.
Usage
diff --git a/log_outgoing_requests/conf.py b/log_outgoing_requests/conf.py
index 47a65ff..b44abb8 100644
--- a/log_outgoing_requests/conf.py
+++ b/log_outgoing_requests/conf.py
@@ -52,6 +52,12 @@ class LogOutgoingRequestsConf(AppConf):
database, but the body will be missing.
"""
+ MAX_AGE = 1
+ """
+ The maximum age (in days) of request logs, after which they are deleted (via a Celery
+ task, Django management command, or the like).
+ """
+
RESET_DB_SAVE_AFTER = 60
"""
If the config has been updated, reset the database logging after the specified
diff --git a/log_outgoing_requests/management/__init__.py b/log_outgoing_requests/management/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/log_outgoing_requests/management/commands/__init__.py b/log_outgoing_requests/management/commands/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/log_outgoing_requests/management/commands/prune_outgoing_request_logs.py b/log_outgoing_requests/management/commands/prune_outgoing_request_logs.py
new file mode 100644
index 0000000..9b5f188
--- /dev/null
+++ b/log_outgoing_requests/management/commands/prune_outgoing_request_logs.py
@@ -0,0 +1,9 @@
+from django.core.management.base import BaseCommand
+
+from ...models import OutgoingRequestsLog
+
+
+class Command(BaseCommand):
+ def handle(self, *args, **kwargs):
+ num_deleted = OutgoingRequestsLog.objects.prune()
+ self.stdout.write(f"Deleted {num_deleted} outgoing request log(s)")
diff --git a/log_outgoing_requests/models.py b/log_outgoing_requests/models.py
index f10cdf1..7de2bd7 100644
--- a/log_outgoing_requests/models.py
+++ b/log_outgoing_requests/models.py
@@ -1,9 +1,11 @@
import logging
+from datetime import timedelta
from typing import Union
from urllib.parse import urlparse
from django.core.validators import MinValueValidator
from django.db import models
+from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
@@ -16,6 +18,17 @@
logger = logging.getLogger(__name__)
+class OutgoingRequestsLogQueryset(models.QuerySet):
+ def prune(self) -> int:
+ max_age = settings.LOG_OUTGOING_REQUESTS_MAX_AGE
+ if max_age is None:
+ return 0
+
+ now = timezone.now()
+ num_deleted, _ = self.filter(timestamp__lt=now - timedelta(max_age)).delete()
+ return num_deleted
+
+
class OutgoingRequestsLog(models.Model):
url = models.URLField(
verbose_name=_("URL"),
@@ -108,6 +121,8 @@ class OutgoingRequestsLog(models.Model):
help_text=_("Text providing information in case of request failure."),
)
+ objects = OutgoingRequestsLogQueryset.as_manager()
+
class Meta:
verbose_name = _("Outgoing request log")
verbose_name_plural = _("Outgoing request logs")
diff --git a/log_outgoing_requests/tasks.py b/log_outgoing_requests/tasks.py
index 4f035e2..3e41557 100644
--- a/log_outgoing_requests/tasks.py
+++ b/log_outgoing_requests/tasks.py
@@ -1,6 +1,19 @@
+import logging
+
from .compat import shared_task
from .constants import SaveLogsChoice
+logger = logging.getLogger(__name__)
+
+
+@shared_task
+def prune_logs():
+ from .models import OutgoingRequestsLog
+
+ num_deleted = OutgoingRequestsLog.objects.prune()
+ logger.info("Deleted %d outgoing request log(s)", num_deleted)
+ return num_deleted
+
@shared_task
def reset_config():
| diff --git a/tests/test_tasks.py b/tests/test_tasks.py
index c520e8c..4a2dc93 100644
--- a/tests/test_tasks.py
+++ b/tests/test_tasks.py
@@ -1,5 +1,12 @@
+import logging
+from io import StringIO
+
+from django.core.management import call_command
+from django.utils import timezone
+
import pytest
import requests
+from freezegun import freeze_time
from log_outgoing_requests.config_reset import schedule_config_reset
from log_outgoing_requests.models import OutgoingRequestsLog, OutgoingRequestsLogConfig
@@ -12,6 +19,48 @@
has_celery = celery is not None
[email protected]_db
+def test_cleanup_request_logs_command(settings, caplog):
+ settings.LOG_OUTGOING_REQUESTS_MAX_AGE = 1 # delete if > 1 day old
+
+ with freeze_time("2023-10-02T12:00:00Z") as frozen_time:
+ OutgoingRequestsLog.objects.create(timestamp=timezone.now())
+ frozen_time.move_to("2023-10-04T12:00:00Z")
+ recent_log = OutgoingRequestsLog.objects.create(timestamp=timezone.now())
+
+ stdout = StringIO()
+ with caplog.at_level(logging.INFO):
+ call_command(
+ "prune_outgoing_request_logs", stdout=stdout, stderr=StringIO()
+ )
+
+ output = stdout.getvalue()
+ assert output == "Deleted 1 outgoing request log(s)\n"
+
+ assert OutgoingRequestsLog.objects.get() == recent_log
+
+
[email protected](not has_celery, reason="Celery is optional dependency")
[email protected]_db
+def test_cleanup_request_logs_celery_task(requests_mock, settings, caplog):
+ from log_outgoing_requests.tasks import prune_logs
+
+ settings.LOG_OUTGOING_REQUESTS_MAX_AGE = 1 # delete if > 1 old old
+
+ with freeze_time("2023-10-02T12:00:00Z") as frozen_time:
+ OutgoingRequestsLog.objects.create(timestamp=timezone.now())
+ frozen_time.move_to("2023-10-04T12:00:00Z")
+ recent_log = OutgoingRequestsLog.objects.create(timestamp=timezone.now())
+
+ with caplog.at_level(logging.INFO):
+ prune_logs()
+
+ assert len(caplog.records) == 1
+ assert "Deleted 1 outgoing request log(s)" in caplog.text
+
+ assert OutgoingRequestsLog.objects.get() == recent_log
+
+
@pytest.mark.skipif(not has_celery, reason="Celery is optional dependency")
@pytest.mark.django_db
def test_reset_config(requests_mock, settings):
| Move periodic "purge records" implementation to the library
This is currently implemented in Open Forms to interface with Celery tasks, but we can avoid leaking those implementation details.
Ideally, this library offers two things:
* a function `log_outgoing_requests.service.purge_log_records`, taking the (optional?) argument `older_than` which is a number of days
* an equivalent management command `purge_outgoing_request_logs`, taking the `--older-than` CLI flag which calls the function above.
This allows users of the library to decide for themselves if they want to hook this up via a celery beat task or a cronjob like solution where the management command is called (could be cron on a VM or kubernetes cronjob, or just manual invoking for low-traffic projects).
This way we avoid pulling in all of celery as a dependency and offer maximum flexibility while still hiding our own implementation details.
| 2023-10-02T13:06:27.000 | -1.0 | [
"tests/test_tasks.py::test_cleanup_request_logs_command"
] | [
"tests/test_tasks.py::test_saving_config_schedules_config_reset"
] |
|
matheusfelipeog/filometro | 42 | matheusfelipeog__filometro-42 | ['41'] | 922591df25afccec8aa8ac827da8c0c4344b9bb5 | diff --git a/filometro/deolhonafila.py b/filometro/deolhonafila.py
index 24868fd..aa24e42 100644
--- a/filometro/deolhonafila.py
+++ b/filometro/deolhonafila.py
@@ -2,7 +2,7 @@
filometro.deolhonafila
----------------------
-Disponíbiliza formas de ter acesso aos dados do site 'De Olho na Fila'.
+Disponibiliza formas de ter acesso aos dados do site 'De Olho na Fila'.
"""
__all__ = ['APIDeOlhoNaFila']
@@ -11,22 +11,30 @@
import requests
+from filometro.exceptions import DataCollectionError
+
class APIDeOlhoNaFila():
"""Um wrapper da API do site 'De Olho na Fila'."""
def __init__(self) -> None:
- self.endpoint = 'https://deolhonafila.prefeitura.sp.gov.br/processadores/dados.php'
+ self.endpoint = (
+ 'https://deolhonafila.prefeitura.sp.gov.br'
+ '/processadores/dados.php'
+ )
self.payload = {'dados': 'dados'}
self.headers = {
'User-Agent': (
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
- 'Chrome/95.0.4638.69 Safari/537.36'
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
+ '(KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
),
'Host': 'deolhonafila.prefeitura.sp.gov.br',
'Connection': 'keep-alive',
'Content-Length': '11',
- 'sec-ch-ua': '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"',
+ 'sec-ch-ua': (
+ '"Google Chrome";v="95", "Chromium";'
+ 'v="95", ";Not A Brand";v="99"'
+ ),
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
@@ -46,8 +54,22 @@ def __init__(self) -> None:
def get_data(self) -> List[dict]:
"""Pegue todos os dados do site 'De Olho na Fila'."""
- response = requests.post(self.endpoint, headers=self.headers, data=self.payload)
+ data = []
+ try:
+ response = requests.post(
+ self.endpoint,
+ headers=self.headers,
+ data=self.payload,
+ timeout=15
+ )
+
+ response.raise_for_status()
+
+ data = response.json()
- response.raise_for_status()
+ except (requests.Timeout, requests.HTTPError) as err:
+ raise DataCollectionError(
+ 'Não foi possível coletar os dados no site "De Olho na Fila".'
+ ) from err
- return response.json()
+ return data
diff --git a/filometro/exceptions.py b/filometro/exceptions.py
new file mode 100644
index 0000000..932a4ec
--- /dev/null
+++ b/filometro/exceptions.py
@@ -0,0 +1,14 @@
+"""
+filometro.exceptions
+--------------------
+
+Disponibiliza as exceções que podem ocorrer no pacote.
+"""
+
+
+class FilometroException(Exception):
+ ...
+
+
+class DataCollectionError(FilometroException):
+ ...
diff --git a/filometro/filometro.py b/filometro/filometro.py
index a71d302..c2c98b6 100644
--- a/filometro/filometro.py
+++ b/filometro/filometro.py
@@ -7,7 +7,7 @@
__all__ = ['Filometro']
-from typing import List
+from typing import List, Union
from dataclasses import asdict
@@ -63,7 +63,7 @@ class Filometro():
Fornence os métodos para coletar e filtrar os dados dos postos.
"""
- def __init__(self, _api: APIDeOlhoNaFila = None) -> None:
+ def __init__(self, _api: Union[APIDeOlhoNaFila, None] = None) -> None:
self._api = _api or APIDeOlhoNaFila()
self._postos = self._load_postos()
| diff --git a/tests/test_deolhonafila.py b/tests/test_deolhonafila.py
index 24e7728..f2c4298 100644
--- a/tests/test_deolhonafila.py
+++ b/tests/test_deolhonafila.py
@@ -12,7 +12,10 @@ def setUp(self):
self.api = APIDeOlhoNaFila()
def test_if_has_the_endpoint_attribute_with_the_valid_value(self):
- valid_endpoint = 'https://deolhonafila.prefeitura.sp.gov.br/processadores/dados.php'
+ valid_endpoint = (
+ 'https://deolhonafila.prefeitura.sp.gov.br'
+ '/processadores/dados.php'
+ )
self.assertTrue(hasattr(self.api, 'endpoint'))
self.assertEqual(self.api.endpoint, valid_endpoint)
@@ -25,14 +28,17 @@ def test_if_has_the_payload_attribute_with_the_valid_value(self):
def test_if_has_the_headers_attribute_with_the_valid_value(self):
valid_headers = {
- 'User-Agent': ( # implicit concatenation
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
- 'Chrome/95.0.4638.69 Safari/537.36'
+ 'User-Agent': (
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
+ '(KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
),
'Host': 'deolhonafila.prefeitura.sp.gov.br',
'Connection': 'keep-alive',
'Content-Length': '11',
- 'sec-ch-ua': '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"',
+ 'sec-ch-ua': (
+ '"Google Chrome";v="95", "Chromium";'
+ 'v="95", ";Not A Brand";v="99"'
+ ),
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
diff --git a/tests/test_filometro.py b/tests/test_filometro.py
index e5a5033..20f9862 100644
--- a/tests/test_filometro.py
+++ b/tests/test_filometro.py
@@ -134,7 +134,7 @@ class TestFilometro(unittest.TestCase):
"""Testes relacionados a classe Filometro."""
def setUp(self):
- self.filometro = Filometro(_api=FakeAPIDeOlhoNaFila())
+ self.filometro = Filometro(_api=FakeAPIDeOlhoNaFila()) # type: ignore
self.total_of_postos = len(self.filometro._postos)
def test_get_all_postos(self):
| Melhorar tratamento de exceção quando não tiver retorno da API
## Problema
A API do site "De Olho na Fila" está com algum problema, retornando o código http `502 Bad Gateway` após alguns segundos de espera. O código atual trata, mas não informa que não foi possível realizar a coleta dos dados. Um tratamento mais refinado e informativo é necessário.
printscreen:

## To do
- [x] Tratar as exceções que impossibilitem a coleta dos dados de alguma forma;
- [x] Levantar um `TimeoutError` após aguardar 15 segundos para obter uma resposta;
- [x] Informar que os dados não podem ser coletados por problemas na API.
| 2023-07-16T21:14:40.000 | -1.0 | [
"tests/test_deolhonafila.py::TestAPIDeOlhoNaFila::test_if_has_the_headers_attribute_with_the_valid_value"
] | [
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_immunizing",
"tests/test_deolhonafila.py::TestAPIDeOlhoNaFila::test_if_has_the_endpoint_attribute_with_the_valid_value",
"tests/test_filometro.py::TestFilometro::test_return_from_all_postos_cannot_reference_internal_data_list",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_situation",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_open",
"tests/test_filometro.py::TestFilometro::test_convert_postos_to_dict",
"tests/test_filometro.py::TestPostoFactory::test_create_a_list_of_postos_objects",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_modality",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_district",
"tests/test_filometro.py::TestPostoFactory::test_create_posto_object",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_zone",
"tests/test_filometro.py::TestFilometro::test_get_all_postos",
"tests/test_filometro.py::TestPostoFactory::test_raise_exception_with_missing_mandatory_key",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_closed",
"tests/test_deolhonafila.py::TestAPIDeOlhoNaFila::test_if_has_the_payload_attribute_with_the_valid_value"
] |
|
mateuszdrwal/challtools | 18 | mateuszdrwal__challtools-18 | ['3'] | 91da3cec758dff9177c25653d3d42882351dd942 | diff --git a/challtools/codes.yml b/challtools/codes.yml
index 9a15a67..255c942 100755
--- a/challtools/codes.yml
+++ b/challtools/codes.yml
@@ -24,6 +24,11 @@ A005:
level: 3
formatted_message: 'The following regex flag is missing anchors (''^'', ''$'') in the challenge configuration file (challenge.yml): "{flag}".'
docs_message: A regex flag missing anchors ('^', '$') n the challenge configuration file (challenge.yml)
+A006:
+ name: Duplicate custom_service_types types
+ level: 4
+ formatted_message: 'The following custom service type contains a duplicate type (challenge.yml): "{type}".'
+ docs_message: A custom service type contains a duplicate type (challenge.yml)
# challtools messages
B001:
diff --git a/challtools/validator.py b/challtools/validator.py
index 3065412..9d9af04 100755
--- a/challtools/validator.py
+++ b/challtools/validator.py
@@ -182,6 +182,15 @@ def validate(self):
continue
if not (flag["flag"].startswith("^") and flag["flag"].endswith("$")):
self._raise_code("A005", "flags", flag=flag["flag"])
+
+ # A006 duplicate custom_service_types type
+ type_names = set()
+ for custom_service_type in self.normalized_config["custom_service_types"]:
+ type_name = custom_service_type["type"]
+ if type_name in type_names:
+ self._raise_code("A006", "custom_service_types", type=type_name)
+ type_names.add(type_name)
+
### CTF config validation
# if no ctf config was provided to the validator we assume it does not exist and issue B001. not ideal as there might be other reasons for why the ctf config is not provided, but works for now
if self.ctf_config == None:
| diff --git a/tests/test_validator.py b/tests/test_validator.py
index 1be6353..3321a53 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -40,3 +40,31 @@ def test_warn(self):
success, errors = validator.validate()
assert success
assert any([error["code"] == "A005" for error in errors])
+
+
+class Test_A006:
+ def test_valid(self):
+ config = get_min_valid_config()
+ config["custom_service_types"] = [
+ {"type": "ssh", "display": "ssh display"},
+ {"type": "gopher", "display": "gopher display"},
+ ]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert not any([error["code"] == "A006" for error in errors])
+
+ def test_invalid(self):
+ config = get_min_valid_config()
+ config["custom_service_types"] = [
+ {"type": "ssh", "display": "ssh display"},
+ {"type": "ssh", "display": "ssh display number two"},
+ ]
+ validator = ConfigValidator(config)
+
+ success, errors = validator.validate()
+
+ assert success
+ assert any([error["code"] == "A006" for error in errors])
| Check for duplicate yaml keys
Sometimes, the same key might be present in the challenge.yaml by mistake, which can cause issues. I don't believe pyyaml checks for this currently (a quick test returns the latest defined value), so this might be as simple as finding the option to enable it or having to subclass a loader.
| 2023-11-03T17:04:31.000 | -1.0 | [
"tests/test_validator.py::Test_A006::test_invalid"
] | [
"tests/test_validator.py::Test_A005::test_valid",
"tests/test_validator.py::Test_A006::test_valid",
"tests/test_validator.py::Test_A005::test_warn",
"tests/test_validator.py::Test_A002::test_invalid"
] |
|
palazzem/econnect-python | 72 | palazzem__econnect-python-72 | ['57'] | d33ce9910ab62bd01a43a78681fc5785e2f4d5e9 | diff --git a/elmo/api/client.py b/elmo/api/client.py
index b73a14b..ed17b48 100644
--- a/elmo/api/client.py
+++ b/elmo/api/client.py
@@ -463,29 +463,32 @@ def _get_descriptions(self):
@require_session
def query(self, query):
- """Query an Elmo System to retrieve registered entries. Items are grouped
- by "Active" status. It's possible to query different part of the system
- using the `elmo.query` module:
+ """Query an Elmo System to retrieve registered entries. It's possible to query
+ different part of the system using the `elmo.query` module:
from elmo import query
- sectors_armed, sectors_disarmed = client.query(query.SECTORS)
- inputs_alerted, inputs_wait = client.query(query.INPUTS)
+ sectors = client.query(query.SECTORS)
+ inputs = client.query(query.INPUTS)
Raises:
QueryNotValid: if the query is not recognized.
HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
- A tuple containing two list `(active, not_active)`. Every item is an entry
- (sector or input) represented by a `dict` with the following fields: `id`,
- `index`, `element`, `name`.
+ A list of items containing the raw query. Every item is an entry
+ (sector or input) represented by a `dict` with the following structure:
+ {
+ "id": 1,
+ "index": 0,
+ "element": 3,
+ "excluded": False,
+ "name": "Kitchen",
+ }
"""
# Query detection
if query == q.SECTORS:
endpoint = self._router.sectors
- status = "Active"
elif query == q.INPUTS:
- status = "Alarm"
endpoint = self._router.inputs
else:
# Bail-out if the query is not recognized
@@ -494,30 +497,25 @@ def query(self, query):
response = self._session.post(endpoint, data={"sessionId": self._session_id})
response.raise_for_status()
- # Retrieve cached descriptions
+ # Retrieve description or use the cache
descriptions = self._get_descriptions()
# Filter only entries that are used
- active = []
- not_active = []
+ # `excluded` field is available only on inputs, but to return the same `dict`
+ # structure, we default "excluded" as False for sectors. In fact, sectors
+ # are never excluded.
entries = response.json()
-
- # The last entry ID is used in `self.poll()` long-polling API
- self._latestEntryId[query] = entries[-1]["Id"]
-
- # Massage data
+ items = {}
for entry in entries:
if entry["InUse"]:
item = {
- "id": entry["Id"],
- "index": entry["Index"],
- "element": entry["Element"],
- "name": descriptions[query][entry["Index"]],
+ "id": entry.get("Id"),
+ "index": entry.get("Index"),
+ "element": entry.get("Element"),
+ "excluded": entry.get("Excluded", False),
+ "name": descriptions[query][entry.get("Index")],
}
- if entry[status]:
- active.append(item)
- else:
- not_active.append(item)
+ items[entry.get("Index")] = item
- return active, not_active
+ return items
| diff --git a/tests/conftest.py b/tests/conftest.py
index e5bb2eb..d8c5653 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -109,7 +109,7 @@ def inputs_json():
{
"Alarm": false,
"MemoryAlarm": false,
- "Excluded": false,
+ "Excluded": true,
"InUse": true,
"IsVideo": false,
"Id": 3,
diff --git a/tests/test_client.py b/tests/test_client.py
index 55e8d75..660cfde 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1124,19 +1124,21 @@ def test_client_get_sectors_status(server, client, sectors_json, mocker):
9: {0: "Living Room", 1: "Bedroom", 2: "Kitchen", 3: "Entryway"},
}
client._session_id = "test"
- sectors_armed, sectors_disarmed = client.query(query.SECTORS)
+ sectors = client.query(query.SECTORS)
# Expected output
assert client._get_descriptions.called is True
assert len(server.calls) == 1
- assert sectors_armed == [
- {"element": 1, "id": 1, "index": 0, "name": "Living Room"},
- {"element": 2, "id": 2, "index": 1, "name": "Bedroom"},
- ]
- assert sectors_disarmed == [
- {"element": 3, "id": 3, "index": 2, "name": "Kitchen"},
- ]
- # Element 4 is filtered out but the query must store that value
- assert client._latestEntryId[query.SECTORS] == 4
+ assert sectors == {
+ 0: {
+ "element": 1,
+ "id": 1,
+ "index": 0,
+ "excluded": False,
+ "name": "Living Room",
+ },
+ 1: {"element": 2, "id": 2, "index": 1, "excluded": False, "name": "Bedroom"},
+ 2: {"element": 3, "id": 3, "index": 2, "excluded": False, "name": "Kitchen"},
+ }
def test_client_get_inputs(server, client, inputs_json, mocker):
@@ -1150,19 +1152,27 @@ def test_client_get_inputs(server, client, inputs_json, mocker):
10: {0: "Alarm", 1: "Window kitchen", 2: "Door entryway", 3: "Window bathroom"},
}
client._session_id = "test"
- inputs_alerted, inputs_wait = client.query(query.INPUTS)
+ inputs = client.query(query.INPUTS)
# Expected output
assert client._get_descriptions.called is True
assert len(server.calls) == 1
- assert inputs_alerted == [
- {"element": 1, "id": 1, "index": 0, "name": "Alarm"},
- {"element": 2, "id": 2, "index": 1, "name": "Window kitchen"},
- ]
- assert inputs_wait == [
- {"element": 3, "id": 3, "index": 2, "name": "Door entryway"},
- ]
- # Element 4 is filtered out but the query must store that value
- assert client._latestEntryId[query.INPUTS] == 4
+ assert inputs == {
+ 0: {"element": 1, "id": 1, "index": 0, "excluded": False, "name": "Alarm"},
+ 1: {
+ "element": 2,
+ "id": 2,
+ "index": 1,
+ "excluded": False,
+ "name": "Window kitchen",
+ },
+ 2: {
+ "element": 3,
+ "id": 3,
+ "index": 2,
+ "excluded": True,
+ "name": "Door entryway",
+ },
+ }
def test_client_query_not_valid(client):
| Cannot retrieve system input exclusion status
Filled as per [this comment](https://github.com/palazzem/econnect-python/pull/55#pullrequestreview-421478063) of #55.
I need a way to get data about system inputs exclusion status.
This is a piece of info exposed by the server response to the [query](https://github.com/palazzem/econnect-python/blob/76915efc6fced0a166b5f832bf7f4786d2d7b1ad/elmo/api/client.py#L244-L261) along with other additional details.
Currently the query function simply ignores these details.
The same stands for sectors.
The first solution that comes into my mind is adding a `def rawquery(self, query, callback):` function which returns the result of invoking _callback_ passing the data as returned by the server.
(Probably there are more pythonic ways to achieve the same)
This is an excerpt of the whole set of attributes exposed by the server api respectively for sectors and inputs.
_SECTORS_
```
'Active' = {bool} False
'ActivePartial' = {bool} False
'Max' = {bool} False
'Activable' = {bool} True
'ActivablePartial' = {bool} False
'InUse' = {bool} True
'Id' = {int} 7010
'Index' = {int} 0
'Element' = {int} 1
'CommandId' = {int} 0
'InProgress' = {bool} False
```
_INPUTS_
```
'Alarm' = {bool} False
'MemoryAlarm' = {bool} False
'Excluded' = {bool} False
'InUse' = {bool} True
'IsVideo' = {bool} False
'Id' = {int} 26114
'Index' = {int} 0
'Element' = {int} 1
'CommandId' = {int} 0
'InProgress' = {bool} False
```
| I'm currently working in making `ElmoClient` lightweight with the only responsibility of handling the connection and making API calls. This means that I'm going to include the raw query and then let an external component (e.g. the `Device` object I'm adding in another branch) handle what is active/not active or included/excluded.
I will close this issue once all PRs are merged into `master`. | 2021-08-14T15:05:11.000 | -1.0 | [
"tests/test_client.py::test_client_get_sectors_status",
"tests/test_client.py::test_client_get_inputs"
] | [
"tests/test_client.py::test_client_auth_without_domain",
"tests/test_client.py::test_client_auth_success",
"tests/test_client.py::test_client_query_not_valid",
"tests/test_client.py::test_client_include_fails_unknown_error",
"tests/test_client.py::test_client_arm_fails_wrong_sector",
"tests/test_client.py::test_client_poll_unknown_error",
"tests/test_client.py::test_client_unlock_fails_missing_lock",
"tests/test_client.py::test_client_include_fails_wrong_input",
"tests/test_client.py::test_client_poll_with_updated_ids",
"tests/test_client.py::test_client_arm_sectors",
"tests/test_client.py::test_client_poll_with_changes",
"tests/test_client.py::test_client_include_fails_missing_session",
"tests/test_client.py::test_client_unlock",
"tests/test_client.py::test_client_unlock_fails_unexpected_error",
"tests/test_client.py::test_client_include",
"tests/test_client.py::test_client_arm_fails_unknown_error",
"tests/test_client.py::test_client_auth_unknown_error",
"tests/test_client.py::test_client_auth_forbidden",
"tests/test_client.py::test_client_lock_wrong_code",
"tests/test_client.py::test_client_lock",
"tests/test_client.py::test_client_disarm_fails_missing_session",
"tests/test_client.py::test_client_lock_unknown_error",
"tests/test_client.py::test_client_disarm_fails_unknown_error",
"tests/test_client.py::test_client_query_unauthorized",
"tests/test_client.py::test_client_disarm_fails_wrong_sector",
"tests/test_client.py::test_client_auth_redirect",
"tests/test_client.py::test_client_auth_infinite_redirect",
"tests/test_client.py::test_client_auth_with_domain",
"tests/test_client.py::test_client_get_descriptions_cached",
"tests/test_client.py::test_client_lock_calls_unlock",
"tests/test_client.py::test_client_constructor_with_session_id",
"tests/test_client.py::test_client_arm",
"tests/test_client.py::test_client_arm_fails_missing_lock",
"tests/test_client.py::test_client_constructor_default",
"tests/test_client.py::test_client_lock_called_twice",
"tests/test_client.py::test_client_constructor",
"tests/test_client.py::test_client_poll",
"tests/test_client.py::test_client_exclude_fails_missing_lock",
"tests/test_client.py::test_client_get_descriptions_unauthorized",
"tests/test_client.py::test_client_include_multiple_inputs",
"tests/test_client.py::test_client_arm_fails_missing_session",
"tests/test_client.py::test_client_include_fails_missing_lock",
"tests/test_client.py::test_client_query_error",
"tests/test_client.py::test_client_exclude_fails_missing_session",
"tests/test_client.py::test_client_get_descriptions_error",
"tests/test_client.py::test_client_disarm_fails_missing_lock",
"tests/test_client.py::test_client_disarm_sectors",
"tests/test_client.py::test_client_disarm",
"tests/test_client.py::test_client_exclude_fails_unknown_error",
"tests/test_client.py::test_client_constructor_v03",
"tests/test_client.py::test_client_exclude",
"tests/test_client.py::test_client_exclude_fails_wrong_input",
"tests/test_client.py::test_client_lock_and_unlock_with_exception",
"tests/test_client.py::test_client_unlock_fails_forbidden",
"tests/test_client.py::test_client_get_descriptions"
] |
palazzem/econnect-python | 66 | palazzem__econnect-python-66 | ['56'] | 221cd7c01538c56036167b89ddee2b5dcf3bceb5 | diff --git a/elmo/api/client.py b/elmo/api/client.py
index 807d600..5666943 100644
--- a/elmo/api/client.py
+++ b/elmo/api/client.py
@@ -119,8 +119,10 @@ def lock(self, code):
raise CodeError
self._lock.acquire()
- yield self
- self.unlock()
+ try:
+ yield self
+ finally:
+ self.unlock()
@require_session
@require_lock
| diff --git a/tests/test_client.py b/tests/test_client.py
index e221b74..6650e17 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -289,6 +289,28 @@ def test_client_lock_calls_unlock(server, client, mocker):
assert len(server.calls) == 1
+def test_client_lock_and_unlock_with_exception(server, client, mocker):
+ """Should call unlock() even if an exception is raised in the block."""
+ html = """[
+ {
+ "Poller": {"Poller": 1, "Panel": 1},
+ "CommandId": 5,
+ "Successful": true
+ }
+ ]"""
+ server.add(
+ responses.POST, "https://example.com/api/panel/syncLogin", body=html, status=200
+ )
+ mocker.patch.object(client, "unlock")
+ client._session_id = "test"
+
+ with pytest.raises(Exception):
+ with client.lock("test"):
+ raise Exception
+ assert client.unlock.called is True
+ assert len(server.calls) == 1
+
+
def test_client_unlock(server, client):
"""Should call the API and release the system lock."""
html = """[
| with client.lock() doesn't unlock in case of error within the execution block
Filled as per [this comment](https://github.com/palazzem/econnect-python/pull/55#pullrequestreview-421478063) of #55.
**Steps to reproduce**
Wrap a lock in a _with_ statement, and throw an exception in the related execution block
**Actual behavior**
the lock is still in place even after the _with_ block execution is finished
**Expected behavior**
the lock is released as soon as the _with_ block execution is finished
**Steps to reproduce**
This is the easiest way I've found to reproduce it
```
from elmo.api.client import ElmoClient
BASE_URL = "https://connect3.elmospa.com"
VENDOR = "yourvendor"
USERNAME = "yourname"
PASSWORD = "*****"
CODE = "*****"
if __name__ == '__main__':
client = ElmoClient(BASE_URL, VENDOR)
client.auth(USERNAME, PASSWORD)
with client.lock(CODE) as c:
c.disarm()
assert False
```
**Side notes**
The snippet I've provided is a naive example. In my code the error is thrown by a call to `vibrator.vibrate()` (from plyer), which in turn catches the error and simply logs a message if the vibration service is not in place.
Given that I'm not a pythonist, when I write `with client.lock()...` I'd expect a semantic similar to a _try...finally_ where at the end the lock is released.
Some references:
* https://docs.python.org/3/reference/compound_stmts.html#the-with-statement
* https://www.python.org/dev/peps/pep-0343/
| 2021-03-10T15:03:26.000 | -1.0 | [
"tests/test_client.py::test_client_lock_and_unlock_with_exception"
] | [
"tests/test_client.py::test_client_auth_without_domain",
"tests/test_client.py::test_client_query_not_valid",
"tests/test_client.py::test_client_auth_success",
"tests/test_client.py::test_client_arm_fails_wrong_sector",
"tests/test_client.py::test_client_unlock_fails_missing_lock",
"tests/test_client.py::test_client_arm_sectors",
"tests/test_client.py::test_client_unlock",
"tests/test_client.py::test_client_unlock_fails_unexpected_error",
"tests/test_client.py::test_client_arm_fails_unknown_error",
"tests/test_client.py::test_client_auth_unknown_error",
"tests/test_client.py::test_client_auth_forbidden",
"tests/test_client.py::test_client_lock_wrong_code",
"tests/test_client.py::test_client_get_descriptions",
"tests/test_client.py::test_client_lock",
"tests/test_client.py::test_client_disarm_fails_missing_session",
"tests/test_client.py::test_client_lock_unknown_error",
"tests/test_client.py::test_client_disarm_fails_unknown_error",
"tests/test_client.py::test_client_query_unauthorized",
"tests/test_client.py::test_client_auth_redirect",
"tests/test_client.py::test_client_auth_infinite_redirect",
"tests/test_client.py::test_client_auth_with_domain",
"tests/test_client.py::test_client_get_descriptions_cached",
"tests/test_client.py::test_client_get_sectors_status",
"tests/test_client.py::test_client_lock_calls_unlock",
"tests/test_client.py::test_client_constructor_with_session_id",
"tests/test_client.py::test_client_arm",
"tests/test_client.py::test_client_lock_called_twice",
"tests/test_client.py::test_client_constructor_default",
"tests/test_client.py::test_client_arm_fails_missing_lock",
"tests/test_client.py::test_client_constructor",
"tests/test_client.py::test_client_get_inputs",
"tests/test_client.py::test_client_get_descriptions_unauthorized",
"tests/test_client.py::test_client_arm_fails_missing_session",
"tests/test_client.py::test_client_disarm_fails_missing_lock",
"tests/test_client.py::test_client_query_error",
"tests/test_client.py::test_client_get_descriptions_error",
"tests/test_client.py::test_client_disarm_sectors",
"tests/test_client.py::test_client_disarm",
"tests/test_client.py::test_client_constructor_v03",
"tests/test_client.py::test_client_check_success",
"tests/test_client.py::test_client_unlock_fails_forbidden",
"tests/test_client.py::test_client_disarm_fails_wrong_sector"
] |
|
matheusfelipeog/filometro | 18 | matheusfelipeog__filometro-18 | ['17'] | c03d2844f33b04ca3c316517483387c806c6d0a5 | diff --git a/filometro/filometro.py b/filometro/filometro.py
index e394b47..45d2654 100644
--- a/filometro/filometro.py
+++ b/filometro/filometro.py
@@ -61,8 +61,8 @@ class Filometro():
Fornence os métodos para coletar e filtrar os dados dos postos.
"""
- def __init__(self, _api: APIDeOlhoNaFila = APIDeOlhoNaFila) -> None:
- self._api = _api()
+ def __init__(self, _api: APIDeOlhoNaFila = None) -> None:
+ self._api = _api or APIDeOlhoNaFila()
self._postos = self._load_postos()
| diff --git a/tests/test_filometro.py b/tests/test_filometro.py
index 6face7a..3ed6a0d 100644
--- a/tests/test_filometro.py
+++ b/tests/test_filometro.py
@@ -128,7 +128,7 @@ class TestFilometro(unittest.TestCase):
"""Testes relacionados a classe Filometro."""
def setUp(self):
- self.filometro = Filometro(_api=FakeAPIDeOlhoNaFila)
+ self.filometro = Filometro(_api=FakeAPIDeOlhoNaFila())
self.total_of_postos = len(self.filometro._postos)
def test_get_all_postos(self):
| Corrigir a injeção de dependência na classe Filometro
A classe `Filometro` possui o argumento interno `_api`, atualmente ele mantém referência a definição da classe `APIDeOlhoNaFila` e não a um objeto dela.
| 2022-10-17T20:12:04.000 | -1.0 | [
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_immunizing",
"tests/test_filometro.py::TestFilometro::test_return_from_all_postos_cannot_reference_internal_data_list",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_situation",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_open",
"tests/test_filometro.py::TestFilometro::test_convert_postos_to_dict",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_district",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_modality",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_from_a_specific_zone",
"tests/test_filometro.py::TestFilometro::test_get_all_postos",
"tests/test_filometro.py::TestFilometro::test_get_all_postos_closed"
] | [
"tests/test_filometro.py::TestPostoFactory::test_create_a_list_of_postos_objects",
"tests/test_filometro.py::TestPostoFactory::test_raise_exception_with_missing_mandatory_key",
"tests/test_filometro.py::TestPostoFactory::test_create_posto_object"
] |
|
gudjonragnar/fastavro-gen | 10 | gudjonragnar__fastavro-gen-10 | ['7'] | 522f14889d78d5fed8923fb5a2a8cc8cb16714c5 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..9704c6e
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,52 @@
+name: CI
+
+on: [push, pull_request]
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ typecheck:
+ runs-on: ubuntu-20.04
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v2
+
+ - name: Set up Python 3.8
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.8
+
+ - name: Install dependencies
+ run: python3.8 -m pip install nox
+
+ - name: Run mypy
+ run: nox -s typecheck
+
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: [3.8, 3.9]
+ os: [macos-latest, windows-latest, ubuntu-latest]
+ experimental: [false]
+
+ runs-on: ${{ matrix.os }}
+ name: ${{ fromJson('{"macos-latest":"macOS","windows-latest":"Windows","ubuntu-latest":"Ubuntu"}')[matrix.os] }} ${{ matrix.python-version }}
+ continue-on-error: ${{ matrix.experimental }}
+ steps:
+ - name: Checkout Repository
+ uses: actions/checkout@v2
+
+ - name: Set Up Python - ${{ matrix.python-version }}
+ uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install Dependencies
+ run: python -m pip install --upgrade nox
+
+ - name: Run Tests
+ run: nox -s test-${{ matrix.python-version }} --error-on-missing-interpreters
\ No newline at end of file
diff --git a/fastavro_gen/__main__.py b/fastavro_gen/__main__.py
index ad43a02..48ec8b6 100644
--- a/fastavro_gen/__main__.py
+++ b/fastavro_gen/__main__.py
@@ -1,5 +1,5 @@
from argparse import ArgumentParser
-from typing import Dict, List
+from typing import Dict, List, cast
from fastavro_gen.models import OutputType
from fastavro_gen.type_gen import read_schemas_and_generate_classes
import toml
@@ -46,10 +46,11 @@ def main() -> None:
)
args = parser.parse_args()
+ schemas_to_parse: Dict[str, List[str]]
if args.ordered:
- schemas_to_parse = toml.load(args.ordered)
+ schemas_to_parse = cast(Dict[str, List[str]], toml.load(args.ordered))
else:
- schemas_to_parse: Dict[str, List[str]] = {}
+ schemas_to_parse = {}
for f in args.file:
schemas_to_parse[f.split("/")[-1]] = [f]
read_schemas_and_generate_classes(
diff --git a/fastavro_gen/type_gen.py b/fastavro_gen/type_gen.py
index 2e5803b..3a73d4d 100644
--- a/fastavro_gen/type_gen.py
+++ b/fastavro_gen/type_gen.py
@@ -67,9 +67,9 @@ def _parse_type(
return _parse_type(_type[0], collector, namespace_prefix=namespace_prefix)
if len(_type) == 2 and "null" in _type:
_other = [i for i in _type if i != "null"]
- if _other:
- collector.typing.add("Optional")
- return f"Optional[{_parse_type(_other[0], collector, namespace_prefix=namespace_prefix)}]"
+ collector.typing.add("Optional")
+ return f"Optional[{_parse_type(_other[0], collector, namespace_prefix=namespace_prefix)}]"
+
else:
collector.typing.add("Union")
return f"Union[{', '.join([_parse_type(t, collector, namespace_prefix=namespace_prefix) for t in _type])}]"
diff --git a/noxfile.py b/noxfile.py
new file mode 100644
index 0000000..55bae5f
--- /dev/null
+++ b/noxfile.py
@@ -0,0 +1,21 @@
+import nox
+
+
[email protected](python=["3.8", "3.9"])
+def test(session):
+ session.install("fastavro", "black", "pytest")
+ session.install(".")
+
+ # Show the pip version.
+ session.run("pip", "--version")
+ # Print the Python version and bytesize.
+ session.run("python", "--version")
+
+ session.run("pytest", "tests")
+
+
[email protected]
+def typecheck(session):
+ session.install("mypy")
+
+ session.run("mypy", "--ignore-missing-imports", "fastavro_gen")
\ No newline at end of file
diff --git a/setup.py b/setup.py
index e9c5ad7..777ef76 100644
--- a/setup.py
+++ b/setup.py
@@ -26,7 +26,7 @@
"zstandard": ["zstandard"],
"lz4": ["lz4"],
},
- install_requires=["fastavro>=1.3.0"],
+ install_requires=["fastavro>=1.3.0", "black"],
tests_require=["pytest", "mypy"],
package_data={"fastavro_gen": ["py.typed"]},
)
\ No newline at end of file
| diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_from_dict.py b/tests/test_from_dict.py
index 66a8f98..0831ad9 100644
--- a/tests/test_from_dict.py
+++ b/tests/test_from_dict.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
-from tests.test_utils import roundtrip
+from tests.utils import roundtrip
@dataclass
diff --git a/tests/test_generate_classes.py b/tests/test_generate_classes.py
index f789b1a..7ad7834 100644
--- a/tests/test_generate_classes.py
+++ b/tests/test_generate_classes.py
@@ -4,7 +4,7 @@
import os
import sys
from contextlib import contextmanager
-from tests.test_utils import roundtrip
+from tests.utils import roundtrip
@contextmanager
diff --git a/tests/test_utils.py b/tests/utils.py
similarity index 100%
rename from tests/test_utils.py
rename to tests/utils.py
| Fix Mypy issues
| 2021-02-02T14:36:11.000 | -1.0 | [
"tests/test_generate_classes.py::test_generate_schema_classes[OutputType.DATACLASS]",
"tests/test_generate_classes.py::test_generate_schema_classes[OutputType.TYPEDDICT]"
] | [
"tests/test_from_dict.py::test_map",
"tests/test_from_dict.py::test_optional_and_union",
"tests/test_from_dict.py::test_primitives",
"tests/test_from_dict.py::test_lists"
] |
|
palazzem/econnect-python | 39 | palazzem__econnect-python-39 | ['37'] | aa3bbf1b14a4187fa34c45d393ceffaacc403161 | diff --git a/elmo/api/client.py b/elmo/api/client.py
index 42afed7..580f0d2 100644
--- a/elmo/api/client.py
+++ b/elmo/api/client.py
@@ -4,7 +4,7 @@
from requests import Session
from .router import Router
-from .exceptions import PermissionDenied, APIException
+from .exceptions import PermissionDenied
from .decorators import require_session, require_lock
from ..utils import parser
@@ -33,27 +33,26 @@ def __init__(self, base_url, vendor, session_id=None):
self._lock = Lock()
def auth(self, username, password):
- """Authenticate the client and retrieves the access token.
+ """Authenticate the client and retrieves the access token. This API uses
+ a standard authentication form, so even if the authentication fails, a
+ 2xx status code is returned. In that case, the `session_id` is validated
+ to see if the call was a success.
Args:
username: the Username used for the authentication.
password: the Password used for the authentication.
Raises:
PermissionDenied: if wrong credentials are used.
- APIException: if there is an error raised by the API (not 2xx response).
+ HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
The access token retrieved from the scraped page. The token is also
cached in the `ElmoClient` instance.
"""
payload = {"UserName": username, "Password": password, "RememberMe": False}
response = self._session.post(self._router.auth, data=payload)
- if response.status_code == 200:
- self._session_id = parser.get_access_token(response.text)
- else:
- raise APIException(
- "Unexpected status code: {}".format(response.status_code)
- )
+ response.raise_for_status()
+ self._session_id = parser.get_access_token(response.text)
if self._session_id is None:
raise PermissionDenied("Incorrect authentication credentials")
@@ -69,23 +68,17 @@ def lock(self, code):
Args:
code: the alarm code used to obtain the lock.
Raises:
- PermissionDenied: if a wrong access token is used or expired.
- APIException: if there is an error raised by the API (not 2xx response).
+ HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
A client instance with an acquired lock.
"""
payload = {"userId": 1, "password": code, "sessionId": self._session_id}
response = self._session.post(self._router.lock, data=payload)
- if response.status_code == 200:
- self._lock.acquire()
- yield self
- self.unlock()
- elif response.status_code == 403:
- raise PermissionDenied()
- else:
- raise APIException(
- "Unexpected status code: {}".format(response.status_code)
- )
+ response.raise_for_status()
+
+ self._lock.acquire()
+ yield self
+ self.unlock()
@require_session
@require_lock
@@ -99,26 +92,19 @@ def unlock(self):
gain the lock.
Raises:
- PermissionDenied: if a wrong access token is used or expired.
- APIException: if there is an error raised by the API (not 2xx response).
+ HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
A boolean if the lock has been released correctly.
"""
payload = {"sessionId": self._session_id}
response = self._session.post(self._router.unlock, data=payload)
+ response.raise_for_status()
# Release the lock only in case of success, so that if it fails
# the owner of the lock can properly unlock the system again
# (maybe with a retry)
- if response.status_code == 200:
- self._lock.release()
- return True
- elif response.status_code == 403:
- raise PermissionDenied()
- else:
- raise APIException(
- "Unexpected status code: {}".format(response.status_code)
- )
+ self._lock.release()
+ return True
@require_session
@require_lock
@@ -129,8 +115,7 @@ def arm(self):
enabling only some alerts.
Raises:
- PermissionDenied: if a wrong access token is used or expired.
- APIException: if there is an error raised by the API (not 2xx response).
+ HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
A boolean if the system has been armed correctly.
"""
@@ -141,14 +126,8 @@ def arm(self):
"sessionId": self._session_id,
}
response = self._session.post(self._router.send_command, data=payload)
- if response.status_code == 200:
- return True
- elif response.status_code == 403:
- raise PermissionDenied()
- else:
- raise APIException(
- "Unexpected status code: {}".format(response.status_code)
- )
+ response.raise_for_status()
+ return True
@require_session
@require_lock
@@ -159,8 +138,7 @@ def disarm(self):
enabling only some alerts.
Raises:
- PermissionDenied: if a wrong access token is used or expired.
- APIException: if there is an error raised by the API (not 2xx response).
+ HTTPError: if there is an error raised by the API (not 2xx response).
Returns:
A boolean if the system has been disarmed correctly.
"""
@@ -171,11 +149,5 @@ def disarm(self):
"sessionId": self._session_id,
}
response = self._session.post(self._router.send_command, data=payload)
- if response.status_code == 200:
- return True
- elif response.status_code == 403:
- raise PermissionDenied()
- else:
- raise APIException(
- "Unexpected status code: {}".format(response.status_code)
- )
+ response.raise_for_status()
+ return True
diff --git a/elmo/api/exceptions.py b/elmo/api/exceptions.py
index 5167597..1f60679 100644
--- a/elmo/api/exceptions.py
+++ b/elmo/api/exceptions.py
@@ -4,10 +4,7 @@ class APIException(Exception):
default_message = "A server error occurred"
def __init__(self, message=None):
- if message is None:
- message = self.default_message
-
- self.message = message
+ self.message = message or self.default_message
def __str__(self):
return str(self.message)
| diff --git a/tests/test_client.py b/tests/test_client.py
index bf7551b..ebf2f2a 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1,8 +1,10 @@
import pytest
import responses
+from requests.exceptions import HTTPError
+
from elmo.api.client import ElmoClient
-from elmo.api.exceptions import APIException, PermissionDenied, LockNotAcquired
+from elmo.api.exceptions import PermissionDenied, LockNotAcquired
def test_client_constructor():
@@ -57,7 +59,7 @@ def test_client_auth_unknown_error(server, client):
responses.POST, "https://example.com/vendor", body="Server Error", status=500
)
- with pytest.raises(APIException):
+ with pytest.raises(HTTPError):
client.auth("test", "test")
assert client._session_id is None
assert len(server.calls) == 1
@@ -98,7 +100,7 @@ def test_client_lock_forbidden(server, client, mocker):
mocker.patch.object(client, "unlock")
client._session_id = "test"
- with pytest.raises(PermissionDenied):
+ with pytest.raises(HTTPError):
with client.lock("test"):
pass
assert len(server.calls) == 1
@@ -116,7 +118,7 @@ def test_client_lock_unknown_error(server, client, mocker):
mocker.patch.object(client, "unlock")
client._session_id = "test"
- with pytest.raises(APIException):
+ with pytest.raises(HTTPError):
with client.lock(None):
pass
assert len(server.calls) == 1
@@ -186,7 +188,7 @@ def test_client_unlock_fails_forbidden(server, client):
client._session_id = "test"
client._lock.acquire()
- with pytest.raises(PermissionDenied):
+ with pytest.raises(HTTPError):
client.unlock()
assert not client._lock.acquire(False)
assert len(server.calls) == 1
@@ -210,7 +212,7 @@ def test_client_unlock_fails_unexpected_error(server, client):
client._session_id = "test"
client._lock.acquire()
- with pytest.raises(APIException):
+ with pytest.raises(HTTPError):
client.unlock()
assert not client._lock.acquire(False)
assert len(server.calls) == 1
@@ -266,7 +268,7 @@ def test_client_arm_fails_missing_session(server, client):
client._session_id = "test"
client._lock.acquire()
- with pytest.raises(PermissionDenied):
+ with pytest.raises(HTTPError):
client.arm()
assert len(server.calls) == 1
@@ -282,7 +284,7 @@ def test_client_arm_fails_unknown_error(server, client):
client._session_id = "test"
client._lock.acquire()
- with pytest.raises(APIException):
+ with pytest.raises(HTTPError):
client.arm()
assert len(server.calls) == 1
@@ -337,7 +339,7 @@ def test_client_disarm_fails_missing_session(server, client):
client._session_id = "test"
client._lock.acquire()
- with pytest.raises(PermissionDenied):
+ with pytest.raises(HTTPError):
client.disarm()
assert len(server.calls) == 1
@@ -353,6 +355,6 @@ def test_client_disarm_fails_unknown_error(server, client):
client._session_id = "unknown"
client._lock.acquire()
- with pytest.raises(APIException):
+ with pytest.raises(HTTPError):
client.disarm()
assert len(server.calls) == 1
| Remove boilerplate in ElmoClient
### Overview
There is some code duplication in `ElmoClient` public functions. Most of the code is always an API call with error checking. Probably we should refactor the code with some internal functions that are used across all methods.
| 2019-11-16T22:52:03.000 | -1.0 | [
"tests/test_client.py::test_client_unlock_fails_unexpected_error",
"tests/test_client.py::test_client_arm_fails_unknown_error",
"tests/test_client.py::test_client_arm_fails_missing_session",
"tests/test_client.py::test_client_auth_unknown_error",
"tests/test_client.py::test_client_lock_forbidden",
"tests/test_client.py::test_client_disarm_fails_missing_session",
"tests/test_client.py::test_client_lock_unknown_error",
"tests/test_client.py::test_client_disarm_fails_unknown_error",
"tests/test_client.py::test_client_unlock_fails_forbidden"
] | [
"tests/test_client.py::test_client_disarm_fails_missing_lock",
"tests/test_client.py::test_client_auth_success",
"tests/test_client.py::test_client_auth_forbidden",
"tests/test_client.py::test_client_lock_calls_unlock",
"tests/test_client.py::test_client_constructor_with_session_id",
"tests/test_client.py::test_client_lock",
"tests/test_client.py::test_client_arm",
"tests/test_client.py::test_client_disarm",
"tests/test_client.py::test_client_arm_fails_missing_lock",
"tests/test_client.py::test_client_unlock_fails_missing_lock",
"tests/test_client.py::test_client_constructor",
"tests/test_client.py::test_client_unlock"
] |
|
palazzem/econnect-python | 38 | palazzem__econnect-python-38 | ['34'] | 4c160ffe57e1b6d61fa6dbaacac54bca7fbbe9df | diff --git a/elmo/api/client.py b/elmo/api/client.py
index fe44491..42afed7 100644
--- a/elmo/api/client.py
+++ b/elmo/api/client.py
@@ -26,10 +26,10 @@ class ElmoClient(object):
c.disarm() # Disarm all alarms
"""
- def __init__(self, base_url, vendor):
+ def __init__(self, base_url, vendor, session_id=None):
self._router = Router(base_url, vendor)
self._session = Session()
- self._session_id = None
+ self._session_id = session_id
self._lock = Lock()
def auth(self, username, password):
| diff --git a/tests/test_client.py b/tests/test_client.py
index 8dcdb03..bf7551b 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -1,9 +1,24 @@
import pytest
import responses
+from elmo.api.client import ElmoClient
from elmo.api.exceptions import APIException, PermissionDenied, LockNotAcquired
+def test_client_constructor():
+ """Should build the client using the base URL and the vendor suffix."""
+ client = ElmoClient("https://example.com", "vendor")
+ assert client._router._base_url == "https://example.com"
+ assert client._router._vendor == "vendor"
+ assert client._session_id is None
+
+
+def test_client_constructor_with_session_id():
+ """Should build the client with a provided `session_id`."""
+ client = ElmoClient("https://example.com", "vendor", session_id="test")
+ assert client._session_id == "test"
+
+
def test_client_auth_success(server, client):
"""Should authenticate with valid credentials."""
html = """<script type="text/javascript">
| Extend ElmoClient constructor
### Overview
If a new `ElmoClient` must be created, the only way to set the underlying access token is to initialize the client and access an internal attribute:
```python
from elmo.api.client import ElmoClient
c = ElmoClient()
c._session_id = "test"
```
Would be better if a kwarg is available:
```python
from elmo.api.client import ElmoClient
c = ElmoClient(session_id="test)
```
| 2019-11-16T22:26:52.000 | -1.0 | [
"tests/test_client.py::test_client_constructor_with_session_id"
] | [
"tests/test_client.py::test_client_auth_success",
"tests/test_client.py::test_client_unlock_fails_missing_lock",
"tests/test_client.py::test_client_unlock",
"tests/test_client.py::test_client_unlock_fails_unexpected_error",
"tests/test_client.py::test_client_arm_fails_unknown_error",
"tests/test_client.py::test_client_auth_unknown_error",
"tests/test_client.py::test_client_auth_forbidden",
"tests/test_client.py::test_client_lock",
"tests/test_client.py::test_client_disarm_fails_missing_session",
"tests/test_client.py::test_client_lock_unknown_error",
"tests/test_client.py::test_client_disarm_fails_unknown_error",
"tests/test_client.py::test_client_lock_calls_unlock",
"tests/test_client.py::test_client_arm",
"tests/test_client.py::test_client_lock_forbidden",
"tests/test_client.py::test_client_arm_fails_missing_lock",
"tests/test_client.py::test_client_constructor",
"tests/test_client.py::test_client_arm_fails_missing_session",
"tests/test_client.py::test_client_disarm_fails_missing_lock",
"tests/test_client.py::test_client_disarm",
"tests/test_client.py::test_client_unlock_fails_forbidden"
] |
|
khirotaka/enchanter | 52 | khirotaka__enchanter-52 | ['47', '51'] | e6b80ceceb3fe10ee3c5fc70f5171792c95c6779 | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8cf7e79
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,59 @@
+# Table of contents
+* [Contributing to Enchanter](#Contributing-to-Enchanter)
+* [Developing Enchanter](#Developing-Enchanter)
+* [Writing documentation](#Writing-documentation)
+
+## Contributing to Enchanter
+If you are interested in contributing to Enchanter, your contributions will fall into two categories:
+
+1. You want to propose a new feature and implement it.
+Post about your intended feature, and we shall discuss the design and implementation.
+Once we agree that the plan looks good, go ahead and implement it.
+
+2. You want to implement a feature or bug-fix for an outstanding issue.
+ * Search for your issue here: [https://github.com/khirotaka/enchanter/issues](https://github.com/khirotaka/enchanter/issues)
+ * Pick an issue and comment on the task that you want to work on this feature.
+ * If you need more context on a particular issue, please ask and we shall provide.
+
+## Developing Enchanter
+To develop Enchanter on your machine
+
+1. Clone a copy of Enchanter from source:
+```shell script
+git clone https://github.com/khirotaka/enchanter.git
+cd enchanter
+```
+
+1.1 If you already have Enchanter from source, update it:
+```shell script
+git pull --rebase
+git submodule sync --recursive
+git submodule update --init --recursive
+```
+
+and install Enchanter on develop mode.
+
+```shell script
+python setup.py develop
+```
+
+If you want to reinstall, make sure that you uninstall Enchanter first by running `pip uninstall enchanter` and
+`python setup.py clearn`. Then you can install in develop mode again.
+
+## Writing documentation
+Enchanter uses Google style for formatting docstrings.
+
+### Building documentation
+To build the documentation
+
+1. Build and install Enchanter
+2. Install the requirements
+```shell script
+cd docs/
+pip install -r requirements.txt
+```
+3. Generate the documentation HTML files.
+
+```shell script
+make html
+```
diff --git a/enchanter/__version__.py b/enchanter/__version__.py
index 60501de..7628237 100644
--- a/enchanter/__version__.py
+++ b/enchanter/__version__.py
@@ -1,1 +1,1 @@
-__version__ = "0.5.1-rc1"
+__version__ = "0.5.1-rc2"
diff --git a/enchanter/engine/runner.py b/enchanter/engine/runner.py
index c54692d..ef5bd7b 100644
--- a/enchanter/engine/runner.py
+++ b/enchanter/engine/runner.py
@@ -178,10 +178,11 @@ def train_cycle(self, epoch, loader):
outputs["loss"].backward()
self.optimizer.step()
- per = "{:1.0%}".format(step / loader_size)
- self.pbar.set_postfix(
- OrderedDict(train_batch=per), refresh=True
- )
+ if hasattr(self.pbar, "set_postfix"):
+ per = "{:1.0%}".format(step / loader_size)
+ self.pbar.set_postfix(
+ OrderedDict(train_batch=per), refresh=True
+ )
outputs = {
key: outputs[key].detach().cpu() if isinstance(outputs[key], torch.Tensor) else outputs[key]
@@ -219,10 +220,11 @@ def val_cycle(self, epoch, loader):
# on_step_start()
outputs = self.val_step(batch) # pylint: disable=E1111
- per = "{:1.0%}".format(step / loader_size)
- self.pbar.set_postfix(
- OrderedDict(val_batch=per), refresh=True
- )
+ if hasattr(self.pbar, "set_postfix"):
+ per = "{:1.0%}".format(step / loader_size)
+ self.pbar.set_postfix(
+ OrderedDict(val_batch=per), refresh=True
+ )
outputs = {
key: outputs[key].cpu() if isinstance(outputs[key], torch.Tensor) else outputs[key]
@@ -260,9 +262,11 @@ def test_cycle(self, loader):
outputs = self.test_step(batch) # pylint: disable=E1111
per = "{:1.0%}".format(step / loader_size)
- self.pbar.set_postfix(
- OrderedDict(test_batch=per), refresh=True
- )
+ if hasattr(self.pbar, "set_postfix"):
+ self.pbar.set_postfix(
+ OrderedDict(test_batch=per), refresh=True
+ )
+ self.pbar.update(1)
outputs = {
key: outputs[key].cpu() if isinstance(outputs[key], torch.Tensor) else outputs[key]
@@ -279,13 +283,12 @@ def test_cycle(self, loader):
self._metrics.update(dic)
self.experiment.log_metrics(dic)
- def train_config(self, epochs, *args, **kwargs):
+ def train_config(self, epochs, **kwargs):
"""
.run() メソッドを用いて訓練を行う際に、 epochs などを指定する為のメソッドです。
Args:
epochs (int):
- *args:
**kwargs:
Returns:
@@ -369,7 +372,7 @@ def run(self, verbose=True):
if self.scheduler:
self.scheduler.step(epoch=None)
- self.experiment.log_metric("scheduler_lr", self.scheduler.get_last_lr(), epoch=epoch)
+ self.experiment.log_metric("scheduler_lr", self.scheduler.get_lr(), epoch=epoch)
if self.early_stop:
if self.early_stop.on_epoch_end(self._metrics, epoch):
@@ -381,6 +384,7 @@ def run(self, verbose=True):
if "test" in self.loaders:
# on_test_start()
+ self.pbar = tqdm(total=len(self.loaders["test"]), desc="Evaluating") if verbose else None
self.test_cycle(self.loaders["test"])
# on_test_end()
diff --git a/enchanter/engine/runner.pyi b/enchanter/engine/runner.pyi
index f8271ac..352cd50 100644
--- a/enchanter/engine/runner.pyi
+++ b/enchanter/engine/runner.pyi
@@ -45,7 +45,7 @@ class BaseRunner(base.BaseEstimator, ABC, metaclass=abc.ABCMeta):
def train_cycle(self, epoch: int, loader: DataLoader) -> None: ...
def val_cycle(self, epoch: int, loader: DataLoader) -> None: ...
def test_cycle(self, loader: DataLoader) -> None: ...
- def train_config(self, epochs: int, *args: Any, **kwargs: Any) -> None: ...
+ def train_config(self, epochs: int, **kwargs: Any) -> None: ...
def log_hyperparams(self, dic: Dict=..., prefix: str=...) -> None: ...
def initialize(self) -> None: ...
def run(self, verbose: bool = ...) -> None: ...
diff --git a/setup.py b/setup.py
index 202d408..cc3ec9a 100644
--- a/setup.py
+++ b/setup.py
@@ -24,7 +24,7 @@ def load_requirements(path_dir=PATH_ROOT, comment_char='#'):
setup(
name='enchanter',
- version='0.5.1-rc1',
+ version='0.5.1-rc2',
packages=[
'enchanter', 'enchanter.addons', 'enchanter.addons.layers',
'enchanter.callbacks', 'enchanter.engine', 'enchanter.metrics',
| diff --git a/tests/engine/test_custom_runner.py b/tests/engine/test_custom_runner.py
index c26d4db..99dcdfb 100644
--- a/tests/engine/test_custom_runner.py
+++ b/tests/engine/test_custom_runner.py
@@ -75,6 +75,23 @@ def test_custom_runner_1():
def test_custom_runner_2():
runner = Runner2()
+ ds = enchanter.engine.modules.get_dataset(X, Y)
+ loader = DataLoader(ds, batch_size=32)
+
+ try:
+ runner.add_loader("test", loader)
+ runner.run()
+ is_pass = True
+
+ except Exception as e:
+ print(e)
+ is_pass = False
+
+ assert is_pass
+
+
+def test_custom_runner_3():
+ runner = Runner2()
ds = enchanter.engine.modules.get_dataset(X, Y)
loader = DataLoader(ds, batch_size=32)
| バッチ内にtorch.Tensor以外を含むとエラーを起こす
バッチ内にtorch.Tensor以外を含むとエラーを起こす
Test DataLoaderだけで実行するとエラーが発生する
| 2020-05-10T08:43:35.000 | -1.0 | [
"tests/engine/test_custom_runner.py::test_custom_runner_2"
] | [
"tests/engine/test_custom_runner.py::test_custom_runner_3",
"tests/engine/test_custom_runner.py::test_custom_runner_1"
] |
|
langmuirproject/langmuir | 35 | langmuirproject__langmuir-35 | ['34'] | 2f315ab4a8d7bf7e9ff032f34d4084651de83f7b | diff --git a/langmuir/analytical.py b/langmuir/analytical.py
index 42fd7b1..5af1528 100644
--- a/langmuir/analytical.py
+++ b/langmuir/analytical.py
@@ -27,6 +27,8 @@
from scipy.special import gamma, erfc, hyp2f1
from copy import deepcopy
import numpy as np
+import warnings
+
def normalization_current(geometry, species):
"""
@@ -144,7 +146,7 @@ def OML_current(geometry, species, V=None, eta=None, normalization=None):
charge and temperature and k is Boltzmann's constant.
normalization: 'th', 'thmax', None
- Wether to normalize the output current by, respectively, the thermal
+ Whether to normalize the output current by, respectively, the thermal
current, the Maxwellian thermal current, or not at all, i.e., current
in [A/m].
@@ -187,16 +189,43 @@ def OML_current(geometry, species, V=None, eta=None, normalization=None):
indices_n = np.where(eta < 0)[0] # indices for repelled particles
indices_p = np.where(eta >= 0)[0] # indices for attracted particles
+ if kappa < 1.5:
+ warnings.warn("kappa < 1.5 may result in invalid values for the computed OML current.")
+
if kappa == float('inf'):
C = 1.0
D = (1.+24*alpha)/(1.+15*alpha)
E = 4.*alpha/(1.+24*alpha)
F = (1.+8*alpha)/(1.+24*alpha)
else:
+ # Note: Problematic kappa values in the expression for C:
+ # - RuntimeWarning: if kappa < 1.5, then numpy.sqrt returns nan, without throwing any exceptions
C = np.sqrt(kappa-1.5)*gamma(kappa-1.)/gamma(kappa-0.5)
- D = (1.+24*alpha*((kappa-1.5)**2/((kappa-2.)*(kappa-3.))))/(1.+15*alpha*((kappa-1.5)/(kappa-2.5)))
- E = 4.*alpha*kappa*(kappa-1.)/( (kappa-2.)*(kappa-3.)+24*alpha*(kappa-1.5)**2 )
- F = ((kappa-1.)*(kappa-2.)*(kappa-3.)+8*alpha*(kappa-3.)*(kappa-1.5)**2) /( (kappa-2.)*(kappa-3.)*(kappa-1.5)+24*alpha*(kappa-1.5)**3 )
+ if alpha == 0:
+ # Problematic kappa values:
+ # - ZeroDivisionError for kappa= 1.5
+ if kappa == 1.5:
+ raise ValueError("Invalid value: for alpha = 0, kappa cannot be 3/2.")
+ D = 1.
+ E = 0.
+ F = (kappa-1.) / (kappa-1.5)
+ else:
+ # Note: Problematic kappa values:
+ # - in D:
+ # - ZeroDivisionError for kappa = 2.0, 2.5, 3.0
+ # - in E:
+ # - nan for kappa = [5+72*alpha pm sqrt(1-72*alpha)] / [2*(1+24*alpha)]
+ # - in F:
+ # - ZeroDivisionError for kappa = 1.5
+ # - nan for kappa = [5+72*alpha pm sqrt(1-72*alpha)] / [2*(1+24*alpha)]
+ if kappa in [1.5, 2.0, 2.5, 3.0]:
+ raise ValueError("Invalid value: for alpha > 0, kappa cannot be 1.5, 2.0, 2.5, or, 3.0")
+
+ D = (1. + 24 * alpha * ((kappa - 1.5) ** 2 / ((kappa - 2.) * (kappa - 3.)))) / (
+ 1. + 15 * alpha * ((kappa - 1.5) / (kappa - 2.5)))
+ E = 4. * alpha * kappa * (kappa - 1.) / ((kappa - 2.) * (kappa - 3.) + 24 * alpha * (kappa - 1.5) ** 2)
+ F = ((kappa - 1.) * (kappa - 2.) * (kappa - 3.) + 8 * alpha * (kappa - 3.) * (kappa - 1.5) ** 2) / (
+ (kappa - 2.) * (kappa - 3.) * (kappa - 1.5) + 24 * alpha * (kappa - 1.5) ** 3)
if normalization is None:
I0 = normalization_current(geometry, species)
@@ -215,6 +244,10 @@ def OML_current(geometry, species, V=None, eta=None, normalization=None):
I[indices_n] = I0 * C * D * np.exp(eta[indices_n]) * (1. + E * -eta[indices_n] * (-eta[indices_n] + 4.))
else:
+ # Note: Problematic kappa values:
+ # - ZeroDivisionError for kappa = 1.0, 1.5
+ if kappa in [1.0, 1.5]:
+ raise ValueError("Invalid value: kappa cannot be 1.0 or 1.5")
I[indices_n] = I0 * C * D * (1. - eta[indices_n] / (kappa - 1.5))**(
1. - kappa) * (1. + E * (-eta[indices_n]) * (-eta[indices_n] + 4. * ((kappa - 1.5) / (kappa - 1.))))
@@ -231,6 +264,11 @@ def OML_current(geometry, species, V=None, eta=None, normalization=None):
(-eta[indices_n]) * (-eta[indices_n] + 4.))
else:
+ # Note: Problematic kappa values:
+ # - ZeroDivisionError for kappa = 1.0, 1.5
+ if kappa in [1.0, 1.5]:
+ raise ValueError("Invalid value: kappa cannot be 1.0 or 1.5")
+
I[indices_n] = I0 * C * D * (1. - eta[indices_n] / (kappa - 1.5))**(
1. - kappa) * (1. + E * (-eta[indices_n]) * (-eta[indices_n] + 4. * ((kappa - 1.5) / (kappa - 1.))))
@@ -242,17 +280,38 @@ def OML_current(geometry, species, V=None, eta=None, normalization=None):
np.exp(eta[indices_p]) * (1. + E * eta[indices_p] * (eta[indices_p] - 4.)) * erfc(np.sqrt(eta[indices_p])))
else:
+ # Note: Problematic kappa values in the expression for C:
+ # - RuntimeWarning: if kappa < 1.5, then numpy.sqrt returns nan, without throwing any exceptions
C = np.sqrt(kappa - 1.5) * (kappa - .5) / (kappa - 1.0)
- D = (1. + 3 * alpha * ((kappa - 1.5) / (kappa - 0.5))) / \
- (1. + 15 * alpha * ((kappa - 1.5) / (kappa - 2.5)))
- E = 4. * alpha * kappa * \
- (kappa - 1.) / ((kappa - .5) *
- (kappa - 1.5) + 3. * alpha * (kappa - 1.5)**2)
-
- I[indices_p] = (2./np.sqrt(np.pi))*I0 * C * D * (eta[indices_p]/(kappa-1.5))**(1.-kappa) * \
- (((kappa - 1.) / (kappa - 3.)) * E * (eta[indices_p]**2) * hyp2f1(kappa - 3, kappa + .5, kappa - 2., 1. - (kappa - 1.5) / (eta[indices_p])) + \
- ((kappa - 1.5 - 2. * (kappa - 1.) * eta[indices_p]) / (kappa - 2.)) * E * eta[indices_p] * hyp2f1(kappa - 2, kappa + .5, kappa - 1., 1. - (kappa - 1.5) / (eta[indices_p])) +
- (1. + E * eta[indices_p] * (eta[indices_p]-((kappa-1.5)/(kappa-1.)))) * hyp2f1(kappa - 1., kappa + .5, kappa, 1. - (kappa - 1.5) / (eta[indices_p])))
+ if alpha == 0:
+ # Note: Problematic kappa values:
+ # - ZeroDivisionError for kappa = 1.5
+ if kappa == 1.5:
+ raise ValueError("Invalid value: kappa cannot be 3/2.")
+ I[indices_p] = (2. / np.sqrt(np.pi)) * I0 * C
+ I[indices_p] *= (eta[indices_p] / (kappa - 1.5)) ** (1. - kappa)
+ I[indices_p] *= hyp2f1(kappa - 1., kappa + .5, kappa, 1. - (kappa - 1.5) / (eta[indices_p]))
+ else:
+ # Note: Problematic kappa values:
+ # - in D:
+ # - ZeroDivisionError for kappa = 0.5 and 2.5
+ # - in E:
+ # - ZeroDivisionError for kappa = 1.5 and kappa = 0.5*((1+9*alpha)/(1+3*alpha))
+ # - in the expression for I[indices_p]:
+ # - ZeroDivisionError for kappa = 1.0, 1.5, 2.0, 3.0
+ if kappa in [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 0.5*(1.+9.*alpha)/(1.+3.*alpha)]:
+ raise ValueError("Invalid value: for alpha > 0, kappa cannot be " + str(kappa))
+
+ D = (1. + 3 * alpha * ((kappa - 1.5) / (kappa - 0.5))) / \
+ (1. + 15 * alpha * ((kappa - 1.5) / (kappa - 2.5)))
+ E = 4. * alpha * kappa * \
+ (kappa - 1.) / ((kappa - .5) *
+ (kappa - 1.5) + 3. * alpha * (kappa - 1.5)**2)
+
+ I[indices_p] = (2./np.sqrt(np.pi))*I0 * C * D * (eta[indices_p]/(kappa-1.5))**(1.-kappa) * \
+ (((kappa - 1.) / (kappa - 3.)) * E * (eta[indices_p]**2) * hyp2f1(kappa - 3, kappa + .5, kappa - 2., 1. - (kappa - 1.5) / (eta[indices_p])) + \
+ ((kappa - 1.5 - 2. * (kappa - 1.) * eta[indices_p]) / (kappa - 2.)) * E * eta[indices_p] * hyp2f1(kappa - 2, kappa + .5, kappa - 1., 1. - (kappa - 1.5) / (eta[indices_p])) +
+ (1. + E * eta[indices_p] * (eta[indices_p]-((kappa-1.5)/(kappa-1.)))) * hyp2f1(kappa - 1., kappa + .5, kappa, 1. - (kappa - 1.5) / (eta[indices_p])))
else:
raise ValueError('Geometry not supported: {}'.format(geometry))
diff --git a/langmuir/species.py b/langmuir/species.py
index 79c1d2b..db0f133 100644
--- a/langmuir/species.py
+++ b/langmuir/species.py
@@ -117,6 +117,10 @@ def __init__(self, **kwargs):
if self.kappa == float('inf'):
self.debye = np.sqrt(eps0*k*self.T/(self.q**2*self.n))*np.sqrt((1.0 + 15.0*self.alpha)/(1.0 + 3.0*self.alpha))
else:
+ # Note: Problematic kappa values:
+ # - ZeroDivisionError for kappa = 1.0, 1.5
+ if self.kappa in [0.5, 2.5]:
+ raise ValueError("Invalid value: kappa cannot be 0.5 or 2.5")
self.debye = np.sqrt(eps0 * k * self.T / (self.q**2 * self.n)) *\
np.sqrt(((self.kappa - 1.5) / (self.kappa - 0.5)) *\
((1.0 + 15.0 * self.alpha * ((self.kappa - 1.5) / (self.kappa - 2.5))) / (1.0 + 3.0 * self.alpha * ((self.kappa - 1.5) / (self.kappa - 0.5)))))
| diff --git a/langmuir/test_analytical.py b/langmuir/test_analytical.py
index 30e25bb..f014d81 100644
--- a/langmuir/test_analytical.py
+++ b/langmuir/test_analytical.py
@@ -190,6 +190,34 @@ def test_OML_current_kappa_cairns():
I = OML_current(geo, sp_k, eta=-5)
assert(I == approx(-2.26604e-11))
+
[email protected]("kappa, alpha, eta", [(.5, 0, 5), (.5, 0.2, 5), (.5, 0, -5), (.5, 0.2, -5),
+ (1., 0, 5), (1., 0.2, 5), (1., 0, -5), (1., 0.2, -5),
+ (1.5, 0, 5), (1.5, 0, -5), (1.5, 0, -5), (1.5, 0.2, -5),
+ (2.0, 0, 5), (2, 0.2, 5), (2, 0, -5), (2, 0.2, -5),
+ (2.5, 0, 5), (2.5, 0.2, 5), (2.5, 0, -5), (2.5, 0.2, -5),
+ (3, 0, 5), (3, 0.2, 5), (3, 0, -5), (3, 0.2, -5)])
+def test_valid_kappa_and_alpha_values(kappa, alpha, eta):
+ if kappa in [0.5, 2.5]:
+ with pytest.raises(ValueError):
+ Electron(n=1e11, T=1000, kappa=kappa, alpha=alpha)
+ return
+ else:
+ sp = Electron(n=1e11, T=1000, kappa=kappa, alpha=alpha)
+
+ geometries = [Cylinder(0.255e-3, 25e-3), Sphere(0.255e-3)]
+ for geo in geometries:
+ if alpha == 0:
+ if kappa in [1., 1.5]:
+ with pytest.raises(ValueError):
+ OML_current(geo, sp, eta=eta)
+ else:
+ assert OML_current(geo, sp, eta=eta)
+ else:
+ with pytest.raises(ValueError):
+ OML_current(geo, sp, eta=eta)
+
+
def test_jacobsen_density_identity():
# Tests that the Jacobsen methods agrees perfectly with OML
n = [1e11, 5e11, 1e12]
diff --git a/langmuir/test_species.py b/langmuir/test_species.py
index 6aa99db..80a9e9c 100644
--- a/langmuir/test_species.py
+++ b/langmuir/test_species.py
@@ -155,3 +155,9 @@ def test_debye():
def test_negative_temperature(caplog):
sp = Species(n=1e11, T=-1)
assert(caplog.records[0].levelname == 'WARNING')
+
+
[email protected]("kappa, alpha", [(.5, 0), (.5, 0.2), (2.5, 0), (2.5, 0.2)])
+def test_invalid_kappa_values(kappa, alpha):
+ with pytest.raises(ValueError):
+ Electron(n=1e11, T=1000, kappa=kappa, alpha=alpha)
| kappa = 2 or 3 fails
Electrons with kappa = 2 or 3 leads to divide-by-zero when using finite_radius_current
| On closer inspection, kappa<4 is not valid for `finite_radius_current`, because it is outside the domain of tabulated values. kappe=4, kappa=6, and kappa=inf are the tabulation points for kappa. However, the error also occur in `OML_current`, which, should be valid for kappa>D/2+1, where D is the number of dimensions, e.g. kappa>2.5 for spheres, and kappa>2 for cylinders. `finite_radius_current` uses `OML_current` internally, so probably it is enough to fix `OML_current`.
Here is an example:
```
In [82]: OML_current(Sphere(r=1e-2), Electron(kappa=3+1e-5), eta=10)
Out[82]: -1.305821017623522e-05
In [83]: OML_current(Sphere(r=1e-2), Electron(kappa=3-1e-5), eta=10)
Out[83]: -1.3058236835311985e-05
In [84]: OML_current(Sphere(r=1e-2), Electron(kappa=3), eta=10)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-84-9e851f1ac3f1> in <module>
----> 1 OML_current(Sphere(r=1e-2), Electron(kappa=3), eta=10)
~/Codes/langmuir/langmuir/analytical.py in OML_current(geometry, species, V, eta, normalization)
195 else:
196 C = np.sqrt(kappa-1.5)*gamma(kappa-1.)/gamma(kappa-0.5)
--> 197 D = (1.+24*alpha*((kappa-1.5)**2/((kappa-2.)*(kappa-3.))))/(1.+15*alpha*((kappa-1.5)/(kappa-2.5)))
198 E = 4.*alpha*kappa*(kappa-1.)/( (kappa-2.)*(kappa-3.)+24*alpha*(kappa-1.5)**2 )
199 F = ((kappa-1.)*(kappa-2.)*(kappa-3.)+8*alpha*(kappa-3.)*(kappa-1.5)**2) /( (kappa-2.)*(kappa-3.)*(kappa-1.5)+24*alpha*(kappa-1.5)**3 )
ZeroDivisionError: float division by zero
```
Although there is a divide-by-zero for kappa=3, the analytical expression used in `OML_current` clearly has a finite value when taking the limit as kappa tends towards 3. Looking at the analytical expressions in the paper, there are a lot of denominators with expressions like (kappa-3), (kappa-2.5) and so forth.
Perhaps one way to proceed would be to first make pytests that `OML_current` and `finite_radius_current` shouldn't throw divide-by-zero when exposed to such kappa-values, and then to correct `OML_current` by implementing limiting cases. Tests should exist for both sphere and cylinder, and both positive and negative `eta`. | 2021-08-29T20:36:19.000 | -1.0 | [
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2.5-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2.5-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[0.5-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.0-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[3-0.2-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.5-0--5_0]",
"langmuir/test_species.py::test_invalid_kappa_values[2.5-0.2]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2.5-0--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2-0--5]",
"langmuir/test_species.py::test_invalid_kappa_values[0.5-0]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.0-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.5-0--5_1]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[3-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[0.5-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.5-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.5-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2-0.2-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.0-0.2-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[3-0--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[0.5-0.2-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[1.0-0--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2.0-0-5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[3-0.2--5]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[0.5-0--5]",
"langmuir/test_species.py::test_invalid_kappa_values[0.5-0.2]",
"langmuir/test_analytical.py::test_valid_kappa_and_alpha_values[2.5-0.2-5]",
"langmuir/test_species.py::test_invalid_kappa_values[2.5-0]"
] | [
"langmuir/test_species.py::test_species_Z",
"langmuir/test_species.py::test_species_maxwellian",
"langmuir/test_analytical.py::test_OML_current_cairns",
"langmuir/test_species.py::test_species_convenience_values",
"langmuir/test_species.py::test_species_kappa",
"langmuir/test_species.py::test_species_amu",
"langmuir/test_species.py::test_species_positron",
"langmuir/test_species.py::test_species_defaults",
"langmuir/test_species.py::test_species_electron",
"langmuir/test_analytical.py::test_thermal_OML_current_maxwellian_normalized",
"langmuir/test_analytical.py::test_OML_current_not_normalized",
"langmuir/test_species.py::test_species_convenience_methods",
"langmuir/test_species.py::test_negative_temperature",
"langmuir/test_analytical.py::test_thermal_current_cairns_normalized",
"langmuir/test_species.py::test_species_repr",
"langmuir/test_analytical.py::test_normalization_current_multiple_species",
"langmuir/test_analytical.py::test_thermal_current_maxwellian_normalized",
"langmuir/test_species.py::test_species_kappa_cairns",
"langmuir/test_analytical.py::test_normalization_current",
"langmuir/test_species.py::test_species_cairns",
"langmuir/test_species.py::test_species_eV",
"langmuir/test_species.py::test_species_debye_length",
"langmuir/test_analytical.py::test_jacobsen_density_shape_mismatch",
"langmuir/test_analytical.py::test_jacobsen_density_identity",
"langmuir/test_species.py::test_species_m",
"langmuir/test_species.py::test_species_proton",
"langmuir/test_analytical.py::test_OML_current_kappa_cairns",
"langmuir/test_analytical.py::test_jacobsen_density_geometry",
"langmuir/test_analytical.py::test_thermal_current_kappa_normalized",
"langmuir/test_analytical.py::test_thermal_current_kappa_cairns_normalized",
"langmuir/test_species.py::test_debye",
"langmuir/test_species.py::test_species_vth",
"langmuir/test_analytical.py::test_OML_current_maxwellian",
"langmuir/test_species.py::test_species_q"
] |
zobayer1/logging-extras | 20 | zobayer1__logging-extras-20 | ['16'] | a9c213a5099ee0b72c54dc2842ef8d394b2a3aeb | diff --git a/.github/ISSUE_TEMPLATE/BUG.md b/.github/ISSUE_TEMPLATE/BUG.md
new file mode 100644
index 0000000..58d29ad
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/BUG.md
@@ -0,0 +1,26 @@
+---
+name: Bug report
+about: Create a bug report.
+title: "[BUG]"
+labels: bug
+---
+
+### TL;DR
+<!-- Describe the bug in 1-2 sentences. -->
+
+**Expected behavior**
+<!-- What did you expect to happen? -->
+
+**Observed behavior**
+<!-- What did happened instead? -->
+
+### Reproduction
+<!-- What did you do? Provide a list of steps taken. -->
+
+**Environment**
+<!-- Complete the following information about your environment. -->
+- OS: (e.g. Centos 7.5)
+- Python: (e.g. 3.8)
+
+**Additional information**
+<!-- Are you doing something out of the ordinary? -->
diff --git a/.github/ISSUE_TEMPLATE/FEATURE.md b/.github/ISSUE_TEMPLATE/FEATURE.md
new file mode 100644
index 0000000..9bfc4b7
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/FEATURE.md
@@ -0,0 +1,28 @@
+---
+name: Feature plan
+about: Tasks describing a feature.
+title: "[FEATURE]"
+labels: feature
+---
+
+### TL;DR
+<!-- Describe the feature in 1-2 sentences. -->
+
+### Design
+
+**Tasks Breakdown**
+<!-- Tasks for this feature with algorithm description -->
+
+**Depends On**
+<!-- List of dependencies for this feature -->
+
+**Required For**
+<!-- List of tasks depending on this feature -->
+
+**Additional information**
+<!-- Are you doing something out of the ordinary? -->
+
+### Testing
+
+**Testing Scenarios**
+<!-- Testing checklist for this feature -->
diff --git a/.github/ISSUE_TEMPLATE/IMPROVE.md b/.github/ISSUE_TEMPLATE/IMPROVE.md
new file mode 100644
index 0000000..4966a65
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/IMPROVE.md
@@ -0,0 +1,23 @@
+---
+name: Feature request
+about: Suggest an improvement idea.
+title: "[IMPROVE]"
+labels: enhancement
+---
+
+### TL;DR
+<!-- Describe the feature in 1-2 sentences. -->
+
+### Design
+
+**Proposal**
+<!-- Provide more detail on the proposal. What would it look like? -->
+
+**Alternatives considered**
+<!-- Have you explored other ways to solve this? -->
+
+**Resources**
+<!-- Please provide links to relevant documentation or examples. -->
+
+**Additional information**
+<!-- Are you doing something out of the ordinary? -->
diff --git a/.github/ISSUE_TEMPLATE/QUESTION.md b/.github/ISSUE_TEMPLATE/QUESTION.md
new file mode 100644
index 0000000..ee034cc
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/QUESTION.md
@@ -0,0 +1,10 @@
+---
+name: Question
+about: Ask us a question.
+title: "[QUESTION]"
+labels: question
+---
+
+### Question
+<!-- Ask your question in 1-2 sentences. -->
+<!-- If you're sharing code, please use ``` codeblocks -->
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..cdc6631
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,13 @@
+### Related Issues
+<!-- List of related issues -->
+
+### Proposed Changes
+<!-- List of changes made in this PR -->
+
+**Additional information**
+<!-- Are you doing something out of the ordinary? -->
+
+### Checklist
+- [ ] Tests
+- [ ] Coverages
+- [ ] Documentations
diff --git a/.github/SECURITY.md b/.github/SECURITY.md
new file mode 100644
index 0000000..3fb6d91
--- /dev/null
+++ b/.github/SECURITY.md
@@ -0,0 +1,3 @@
+# Security Policy
+
+To report a suspected vulnerability, please [create a bug report](https://github.com/zobayer1/logging-extras/issues) and include the steps to produce the vulnerability.
diff --git a/.gitignore b/.gitignore
index 3417b4e..80675aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -115,6 +115,7 @@ venv/
ENV/
env.bak/
venv.bak/
+requirements.txt
# Spyder project settings
.spyderproject
diff --git a/README.md b/README.md
index 0eb897a..54098fd 100644
--- a/README.md
+++ b/README.md
@@ -4,10 +4,10 @@ LOGGING EXTRAS
A collection of various python logging extensions.
[](https://www.python.org)
-[](https://github.com/pre-commit/pre-commit)
-
-
+[](https://github.com/zobayer1/logging-extras/actions/workflows/python-publish.yml)
+[](https://github.com/zobayer1/logging-extras/actions/workflows/python-package.yml)
[](https://codecov.io/gh/zobayer1/logging-extras)
+[](https://github.com/pre-commit/pre-commit)
[](https://github.com/psf/black)
[](https://logging-extras.readthedocs.io/en/latest/?badge=latest)
[](https://github.com/zobayer1/logging-extras/blob/main/LICENSE)
@@ -43,7 +43,7 @@ Module Index
config.YAMLConfig
-----------------
-YAMLConfig class can be used for loading YAML files with custom tags. This class adds a custom envvar tag to native YAML parser which is used to evaluate environment variables. Supports one or more environment variables in the form of `${VARNAME}` or `${VARNAME:DEFAULT}` within a string. If no default value is specified, empty string is used. Default values can only be treated as plain strings.
+YAMLConfig class can be used for loading YAML files with custom tags. This class adds a custom envvar tag to native YAML parser which is used to evaluate environment variables. Supports one or more environment variables in the form of `${VARNAME}` or `${VARNAME:DEFAULT}` within a string. If no default value is specified, empty string is used. Default values can only be treated as plain strings. YAMLConfig can also expand `~` or `~username` just like shells do, either directly hardcoded in YAML file or passed through environment variables.
### Example configuration:
@@ -197,6 +197,12 @@ Generate documentation from the source with Sphinx:
make html
python -m http.server --directory build/html
+### No `requirements.txt` File
+
+This is a python library package that is compatible with a wide range of Python versions. It does not make much sense to pin dependency versions in a traditional `requirements.txt` file. Instead, this project utilizes modern python packaging paradigms with `pyproject.toml` and `setup.cfg` files. However, sometimes some IDEs (i.e. PyCharm) cannot resolve dependencies without a `requirements.txt` file. To generate a `requirements.txt` file, simply run the following command within your venv:
+
+ pip freeze > requirements.txt
+
### Create Distribution Packages
To create a source and wheel distribution, run:
diff --git a/logging_/__init__.py b/logging_/__init__.py
index 40a96af..879d39b 100644
--- a/logging_/__init__.py
+++ b/logging_/__init__.py
@@ -1,1 +1,10 @@
# -*- coding: utf-8 -*-
+import sys
+
+if sys.version_info < (3, 8): # pragma: no cover
+ # noinspection PyUnresolvedReferences
+ from importlib_metadata import version
+else: # pragma: no cover
+ from importlib.metadata import version
+
+__version__ = version("logging-extras")
diff --git a/logging_/config/yaml_config.py b/logging_/config/yaml_config.py
index d5db6d0..2b6b286 100644
--- a/logging_/config/yaml_config.py
+++ b/logging_/config/yaml_config.py
@@ -13,8 +13,10 @@ class YAMLConfig(object):
This class adds a custom envvar tag to native YAML parser which is used to evaluate environment variables. Supports
one or more environment variables in the form of ``${VARNAME}`` or ``${VARNAME:DEFAULT}`` within a string. If no
- default value is specified, empty string is used. Default values can only be treated as plain strings. Inspired by
- several examples from programcreek: ``https://www.programcreek.com/python/example/11269/yaml.add_constructor``
+ default value is specified, empty string is used. Default values can only be treated as plain strings. YAMLConfig
+ can also expand ``~`` or ``~user`` just like shells do, either directly hardcoded in YAML file or passed through
+ environment variables.Inspired by several examples from programcreek:
+ ``https://www.programcreek.com/python/example/11269/yaml.add_constructor``.
Example configuration::
@@ -36,7 +38,7 @@ class YAMLConfig(object):
_uservar_tag_matcher = re.compile(r"^~(\w*?)/")
def __init__(self, config_yaml: str, **kwargs: Any):
- """Instantiates an YAMLConfig object from configuation string.
+ """Instantiates an YAMLConfig object from configuration string.
Registers implicit resolver for custom tag envvar and adds constructor for the tag. Loads logging config from
parsed dictionary using dictConfig.
@@ -89,24 +91,17 @@ def from_file(cls, filename: str, **kwargs: Any):
return cls("", **kwargs)
def _envvar_constructor(self, _loader: Any, node: Any):
- """Constructor callback method for yaml.
-
- Replaces environment variable name with its value. If it is not set, default value will be set.
-
- Args:
- _loader: the Loader object, unused.
- node: the Node object.
-
- Returns:
- The transformed string.
- """
+ """Replaces environment variable name with its value, or a default."""
def replace_fn(match):
+ print(match.group(0))
envparts = f"{match.group(1)}:".split(":")
return os.environ.get(envparts[0], envparts[1])
- return self._envvar_sub_matcher.sub(replace_fn, node.value)
+ return os.path.expanduser(self._envvar_sub_matcher.sub(replace_fn, node.value))
+
+ @staticmethod
+ def _uservar_constructor(_loader: Any, node: Any):
+ """Expands ~ and ~username into user's home directory like shells do."""
- def _uservar_constructor(self, _loader: Any, node: Any):
- """Similar to _envvar_constructor except it expands ~ and ~username in the way that shells do"""
return os.path.expanduser(node.value)
diff --git a/logging_/handlers/queue_listener_handler.py b/logging_/handlers/queue_listener_handler.py
index 3ca3252..a67199a 100644
--- a/logging_/handlers/queue_listener_handler.py
+++ b/logging_/handlers/queue_listener_handler.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import atexit
from logging import LogRecord
-from logging.config import ConvertingDict, ConvertingList, valid_ident
+import logging.config
from logging.handlers import QueueHandler, QueueListener
from typing import Any
@@ -10,7 +10,7 @@ class QueueListenerHandler(QueueHandler):
"""QueueListenerHandler class for managing a queue listener with configured handlers.
This class sets up a queue listener logger handler with customizable configurations. Inspired by Rob Blackbourn's
- article: ``https://rob-blackbourn.medium.com/how-to-use-python-logging-queuehandler-with-dictconfig-1e8b1284e27a``
+ article: ``https://rob-blackbourn.medium.com/how-to-use-python-logging-queuehandler-with-dictconfig-1e8b1284e27a``.
Example configuration::
@@ -45,7 +45,7 @@ def __init__(self, queue: Any, handlers: Any, respect_handler_level: bool = True
"""Instantiates QueueListenerHandler object.
A simple ``QueueHandler`` subclass implementation utilizing ``QueueListener`` for configured handlers. This is
- helpful for detaching ypur logger handlers from the main processing threads, which reduces the risk of getting
+ helpful for detaching your logger handlers from the main processing threads, which reduces the risk of getting
blocked, for example, when using slower handlers such as smtp, file, or socket handlers.
Args:
@@ -75,24 +75,17 @@ def emit(self, record: LogRecord):
super().emit(record)
@staticmethod
- def _resolve_queue(queue: Any) -> Any:
- """Resolves and evaluates queue object.
+ def _resolve_queue(queue: Any) -> Any: # pragma: no cover
+ """Resolves and evaluates queue object."""
- Args:
- queue: queue object passed via logging.config.dictConfig.
-
- Returns:
- Resolved queue object.
- """
-
- if not isinstance(queue, ConvertingDict):
+ if not isinstance(queue, logging.config.ConvertingDict):
return queue
if "__resolved_value__" in queue:
return queue["__resolved_value__"]
cname = queue.pop("class")
klass = queue.configurator.resolve(cname)
props = queue.pop(".", None)
- kwargs = {k: queue[k] for k in queue if valid_ident(k)}
+ kwargs = {k: queue[k] for k in queue if logging.config.valid_ident(k)}
result = klass(**kwargs)
if props:
for name, value in props.items():
@@ -101,16 +94,9 @@ def _resolve_queue(queue: Any) -> Any:
return result
@staticmethod
- def _resolve_handlers(handlers: Any) -> Any:
- """Resolves and evaluates handler objects.
-
- Args:
- handlers: handler list passed via logging.config.dictConfig.
-
- Returns:
- Resolved handler list.
- """
+ def _resolve_handlers(handlers: Any) -> Any: # pragma: no cover
+ """Resolves and evaluates handler objects."""
- if not isinstance(handlers, ConvertingList):
+ if not isinstance(handlers, logging.config.ConvertingList):
return handlers
return [handlers[i] for i in range(len(handlers))]
diff --git a/setup.cfg b/setup.cfg
index 156f0bf..9cac181 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -6,10 +6,12 @@ norecursedirs = docs dist
[options]
install_requires =
+ importlib-metadata; python_version < "3.8"
PyYAML
[options.extras_require]
dev =
+ pyfakefs
pytest
pytest-cov
tox
| diff --git a/tests/test_config/test_yaml_config.py b/tests/test_config/test_yaml_config.py
index 5523734..f3e725a 100644
--- a/tests/test_config/test_yaml_config.py
+++ b/tests/test_config/test_yaml_config.py
@@ -7,50 +7,71 @@
from logging_.config import YAMLConfig
config_yaml = """
- version: 1
- formatters:
- simple:
- format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+version: 1
+formatters:
+ simple:
+ format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+handlers:
+ console:
+ class: logging.StreamHandler
+ formatter: simple
+ stream: ext://sys.stdout
+ file_handler:
+ class: logging.FileHandler
+ filename: ${LOG_FILENAME:test_logger.log}
+ formatter: simple
+loggers:
+ test_logger:
+ level: DEBUG
handlers:
- console:
- class: logging.StreamHandler
- formatter: simple
- stream: ext://sys.stdout
- file_handler:
- class: logging.FileHandler
- filename: ${LOGGING_ROOT:.}/${LOG_FILENAME}
- formatter: simple
- loggers:
- test_logger:
- level: DEBUG
- handlers:
- - file_handler
- propagate: yes
- root:
- level: NOTSET
- handlers:
- - console
+ - file_handler
+ propagate: yes
+root:
+ level: NOTSET
+ handlers:
+ - console
"""
+config_yaml_expand_user = """
+version: 1
+formatters:
+ simple:
+ format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+handlers:
+ console:
+ class: logging.StreamHandler
+ formatter: simple
+ stream: ext://sys.stdout
+ file_handler:
+ class: logging.FileHandler
+ filename: ~/test_logger.log
+ formatter: simple
+loggers:
+ test_logger:
+ level: DEBUG
+ handlers:
+ - file_handler
+ propagate: yes
+root:
+ level: NOTSET
+ handlers:
+ - console
+"""
[email protected](scope="module")
+
[email protected](scope="function")
def logger():
"""Fixture for providing a configured logger object"""
- os.environ.update({"LOG_FILENAME": "test_logger.log"})
YAMLConfig(config_yaml)
return logging.getLogger("test_logger")
def test_logger_configured_with_yaml_config(logger, caplog):
"""Test fails if logger can not be configured with envvars in YAML"""
- log_file_name = os.environ.get("LOG_FILENAME")
- file_handler = None
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
- file_handler = handler
- break
- assert log_file_name in file_handler.baseFilename
- logger.error("This is a test")
+ assert "test_logger.log" in handler.baseFilename
+ logger.info("This is a test")
assert "This is a test" in caplog.text
@@ -58,3 +79,35 @@ def test_logger_configured_with_yaml_config_raises():
"""Test fails if empty YAML configuration does not raise error when silent=False"""
with pytest.raises(TypeError):
YAMLConfig("", silent=False)
+
+
+def test_logger_configured_with_yaml_file(fs):
+ """Test fails if YAMLConfig cannot be instantiated from Yaml file"""
+ fs.create_dir(os.path.expanduser("~"))
+ fs.create_file("logging.yaml", contents=config_yaml)
+ YAMLConfig.from_file("logging.yaml")
+ logger = logging.getLogger("test_logger")
+ for handler in logger.handlers:
+ if isinstance(handler, logging.FileHandler):
+ assert "test_logger.log" in handler.baseFilename
+
+
+def test_logger_configuration_raises_for_invalid_file():
+ """Test fails if YAMLConfig does not raise error when invalid config file given"""
+ with pytest.raises(FileNotFoundError):
+ YAMLConfig.from_file("logging.yaml")
+
+
+def test_logger_configuration_silently_ignores_invalid_file():
+ """Test fails if YAMLConfig raises error for invalid config file when silent=True"""
+ YAMLConfig.from_file("logging.yaml", silent=True)
+
+
+def test_logger_configuration_expands_user(fs):
+ """Test fails if YAMLConfig cannot parse ~ or ~username like shells do"""
+ fs.create_dir(os.path.expanduser("~"))
+ YAMLConfig(config_yaml_expand_user)
+ logger = logging.getLogger("test_logger")
+ for handler in logger.handlers:
+ if isinstance(handler, logging.FileHandler):
+ assert "test_logger.log" in handler.baseFilename
diff --git a/tests/test_handlers/test_queue_listener_handler.py b/tests/test_handlers/test_queue_listener_handler.py
index d83e1a1..3f0f636 100644
--- a/tests/test_handlers/test_queue_listener_handler.py
+++ b/tests/test_handlers/test_queue_listener_handler.py
@@ -5,38 +5,38 @@
import yaml
config_yaml = """
- version: 1
- objects:
- queue:
- class: queue.Queue
- maxsize: 1000
- formatters:
- simple:
- format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+version: 1
+objects:
+ queue:
+ class: queue.Queue
+ maxsize: 1000
+formatters:
+ simple:
+ format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+handlers:
+ console:
+ class: logging.StreamHandler
+ formatter: simple
+ stream: ext://sys.stdout
+ queue_handler:
+ class: logging_.handlers.QueueListenerHandler
handlers:
- console:
- class: logging.StreamHandler
- formatter: simple
- stream: ext://sys.stdout
- queue_handler:
- class: logging_.handlers.QueueListenerHandler
- handlers:
- - cfg://handlers.console
- queue: cfg://objects.queue
- loggers:
- test_logger:
- level: DEBUG
- handlers:
- - queue_handler
- propagate: yes
- root:
- level: NOTSET
- handlers:
- - console
+ - cfg://handlers.console
+ queue: cfg://objects.queue
+loggers:
+ test_logger:
+ level: DEBUG
+ handlers:
+ - queue_handler
+ propagate: yes
+root:
+ level: NOTSET
+ handlers:
+ - console
"""
[email protected](scope="module")
[email protected](scope="function")
def logger():
"""Fixture for providing a configured logger object"""
logging_config = yaml.safe_load(config_yaml)
diff --git a/tests/test_logging.py b/tests/test_logging.py
new file mode 100644
index 0000000..58a8a30
--- /dev/null
+++ b/tests/test_logging.py
@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+import pytest
+
+import logging_
+
+
+def test_version():
+ """Test fails if version string for package could not be fetched"""
+ assert len(logging_.__version__) > 0
| Extend expanduser support to environment variables
#9 Added support to expand user home directory paths when added as string constants, however, it does not cover environment variables. Similar post-processing can be added for envvars to resolve `~/` or `~username/` paths.
| 2021-09-23T12:52:13.000 | -1.0 | [
"tests/test_logging.py::test_version"
] | [
"tests/test_config/test_yaml_config.py::test_logger_configuration_raises_for_invalid_file",
"tests/test_config/test_yaml_config.py::test_logger_configuration_silently_ignores_invalid_file",
"tests/test_handlers/test_queue_listener_handler.py::test_logger_emits_with_queue_handler",
"tests/test_config/test_yaml_config.py::test_logger_configured_with_yaml_config_raises",
"tests/test_config/test_yaml_config.py::test_logger_configured_with_yaml_config"
] |
|
sandflow/imscHRM | 13 | sandflow__imscHRM-13 | ['11'] | e8f6d0a46d8f764bc7e9df6b19b8bce177eacf00 | diff --git a/src/main/python/imschrm/cli.py b/src/main/python/imschrm/cli.py
index 0b2c028..05d21db 100644
--- a/src/main/python/imschrm/cli.py
+++ b/src/main/python/imschrm/cli.py
@@ -95,7 +95,7 @@ def main(argv=None):
logging.basicConfig(level=logging.WARNING)
- imschrm.hrm.validate(imschrm.doc_sequence.iter_isd(doc_sequence), ev)
+ imschrm.hrm.validate(imschrm.doc_sequence.iter_isd(doc_sequence), ev, 0)
if ev.failed:
print("Validation failed")
diff --git a/src/main/python/imschrm/hrm.py b/src/main/python/imschrm/hrm.py
index 27473dc..83a1b26 100644
--- a/src/main/python/imschrm/hrm.py
+++ b/src/main/python/imschrm/hrm.py
@@ -69,14 +69,21 @@ class EventHandler:
'''Allows a callee to inform the caller of events that occur during processing. Typically
overridden by the caller.
'''
-
+
@staticmethod
def _format_message(msg: str, doc_index: int, time_offset: Fraction, available_time: Fraction, stats: ISDStatistics):
- return (
- f"{msg} at {float(time_offset):.3f}s (doc #{doc_index})\n"
- f" available time: {float(available_time):.3f}s | HRM time: {float(stats.dur):.3f}\n"
- f" Glyph copy count: {stats.gcpy_count} | render count: {stats.gren_count} | Background draw count: {stats.nbg_total} | Clear: {stats.clear}\n"
- )
+ if stats.is_empty:
+ return (
+ f"{msg} at {float(time_offset):.3f}s (doc #{doc_index})\n"
+ f" available time: {float(available_time):.3f}s | HRM time: 0 (Empty ISD)\n"
+ )
+ else:
+ return (
+ f"{msg} at {float(time_offset):.3f}s (doc #{doc_index})\n"
+ f" available time: {float(available_time):.3f}s | HRM time: {float(stats.dur):.3f}\n"
+ f" ngra_t: {float(stats.ngra_t):.3f}\n"
+ f" Glyph copy count: {stats.gcpy_count} | render count: {stats.gren_count} | Background draw count: {stats.nbg_total} | Clear: {stats.clear}\n"
+ )
def info(self, msg: str, doc_index: int, time_offset: Fraction, available_time: Fraction, stats: ISDStatistics):
@@ -92,7 +99,7 @@ def debug(self, msg: str, doc_index: int, time_offset: Fraction, available_time:
LOGGER.debug(EventHandler._format_message(msg, doc_index, time_offset, available_time, stats))
-def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD]], event_handler: typing.Type[EventHandler]=EventHandler()):
+def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD]], event_handler: typing.Type[EventHandler]=EventHandler(), tolerance: float=0):
'''Determines whether the sequence of ISDs returned by `isd_iterator` conform to the IMSC HRM.
`isd_iterator` returns a sequence of tuplets `(begin, ISD)`, where `ISD` is an ISD instance whose
active interval starts at `begin` seconds and ends immediately before the `begin` value of the next
@@ -115,10 +122,10 @@ def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD
event_handler.debug("Processed document", doc_index, time_offset, avail_render_time, stats)
if not stats.is_empty:
- if stats.dur > avail_render_time:
+ if stats.dur - avail_render_time > tolerance:
event_handler.error("Rendering time exceeded", doc_index, time_offset, avail_render_time, stats)
- if stats.ngra_t > _NGBS:
+ if stats.ngra_t - _NGBS > tolerance:
event_handler.error("NGBS exceeded", doc_index, time_offset, avail_render_time, stats)
last_render_time = time_offset
@@ -150,11 +157,23 @@ def next_isd(
self.isd_stats = ISDStatistics()
- self._compute_dur_t(isd)
+ self.isd_stats.is_empty = True
+
+ if isd is not None:
+ for region in isd.iter_regions():
+
+ if not _is_presented_region(region):
+ continue
+
+ self.isd_stats.is_empty = False
+
+ if not self.isd_stats.is_empty:
+
+ self._compute_dur_t(isd)
- self._compute_dur_d(isd)
+ self._compute_dur_d(isd)
- self.isd_stats.dur = self.isd_stats.dur_t + self.isd_stats.dur_d
+ self.isd_stats.dur = self.isd_stats.dur_t + self.isd_stats.dur_d
return self.isd_stats
| diff --git a/src/test/python/test_hrm.py b/src/test/python/test_hrm.py
index 6a2191f..af8bd6b 100644
--- a/src/test/python/test_hrm.py
+++ b/src/test/python/test_hrm.py
@@ -191,7 +191,87 @@ def test_buffering_across_isds(self):
self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
self.assertAlmostEqual(stats.ngra_t, 1/15 * 1/15 * 7)
-
+
+
+ def test_buffering_across_isds_with_gap(self):
+ ttml_doc = '''<?xml version="1.0" encoding="UTF-8"?>
+<tt xml:lang="en"
+ xmlns="http://www.w3.org/ns/ttml"
+ xmlns:tts="http://www.w3.org/ns/ttml#styling">
+ <head>
+ <layout>
+ <region xml:id="r1" tts:extent="100% 100%"/>
+ </layout>
+ </head>
+ <body region="r1">
+ <div>
+ <p begin="0s" end="0.5s">
+ <span>hello</span>
+ </p>
+ <p begin="1s" end="2s">
+ <span>bonjour bonjour</span>
+ </p>
+ </div>
+ </body>
+</tt>'''
+
+ doc = ttconv.imsc.reader.to_model(et.ElementTree(et.fromstring(ttml_doc)))
+
+ hrm_runner = hrm.HRM()
+
+ # isd at t = 0
+
+ isd0 = ttconv.isd.ISD.from_model(doc, 0)
+
+ stats = hrm_runner.next_isd(isd0)
+
+ clear_e_n = 1
+
+ paint_e_n = 0
+
+ dur_t = 1/15 * 1/15 * (4 / _REN_G_OTHER + 1 / _GCPY_BASE)
+
+ self.assertEqual(stats.gren_count, 4)
+
+ self.assertEqual(stats.gcpy_count, 1)
+
+ self.assertEqual(stats.nbg_total, 0)
+
+ self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
+
+ self.assertAlmostEqual(stats.ngra_t, 1/15 * 1/15 * 4)
+
+ # isd at t = 0.5
+
+ isd1 = ttconv.isd.ISD.from_model(doc, 0.5)
+
+ stats = hrm_runner.next_isd(isd1)
+
+ self.assertTrue(stats.is_empty)
+
+ # isd at t = 1
+
+ isd2 = ttconv.isd.ISD.from_model(doc, 1)
+
+ stats = hrm_runner.next_isd(isd2)
+
+ clear_e_n = 1
+
+ paint_e_n = 0
+
+ dur_t = 1/15 * 1/15 * (6 / _REN_G_OTHER + 9 / _GCPY_BASE)
+
+ self.assertEqual(stats.gren_count, 6)
+
+ self.assertEqual(stats.gcpy_count, 9)
+
+ self.assertEqual(stats.nbg_total, 0)
+
+ self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
+
+ self.assertAlmostEqual(stats.ngra_t, 1/15 * 1/15 * 7)
+
+
def test_doc_3(self):
ttml_doc = '''<?xml version="1.0" encoding="UTF-8"?>
<tt xml:lang="en"
| Add tolerance to DUR and NGBS checks
The render time and glyph cache checks do not tolerate any numerical errors:
https://github.com/sandflow/imscHRM/blob/e8f6d0a46d8f764bc7e9df6b19b8bce177eacf00/src/main/python/imschrm/hrm.py#L118
| 2023-07-13T17:31:05.000 | -1.0 | [
"src/test/python/test_hrm.py::HRMValidator::test_buffering_across_isds_with_gap"
] | [
"src/test/python/test_hrm.py::HRMValidator::test_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_ipd",
"src/test/python/test_hrm.py::HRMValidator::test_exceed_ipd",
"src/test/python/test_hrm.py::HRMValidator::test_same_char_diff_color",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_regions",
"src/test/python/test_hrm.py::HRMValidator::test_br_ignored",
"src/test/python/test_hrm.py::HRMValidator::test_null_isd",
"src/test/python/test_hrm.py::HRMValidator::test_doc_1",
"src/test/python/test_hrm.py::HRMValidator::test_complex_non_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_doc_3",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_bg_color",
"src/test/python/test_hrm.py::HRMValidator::test_buffering_across_isds",
"src/test/python/test_hrm.py::HRMValidator::test_doc_4"
] |
|
podhmo/handofcats | 38 | podhmo__handofcats-38 | ['37'] | e082e69319329502ca4be097be19fd8304c74d6c | diff --git a/examples/logging/Makefile b/examples/logging/Makefile
new file mode 100644
index 0000000..dfc95be
--- /dev/null
+++ b/examples/logging/Makefile
@@ -0,0 +1,25 @@
+TEE ?= 2>&1 | tee
+
+default: 00 01 02 03 04 05
+
+
+00: dst
+ python run.py -h $(TEE) dst/[email protected]
+01: dst
+ python run.py $(TEE) dst/[email protected]
+02: dst
+ DEBUG=1 python run.py $(TEE) dst/[email protected]
+03: dst
+ python -m handofcats def.py:run $(TEE) dst/[email protected]
+04: dst
+ DEBUG=1 python -m handofcats def.py:run $(TEE) dst/[email protected]
+05: FORMAT ?= {"level": "%(levelname)s", "funcname": "%(funcName)s", "message": "%(message)r"}
+05: dst
+ LOGGIG_FORMAT=stdout LOGGING_FORMAT='${FORMAT}' DEBUG=1 python -m handofcats def.py:run $(TEE) dst/[email protected]
+
+clean:
+ rm -rf dst
+.PHONY: clean
+
+dst:
+ mkdir -p dst
diff --git a/examples/logging/def.py b/examples/logging/def.py
new file mode 100644
index 0000000..6a71060
--- /dev/null
+++ b/examples/logging/def.py
@@ -0,0 +1,18 @@
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def run(ok: bool):
+ logger.debug(""""debug" logger's message""")
+ logger.info(""""info" logger's message""")
+ logger.warning(""""warning" logger's message""")
+ logger.error(""""error" logger's message""")
+ logger.critical(""""critical" logger's message""")
+
+ logger.info("""
+MULTILINE MESSAGE
+
+- hello
+- byebye
+""")
diff --git a/examples/logging/dst/00help-message.output b/examples/logging/dst/00help-message.output
new file mode 100644
index 0000000..c05f55d
--- /dev/null
+++ b/examples/logging/dst/00help-message.output
@@ -0,0 +1,12 @@
+usage: run.py [-h] [--expose] [--inplace] [--typed]
+ [--logging {CRITICAL,FATAL,ERROR,WARN,WARNING,INFO,DEBUG,NOTSET}]
+
+positional arguments:
+ ok
+
+optional arguments:
+ -h, --help show this help message and exit
+ --expose
+ --inplace
+ --typed
+ --logging {CRITICAL,FATAL,ERROR,WARN,WARNING,INFO,DEBUG,NOTSET}
diff --git a/examples/logging/dst/01run.output b/examples/logging/dst/01run.output
new file mode 100644
index 0000000..5108549
--- /dev/null
+++ b/examples/logging/dst/01run.output
@@ -0,0 +1,3 @@
+warning message
+error message
+critical message
diff --git a/examples/logging/dst/02run-with-debug.output b/examples/logging/dst/02run-with-debug.output
new file mode 100644
index 0000000..000ef4f
--- /dev/null
+++ b/examples/logging/dst/02run-with-debug.output
@@ -0,0 +1,6 @@
+level:DEBUG name:__main__ where:run.py:9 relative:22.790908813476562 message:debug message
+level:INFO name:__main__ where:run.py:10 relative:22.938966751098633 message:info message
+level:WARNING name:__main__ where:run.py:11 relative:23.00715446472168 message:warning message
+level:ERROR name:__main__ where:run.py:12 relative:23.107051849365234 message:error message
+level:CRITICAL name:__main__ where:run.py:13 relative:23.19812774658203 message:critical message
+** handofcats.injectlogging: DEBUG=1, activate logging **
diff --git a/examples/logging/dst/03run-from-handofcats.output b/examples/logging/dst/03run-from-handofcats.output
new file mode 100644
index 0000000..454dda6
--- /dev/null
+++ b/examples/logging/dst/03run-from-handofcats.output
@@ -0,0 +1,3 @@
+"warning" logger's message
+"error" logger's message
+"critical" logger's message
diff --git a/examples/logging/dst/04run-from-handofcats-with-debug.output b/examples/logging/dst/04run-from-handofcats-with-debug.output
new file mode 100644
index 0000000..e9d8683
--- /dev/null
+++ b/examples/logging/dst/04run-from-handofcats-with-debug.output
@@ -0,0 +1,12 @@
+level:DEBUG name:def where:def.py:7 relative:26.09419822692871 message:"debug" logger's message
+level:INFO name:def where:def.py:8 relative:26.311159133911133 message:"info" logger's message
+level:WARNING name:def where:def.py:9 relative:26.42822265625 message:"warning" logger's message
+level:ERROR name:def where:def.py:10 relative:26.506900787353516 message:"error" logger's message
+level:CRITICAL name:def where:def.py:11 relative:26.61919593811035 message:"critical" logger's message
+level:INFO name:def where:def.py:13 relative:26.7331600189209 message:
+MULTILINE MESSAGE
+
+- hello
+- byebye
+
+** handofcats.injectlogging: DEBUG=1, activate logging **
diff --git a/examples/logging/dst/05run-from-handofcats-with-format.output b/examples/logging/dst/05run-from-handofcats-with-format.output
new file mode 100644
index 0000000..2c204b2
--- /dev/null
+++ b/examples/logging/dst/05run-from-handofcats-with-format.output
@@ -0,0 +1,7 @@
+{"level": "DEBUG", "funcname": "run", "message": "'"debug" logger\'s message'"}
+{"level": "INFO", "funcname": "run", "message": "'"info" logger\'s message'"}
+{"level": "WARNING", "funcname": "run", "message": "'"warning" logger\'s message'"}
+{"level": "ERROR", "funcname": "run", "message": "'"error" logger\'s message'"}
+{"level": "CRITICAL", "funcname": "run", "message": "'"critical" logger\'s message'"}
+{"level": "INFO", "funcname": "run", "message": "'\nMULTILINE MESSAGE\n\n- hello\n- byebye\n'"}
+** handofcats.injectlogging: DEBUG=1, activate logging **
diff --git a/examples/logging/run.py b/examples/logging/run.py
new file mode 100644
index 0000000..e71c8bc
--- /dev/null
+++ b/examples/logging/run.py
@@ -0,0 +1,13 @@
+from handofcats import as_command
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+@as_command
+def run(ok: bool):
+ logger.debug("debug message")
+ logger.info("info message")
+ logger.warning("warning message")
+ logger.error("error message")
+ logger.critical("critical message")
diff --git a/handofcats/__init__.py b/handofcats/__init__.py
index 5f791f7..b05b919 100644
--- a/handofcats/__init__.py
+++ b/handofcats/__init__.py
@@ -9,7 +9,7 @@ def import_symbol_maybe(ob_or_path, sep=":"):
return import_symbol(ob_or_path, sep=sep)
-def as_command(fn=None, argv=None, driver=Driver, level=2, _force=False):
+def as_command(fn=None, *, argv=None, driver=Driver, level=2, _force=False, ignore_logging=False):
create_driver = import_symbol_maybe(driver)
if argv is None:
argv = sys.argv[1:]
@@ -22,7 +22,7 @@ def call(fn, level=1, argv=argv):
if name != "__main__":
return fn
driver = create_driver()
- return driver.run(fn, argv)
+ return driver.run(fn, argv, ignore_logging=ignore_logging)
if fn is None:
return call
diff --git a/handofcats/driver.py b/handofcats/driver.py
index 26c4aab..97c079d 100644
--- a/handofcats/driver.py
+++ b/handofcats/driver.py
@@ -1,4 +1,5 @@
from .injector import Injector
+from . import injectlogging
class Driver:
@@ -30,14 +31,20 @@ def create_parser(self, fn, *, argv=None, description=None):
parser.add_argument("--typed", action="store_true") # xxx (for ./expose.py)
return parser
- def run(self, fn, argv=None):
+ def run(self, fn, argv=None, *, ignore_logging=False):
parser = self.create_parser(fn, argv=argv, description=fn.__doc__)
injector = self.create_injector(fn)
injector.inject(parser)
+ if not ignore_logging:
+ injectlogging.setup(parser)
args = parser.parse_args(argv)
params = vars(args).copy()
+
+ if not ignore_logging:
+ injectlogging.activate(params)
+
params.pop("expose", None) # xxx: for ./parsers/expose.py
params.pop("inplace", None) # xxx: for ./parsers/expose.py
params.pop("typed", None) # xxx: for ./parsers/expose.py
diff --git a/handofcats/injectlogging.py b/handofcats/injectlogging.py
new file mode 100644
index 0000000..afd600a
--- /dev/null
+++ b/handofcats/injectlogging.py
@@ -0,0 +1,38 @@
+import logging
+import os
+import sys
+
+
+def setup(parser):
+ logging_levels = list(logging._nameToLevel.keys())
+ parser.add_argument(
+ "--logging", choices=logging_levels, default=None
+ )
+
+
+def activate(params, *, logging_level=None, logging_format=None, logging_stream=None):
+ logging_format = (
+ logging_format
+ or "level:%(levelname)s name:%(name)s where:%(filename)s:%(lineno)s relative:%(relativeCreated)s message:%(message)s"
+ )
+
+ if os.environ.get("DEBUG"):
+ logging_level = logging.DEBUG
+ print("** {where}: DEBUG=1, activate logging **".format(where=__name__))
+
+ if os.environ.get("LOGGING_LEVEL"):
+ logging_level = logging._nameToLevel.get(os.environ["LOGGING_LEVEL"])
+ if os.environ.get("LOGGING_FORMAT"):
+ logging_format = os.environ["LOGGING_FORMAT"]
+ if os.environ.get("LOGGING_STREAM"):
+ logging_stream = getattr(sys, os.environ["LOGGING_STREAM"])
+
+ if "logging" in params:
+ level = params.pop("logging", None)
+ if level is not None:
+ logging_level = level
+
+ if logging_level is not None:
+ logging.basicConfig(
+ level=logging_level, format=logging_format, stream=logging_stream,
+ )
| diff --git a/handofcats/tests/test_parse.py b/handofcats/tests/test_parse.py
index 42afe45..2e3e8f0 100644
--- a/handofcats/tests/test_parse.py
+++ b/handofcats/tests/test_parse.py
@@ -20,7 +20,7 @@ def _callFUT(self, fn, *, argv):
class MyDriver(Driver):
create_parser = testing.create_parser
- return target_function(fn=fn, argv=argv, _force=True, driver=MyDriver)
+ return target_function(fn=fn, argv=argv, _force=True, driver=MyDriver, ignore_logging=True)
def test_it(self):
from handofcats.parsers.testing import ParseArgsCalled
| DEBUG=1 logging is activated
| 2020-01-08T12:09:39.000 | -1.0 | [
"handofcats/tests/test_parse.py::Tests::test_it"
] | [] |
|
sandflow/imscHRM | 9 | sandflow__imscHRM-9 | ['8'] | 2792530101b71689fc3390ba27095c3cd958beeb | diff --git a/src/main/python/imschrm/hrm.py b/src/main/python/imschrm/hrm.py
index b33730a..27473dc 100644
--- a/src/main/python/imschrm/hrm.py
+++ b/src/main/python/imschrm/hrm.py
@@ -101,31 +101,27 @@ def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD
hrm = HRM()
- last_offset = 0
-
- is_last_isd_empty = True
+ last_render_time = -_IPD
for doc_index, (time_offset, isd) in enumerate(isd_iterator):
- if time_offset < last_offset:
+ if time_offset <= last_render_time:
raise RuntimeError("ISDs are not in order of increasing offset")
- stats = hrm.next_isd(isd, doc_index, is_last_isd_empty)
-
- avail_render_time = _IPD if doc_index == 0 else time_offset - last_offset
-
- if stats.dur > avail_render_time:
- event_handler.error("Rendering time exceeded", doc_index, time_offset, avail_render_time, stats)
+ stats = hrm.next_isd(isd)
- if stats.ngra_t > 1:
- event_handler.error("NGBS exceeded", doc_index, time_offset, avail_render_time, stats)
+ avail_render_time = min(_IPD, time_offset - last_render_time)
event_handler.debug("Processed document", doc_index, time_offset, avail_render_time, stats)
- if not (stats.is_empty and is_last_isd_empty):
- last_offset = time_offset
+ if not stats.is_empty:
+ if stats.dur > avail_render_time:
+ event_handler.error("Rendering time exceeded", doc_index, time_offset, avail_render_time, stats)
- is_last_isd_empty = stats.is_empty
+ if stats.ngra_t > _NGBS:
+ event_handler.error("NGBS exceeded", doc_index, time_offset, avail_render_time, stats)
+
+ last_render_time = time_offset
@dataclass(frozen=True)
@@ -149,16 +145,14 @@ def __init__(self):
def next_isd(
self,
- isd: typing.Type[ttconv.isd.ISD],
- index_n: int,
- is_last_isd_empty: bool
+ isd: typing.Type[ttconv.isd.ISD]
) -> ISDStatistics:
self.isd_stats = ISDStatistics()
- self._compute_dur_t(isd, index_n)
+ self._compute_dur_t(isd)
- self._compute_dur_d(isd, index_n, is_last_isd_empty)
+ self._compute_dur_d(isd)
self.isd_stats.dur = self.isd_stats.dur_t + self.isd_stats.dur_d
@@ -166,16 +160,12 @@ def next_isd(
def _compute_dur_d(
self,
- isd: typing.Type[ttconv.isd.ISD],
- index_n: int,
- is_last_isd_empty: bool
+ isd: typing.Type[ttconv.isd.ISD]
):
self.isd_stats.is_empty = True
- draw_area = 0 if index_n == 0 or is_last_isd_empty else 1
-
- self.isd_stats.clear = draw_area != 0
+ draw_area = 0
if isd is not None:
for region in isd.iter_regions():
@@ -210,12 +200,15 @@ def _compute_dur_d(
self.isd_stats.nbg_total += nbg
+ draw_area += 0 if self.isd_stats.is_empty else 1
+
+ self.isd_stats.clear = draw_area != 0
+
self.isd_stats.dur_d = draw_area / _BDRAW
def _compute_dur_t(
self,
- isd: typing.Type[ttconv.isd.ISD],
- _index_n: int
+ isd: typing.Type[ttconv.isd.ISD]
):
front_buffer = set()
| diff --git a/src/test/python/test_hrm.py b/src/test/python/test_hrm.py
index 12bd487..6a2191f 100644
--- a/src/test/python/test_hrm.py
+++ b/src/test/python/test_hrm.py
@@ -29,6 +29,7 @@
# pylint: disable=R0201,C0115,C0116,W0212
import unittest
+from fractions import Fraction
import xml.etree.ElementTree as et
import ttconv.model as model
@@ -44,6 +45,13 @@
_REN_G_CJK = 0.6
_REN_G_OTHER = 1.2
+class InvalidError(RuntimeError):
+ pass
+
+class RaiseOnErrorHandler(hrm.EventHandler):
+ def error(self, msg: str, doc_index: int, time_offset: Fraction, available_time: Fraction, stats: hrm.ISDStatistics):
+ raise InvalidError()
+
class HRMValidator(unittest.TestCase):
def test_doc_1(self):
@@ -96,9 +104,9 @@ def test_doc_1(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -144,9 +152,9 @@ def test_buffering_across_isds(self):
isd0 = ttconv.isd.ISD.from_model(doc, 0)
- stats = hrm_runner.next_isd(isd0, 0, True)
+ stats = hrm_runner.next_isd(isd0)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -166,7 +174,7 @@ def test_buffering_across_isds(self):
isd1 = ttconv.isd.ISD.from_model(doc, 1)
- stats = hrm_runner.next_isd(isd1, 1, False)
+ stats = hrm_runner.next_isd(isd1)
clear_e_n = 1
@@ -213,9 +221,9 @@ def test_doc_3(self):
# run HRM
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -260,9 +268,9 @@ def test_doc_4(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0.25
@@ -307,9 +315,9 @@ def test_same_char_diff_color(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -354,9 +362,9 @@ def test_cjk(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -401,9 +409,9 @@ def test_complex_non_cjk(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -453,9 +461,9 @@ def test_multiple_regions(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0.75
@@ -500,9 +508,9 @@ def test_multiple_bg_color(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0.25 * 6
@@ -522,7 +530,7 @@ def test_null_isd(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(None, 0, True)
+ stats = hrm_runner.next_isd(None)
self.assertAlmostEqual(stats.dur, 0)
@@ -534,7 +542,7 @@ def test_null_isd(self):
self.assertEqual(stats.nbg_total, 0)
- stats = hrm_runner.next_isd(None, 1, True)
+ stats = hrm_runner.next_isd(None)
self.assertAlmostEqual(stats.dur, 0)
@@ -578,9 +586,9 @@ def test_br_ignored(self):
# run HRM
- stats = hrm_runner.next_isd(isd, 0, True)
+ stats = hrm_runner.next_isd(isd)
- clear_e_n = 0
+ clear_e_n = 1
paint_e_n = 0
@@ -596,5 +604,103 @@ def test_br_ignored(self):
self.assertAlmostEqual(stats.ngra_t, 1/15 * 1/15 * 4)
+ def test_exceed_ipd(self):
+ ttml_doc = '''<?xml version="1.0" encoding="UTF-8"?>
+<tt xml:lang="en"
+ xmlns="http://www.w3.org/ns/ttml"
+ xmlns:tts="http://www.w3.org/ns/ttml#styling">
+ <head>
+ <layout>
+ <region xml:id="r1" tts:backgroundColor="black"/>
+ </layout>
+ </head>
+ <body region="r1">
+ <div>
+ <p begin="0s" end="1s">0</p>
+ <p begin="2s" end="3s" tts:fontSize="300%">abcdefghijklmnopqrstuvwxy</p>
+ </div>
+ </body>
+</tt>'''
+
+ doc = ttconv.imsc.reader.to_model(et.ElementTree(et.fromstring(ttml_doc)))
+
+ hrm_runner = hrm.HRM()
+
+ isd_list = ttconv.isd.ISD.generate_isd_sequence(doc)
+
+ hrm_runner.next_isd(isd_list[0][1])
+ hrm_runner.next_isd(isd_list[1][1])
+ stats = hrm_runner.next_isd(isd_list[2][1])
+
+ clear_e_n = 1
+
+ paint_e_n = 1
+
+ dur_t = 3/15 * 3/15 * (25 / _REN_G_OTHER)
+
+ self.assertEqual(stats.gren_count, 25)
+
+ self.assertEqual(stats.gcpy_count, 0)
+
+ self.assertEqual(stats.nbg_total, 1)
+
+ self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
+
+ self.assertAlmostEqual(stats.ngra_t, 3/15 * 3/15 * 25)
+
+ # expect failed validation
+
+ eh = RaiseOnErrorHandler()
+
+ with self.assertRaises(InvalidError):
+ hrm.validate(iter(isd_list), eh)
+
+ def test_ipd(self):
+ ttml_doc = '''<?xml version="1.0" encoding="UTF-8"?>
+<tt xml:lang="en"
+ xmlns="http://www.w3.org/ns/ttml"
+ xmlns:tts="http://www.w3.org/ns/ttml#styling">
+ <head>
+ <layout>
+ <region xml:id="r1" tts:backgroundColor="black"/>
+ </layout>
+ </head>
+ <body region="r1">
+ <div>
+ <p begin="0s" end="1s" tts:fontSize="300%">abcdefghijklmnopqrstuvwx</p>
+ </div>
+ </body>
+</tt>'''
+
+ doc = ttconv.imsc.reader.to_model(et.ElementTree(et.fromstring(ttml_doc)))
+
+ hrm_runner = hrm.HRM()
+
+ isd_list = ttconv.isd.ISD.generate_isd_sequence(doc)
+
+ stats = hrm_runner.next_isd(isd_list[0][1])
+
+ clear_e_n = 1
+
+ paint_e_n = 1
+
+ dur_t = 3/15 * 3/15 * (24 / _REN_G_OTHER)
+
+ self.assertEqual(stats.gren_count, 24)
+
+ self.assertEqual(stats.gcpy_count, 0)
+
+ self.assertEqual(stats.nbg_total, 1)
+
+ self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
+
+ self.assertAlmostEqual(stats.ngra_t, 3/15 * 3/15 * 24)
+
+ # expect failed validation
+
+ eh = RaiseOnErrorHandler()
+
+ hrm.validate(iter(isd_list), eh)
+
if __name__ == '__main__':
unittest.main()
| Validation fails on short gaps between complex subs
[Netflix timing guidelines for subtitles](https://partnerhelp.netflixstudios.com/hc/en-us/articles/360051554394-Timed-Text-Style-Guide-Subtitle-Timing-Guidelines) recommends to "close the gap" between subtitles when the gap is smaller than 500ms by setting the gap to 2 frames.
This means that the validation fails on perfectly acceptable documents that produce an ISD sequence with short, empty ISD documents in between long-duration, non-empty ISD documents. The software (and maybe the spec) should be updated to work with such documents.
| 2022-09-02T23:17:14.000 | -1.0 | [
"src/test/python/test_hrm.py::HRMValidator::test_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_ipd",
"src/test/python/test_hrm.py::HRMValidator::test_exceed_ipd",
"src/test/python/test_hrm.py::HRMValidator::test_same_char_diff_color",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_regions",
"src/test/python/test_hrm.py::HRMValidator::test_br_ignored",
"src/test/python/test_hrm.py::HRMValidator::test_null_isd",
"src/test/python/test_hrm.py::HRMValidator::test_doc_1",
"src/test/python/test_hrm.py::HRMValidator::test_complex_non_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_doc_3",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_bg_color",
"src/test/python/test_hrm.py::HRMValidator::test_buffering_across_isds",
"src/test/python/test_hrm.py::HRMValidator::test_doc_4"
] | [] |
|
podhmo/handofcats | 15 | podhmo__handofcats-15 | ['13'] | f00666ab7ea989f76b21084502e48adfde173ce3 | diff --git a/examples/variation/00positional/_exposed.py b/examples/variation/00positional/_exposed.py
index 9e0b8fa..73cac64 100644
--- a/examples/variation/00positional/_exposed.py
+++ b/examples/variation/00positional/_exposed.py
@@ -1,13 +1,13 @@
-def run(filename: str) -> None:
+def run(file_name: str) -> None:
pass
def main(argv=None):
import argparse
parser = argparse.ArgumentParser(description=None)
parser.print_usage = parser.print_help
- parser.add_argument('filename')
+ parser.add_argument('file_name')
args = parser.parse_args(argv)
run(**vars(args))
diff --git a/examples/variation/00positional/main.py b/examples/variation/00positional/main.py
index c462f30..55abce6 100644
--- a/examples/variation/00positional/main.py
+++ b/examples/variation/00positional/main.py
@@ -2,5 +2,5 @@
@as_command
-def run(filename: str) -> None:
+def run(file_name: str) -> None:
pass
diff --git a/examples/variation/01keyword/_exposed.py b/examples/variation/01keyword/_exposed.py
index 7f2ccfc..ac85a61 100644
--- a/examples/variation/01keyword/_exposed.py
+++ b/examples/variation/01keyword/_exposed.py
@@ -1,13 +1,13 @@
-def run(*, filename: str) -> None:
+def run(*, file_name: str) -> None:
pass
def main(argv=None):
import argparse
parser = argparse.ArgumentParser(description=None)
parser.print_usage = parser.print_help
- parser.add_argument('--filename', required=True)
+ parser.add_argument('--file-name', required=True)
args = parser.parse_args(argv)
run(**vars(args))
diff --git a/examples/variation/01keyword/main.py b/examples/variation/01keyword/main.py
index cdb8b67..9b2db1c 100644
--- a/examples/variation/01keyword/main.py
+++ b/examples/variation/01keyword/main.py
@@ -2,5 +2,5 @@
@as_command
-def run(*, filename: str) -> None:
+def run(*, file_name: str) -> None:
pass
diff --git a/handofcats/accessor.py b/handofcats/accessor.py
index e404ba8..d935f95 100644
--- a/handofcats/accessor.py
+++ b/handofcats/accessor.py
@@ -53,7 +53,7 @@ def create_flag(self, name, *, required: bool = False) -> Option:
def create_positional(self, name) -> Option:
return Option(
name=name,
- option_name=option_name(name),
+ option_name=option_name(name).replace("-", "_"),
required=True,
type=self.resolver.resolve_type(name),
default=self.resolver.resolve_default(name),
| diff --git a/handofcats/tests/test_accessor.py b/handofcats/tests/test_accessor.py
index 7884e35..bf04cde 100644
--- a/handofcats/tests/test_accessor.py
+++ b/handofcats/tests/test_accessor.py
@@ -16,7 +16,7 @@ def f(user_name: str) -> None:
self.assertEqual(len(got), 1)
with self.subTest("option_name"):
- self.assertEqual(got[0].option_name, "user-name")
+ self.assertEqual(got[0].option_name, "user_name")
with self.subTest("required"):
self.assertEqual(got[0].required, True)
with self.subTest("default"):
| fix positional arguments naming
the conversion that `root_path` -> `root-path`, is invalid
| 2019-11-11T07:43:06.000 | -1.0 | [
"handofcats/tests/test_accessor.py::Tests::test_args"
] | [
"handofcats/tests/test_accessor.py::Tests::test_kwonlyargs",
"handofcats/tests/test_accessor.py::Tests::test_kwonlyargs_with_type_bool",
"handofcats/tests/test_accessor.py::Tests::test_kwonlyargs_with_type_int"
] |
|
sandflow/imscHRM | 5 | sandflow__imscHRM-5 | ['4'] | 015a4f6dbb5d080700d346b632164d5efeaa199a | diff --git a/src/main/python/imschrm/hrm.py b/src/main/python/imschrm/hrm.py
index 1ee6057..9e283d5 100644
--- a/src/main/python/imschrm/hrm.py
+++ b/src/main/python/imschrm/hrm.py
@@ -57,10 +57,12 @@ class ISDStatistics:
dur: Number = 0 # HRM ISD time
dur_d: Number = 0 # HRM background drawing time
nbg_total: Number = 0 # Number of backgrounds drawn
+ clear: bool = False # Whether the root container had to be cleared
dur_t: Number = 0 # HRM text drawing time
ngra_t: Number = 0 # Total Normalized Rendered Glyph Area
gcpy_count: Number = 0 # Total number of glyphs copied
gren_count: Number = 0 # Total number of glyphs rendered
+ is_empty: bool = False # Does the ISD contain any content
class EventHandler:
@@ -73,7 +75,7 @@ def _format_message(msg: str, doc_index: int, time_offset: Fraction, available_t
return (
f"{msg} at {float(time_offset):.3f}s (doc #{doc_index})\n"
f" available time: {float(available_time):.3f}s | HRM time: {float(stats.dur):.3f}\n"
- f" Glyph copy count: {stats.gcpy_count} | render count: {stats.gren_count} | Background draw count: {stats.nbg_total}\n"
+ f" Glyph copy count: {stats.gcpy_count} | render count: {stats.gren_count} | Background draw count: {stats.nbg_total} | Clear: {stats.clear}\n"
)
@@ -101,12 +103,14 @@ def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD
last_offset = 0
+ is_last_isd_empty = True
+
for doc_index, (time_offset, isd) in enumerate(isd_iterator):
if time_offset < last_offset:
raise RuntimeError("ISDs are not in order of increasing offset")
- stats = hrm.next_isd(isd, doc_index)
+ stats = hrm.next_isd(isd, doc_index, is_last_isd_empty)
avail_render_time = _IPD if doc_index == 0 else time_offset - last_offset
@@ -118,7 +122,11 @@ def validate(isd_iterator: typing.Iterator[typing.Tuple[Fraction, ttconv.isd.ISD
event_handler.debug("Processed document", doc_index, time_offset, avail_render_time, stats)
- last_offset = time_offset
+ if not (stats.is_empty and is_last_isd_empty):
+ last_offset = time_offset
+
+ is_last_isd_empty = stats.is_empty
+
@dataclass(frozen=True)
class _Glyph:
@@ -143,13 +151,14 @@ def next_isd(
self,
isd: typing.Type[ttconv.isd.ISD],
index_n: int,
+ is_last_isd_empty: bool
) -> ISDStatistics:
self.isd_stats = ISDStatistics()
self._compute_dur_t(isd, index_n)
- self._compute_dur_d(isd, index_n)
+ self._compute_dur_d(isd, index_n, is_last_isd_empty)
self.isd_stats.dur = self.isd_stats.dur_t + self.isd_stats.dur_d
@@ -158,10 +167,15 @@ def next_isd(
def _compute_dur_d(
self,
isd: typing.Type[ttconv.isd.ISD],
- index_n: int
+ index_n: int,
+ is_last_isd_empty: bool
):
- draw_area = 0 if index_n == 0 else 1
+ self.isd_stats.is_empty = True
+
+ draw_area = 0 if index_n == 0 or is_last_isd_empty else 1
+
+ self.isd_stats.clear = draw_area != 0
if isd is not None:
for region in isd.iter_regions():
@@ -169,6 +183,8 @@ def _compute_dur_d(
if not _is_presented_region(region):
continue
+ self.isd_stats.is_empty = False
+
nbg = 0
for element in region.dfs_iterator():
@@ -176,6 +192,10 @@ def _compute_dur_d(
# should body elements really be excluded? -> NO
# should transparent backgrounds really be counted? -> NO
# should span and br really be included -> yes for now
+ # should br really be included -> no
+
+ if isinstance(element, ttconv.model.Br):
+ continue
bg_color = element.get_style(styles.StyleProperties.BackgroundColor)
| diff --git a/src/test/python/test_hrm.py b/src/test/python/test_hrm.py
index 9bc61b9..12bd487 100644
--- a/src/test/python/test_hrm.py
+++ b/src/test/python/test_hrm.py
@@ -96,7 +96,7 @@ def test_doc_1(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -144,7 +144,7 @@ def test_buffering_across_isds(self):
isd0 = ttconv.isd.ISD.from_model(doc, 0)
- stats = hrm_runner.next_isd(isd0, 0)
+ stats = hrm_runner.next_isd(isd0, 0, True)
clear_e_n = 0
@@ -166,7 +166,7 @@ def test_buffering_across_isds(self):
isd1 = ttconv.isd.ISD.from_model(doc, 1)
- stats = hrm_runner.next_isd(isd1, 1)
+ stats = hrm_runner.next_isd(isd1, 1, False)
clear_e_n = 1
@@ -213,7 +213,7 @@ def test_doc_3(self):
# run HRM
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -260,7 +260,7 @@ def test_doc_4(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -307,7 +307,7 @@ def test_same_char_diff_color(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -354,7 +354,7 @@ def test_cjk(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -401,7 +401,7 @@ def test_complex_non_cjk(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -453,7 +453,7 @@ def test_multiple_regions(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -500,7 +500,7 @@ def test_multiple_bg_color(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(isd, 0)
+ stats = hrm_runner.next_isd(isd, 0, True)
clear_e_n = 0
@@ -522,7 +522,7 @@ def test_null_isd(self):
hrm_runner = hrm.HRM()
- stats = hrm_runner.next_isd(None, 0)
+ stats = hrm_runner.next_isd(None, 0, True)
self.assertAlmostEqual(stats.dur, 0)
@@ -534,9 +534,9 @@ def test_null_isd(self):
self.assertEqual(stats.nbg_total, 0)
- stats = hrm_runner.next_isd(None, 1)
+ stats = hrm_runner.next_isd(None, 1, True)
- self.assertAlmostEqual(stats.dur, 1 / _BDRAW)
+ self.assertAlmostEqual(stats.dur, 0)
self.assertAlmostEqual(stats.ngra_t, 0)
@@ -546,5 +546,55 @@ def test_null_isd(self):
self.assertEqual(stats.nbg_total, 0)
+ def test_br_ignored(self):
+ """Confirm that BR elements are excluded from NBG(Ri) computations
+ """
+
+ ttml_doc = '''<?xml version="1.0" encoding="UTF-8"?>
+<tt xml:lang="en"
+ xmlns="http://www.w3.org/ns/ttml"
+ xmlns:tts="http://www.w3.org/ns/ttml#styling">
+ <head>
+ <layout>
+ <region xml:id="r1" tts:extent="100% 100%"/>
+ </layout>
+ </head>
+ <body region="r1">
+ <div>
+ <p>
+ <span>hello<br tts:backgroundColor="blue"/></span>
+ </p>
+ </div>
+ </body>
+</tt>'''
+
+ doc = ttconv.imsc.reader.to_model(et.ElementTree(et.fromstring(ttml_doc)))
+
+ hrm_runner = hrm.HRM()
+
+ # create ISDs
+
+ isd = ttconv.isd.ISD.from_model(doc, 0)
+
+ # run HRM
+
+ stats = hrm_runner.next_isd(isd, 0, True)
+
+ clear_e_n = 0
+
+ paint_e_n = 0
+
+ dur_t = 1/15 * 1/15 * (4 / _REN_G_OTHER + 1 / _GCPY_BASE)
+
+ self.assertEqual(stats.gren_count, 4)
+
+ self.assertEqual(stats.gcpy_count, 1)
+
+ self.assertEqual(stats.nbg_total, 0)
+
+ self.assertAlmostEqual(stats.dur, (clear_e_n + paint_e_n) / _BDRAW + dur_t)
+
+ self.assertAlmostEqual(stats.ngra_t, 1/15 * 1/15 * 4)
+
if __name__ == '__main__':
unittest.main()
| Update to match W3C IMSC HRM FPWD
https://www.w3.org/TR/2021/WD-imsc-hrm-20211109/
https://github.com/w3c/imsc-hrm/issues/6
https://github.com/w3c/imsc-hrm/issues/3
https://github.com/w3c/imsc-hrm/issues/4
https://github.com/w3c/imsc-hrm/issues/2
| 2021-11-11T16:54:22.000 | -1.0 | [
"src/test/python/test_hrm.py::HRMValidator::test_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_same_char_diff_color",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_regions",
"src/test/python/test_hrm.py::HRMValidator::test_br_ignored",
"src/test/python/test_hrm.py::HRMValidator::test_null_isd",
"src/test/python/test_hrm.py::HRMValidator::test_doc_1",
"src/test/python/test_hrm.py::HRMValidator::test_complex_non_cjk",
"src/test/python/test_hrm.py::HRMValidator::test_doc_3",
"src/test/python/test_hrm.py::HRMValidator::test_multiple_bg_color",
"src/test/python/test_hrm.py::HRMValidator::test_buffering_across_isds",
"src/test/python/test_hrm.py::HRMValidator::test_doc_4"
] | [] |
|
larray-project/larray | 1,112 | larray-project__larray-1112 | ['1101'] | 7bf1afcc5f489422acf253975c0e77b3715914cf | diff --git a/doc/source/changes/version_0_34_3.rst.inc b/doc/source/changes/version_0_34_3.rst.inc
index 12a36a2ad..585ecc1b0 100644
--- a/doc/source/changes/version_0_34_3.rst.inc
+++ b/doc/source/changes/version_0_34_3.rst.inc
@@ -7,6 +7,40 @@ New features
* added support for Python 3.12 (closes :issue:`1109`).
+Miscellaneous improvements
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+* improved the error message when selecting several labels at the same time and some of them were wrong.
+ In that case, it was hard to know which labels were wrong. This was especially annoying if the axis was long and
+ thus not shown in its entirety in the error message. For example, given the following array: ::
+
+ >>> arr = la.ndtest('a=a0,a1;b=b0..b2,b4..b7')
+ >>> arr
+ a\b b0 b1 b2 b4 b5 b6 b7
+ a0 0 1 2 3 4 5 6
+ a1 7 8 9 10 11 12 13
+
+ This code: ::
+
+ >>> arr['b0,b2,b3,b7']
+
+ used to produce the following error: ::
+
+ ValueError: 'b0,b2,b3,b7' is not a valid label for any axis:
+ a [2]: 'a0' 'a1'
+ b [7]: 'b0' 'b1' 'b2' ... 'b5' 'b6' 'b7'
+
+ which did not contain enough information to determine the problem was with 'b3'. It now produces this instead: ::
+
+ ValueError: 'b0,b2,b3,b7' is not a valid subset for any axis:
+ a [2]: 'a0' 'a1'
+ b [7]: 'b0' 'b1' 'b2' ... 'b5' 'b6' 'b7'
+ Some of those labels are valid though:
+ * axis 'b' contains 3 out of 4 labels (missing labels: 'b3')
+
+ Closes :issue:`1101`.
+
+
Fixes
^^^^^
diff --git a/larray/core/axis.py b/larray/core/axis.py
index bc40775a6..39dfe213c 100644
--- a/larray/core/axis.py
+++ b/larray/core/axis.py
@@ -2681,7 +2681,38 @@ def _translate_nice_key(self, axis_key):
except KeyError:
continue
if not valid_axes:
- raise ValueError(f"{axis_key!r} is not a valid label for any axis:\n{self._axes_summary()}")
+ # if the key has several labels
+ nicer_key = _to_key(axis_key)
+ sequence_types = (tuple, list, np.ndarray, ABCArray)
+ if (isinstance(nicer_key, sequence_types) or
+ (isinstance(nicer_key, Group) and isinstance(nicer_key.key, sequence_types))):
+
+ # we use a different "base" message in this case (because axis_key is not really a *label*)
+ msg = f"{axis_key!r} is not a valid subset for any axis:\n{self._axes_summary()}"
+
+ # ... and check for partial matches
+ if isinstance(nicer_key, Group):
+ nicer_key = nicer_key.eval()
+ key_label_set = set(nicer_key)
+ partial_matches = {}
+ for axis in self:
+ missing_labels = key_label_set - set(axis.labels)
+ if missing_labels < key_label_set:
+ partial_matches[axis] = missing_labels
+
+ if partial_matches:
+ partial_matches_str = '\n'.join(
+ f" * axis '{self.axis_id(axis)}' contains {len(key_label_set) - len(missing_labels)}"
+ f' out of {len(key_label_set)}'
+ f' labels (missing labels: {", ".join(repr(label) for label in missing_labels)})'
+ for axis, missing_labels in partial_matches.items()
+ )
+ msg += f"\nSome of those labels are valid though:\n{partial_matches_str}"
+ else:
+ # we have single label
+ msg = f"{axis_key!r} is not a valid label for any axis:\n{self._axes_summary()}"
+
+ raise ValueError(msg)
elif len(valid_axes) > 1:
raise ValueError(f'{axis_key!r} is ambiguous, it is valid in the following axes:\n'
f'{self._axes_summary(valid_axes)}')
| diff --git a/larray/tests/test_array.py b/larray/tests/test_array.py
index 3d17d33c3..3a5bf7b21 100644
--- a/larray/tests/test_array.py
+++ b/larray/tests/test_array.py
@@ -664,7 +664,7 @@ def test_getitem_guess_axis(array):
_ = array[[1, 2], 999]
# key with invalid label list (ie list of labels not found on any axis)
- with must_raise(ValueError, """[998, 999] is not a valid label for any axis:
+ with must_raise(ValueError, """[998, 999] is not a valid subset for any axis:
a [19]: 0 1 2 ... 16 17 18
b [12]: 'b0' 'b1' 'b2' ... 'b10' 'b11' 'b3'
c [2]: 'c0' 'c1'
@@ -678,11 +678,13 @@ def test_getitem_guess_axis(array):
"7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18"):
_ = array[[1, 2], [3, 999]]
- with must_raise(ValueError, """[999, 4] is not a valid label for any axis:
+ with must_raise(ValueError, """[999, 4] is not a valid subset for any axis:
a [19]: 0 1 2 ... 16 17 18
b [12]: 'b0' 'b1' 'b2' ... 'b10' 'b11' 'b3'
c [2]: 'c0' 'c1'
- d [6]: 'd1' 'd2' 'd3' 'd4' 'd5' 'd6'"""):
+ d [6]: 'd1' 'd2' 'd3' 'd4' 'd5' 'd6'
+Some of those labels are valid though:
+ * axis 'a' contains 1 out of 2 labels (missing labels: 999)"""):
_ = array[[1, 2], [999, 4]]
# ambiguous key
| Improve getitem ValueError message when trying to retrieve multiple labels
When trying to retrieve several labels and it fails, it is sometimes hard to know exactly which label(s) are missing from the array, especially when the axes are long and not all labels are displayed in the axes summary.
I think that when it fails, displaying axes where it matches partially and the missing keys could be a large quality of life improvement:
```python
>>> arr = la.ndtest('a=a0..a4,a6..a9;b=b0..b2')
>>> arr['a0,a7,a2,a5,a3,a4,a8']
ValueError: 'a0,a7,a2,a5,a3,a4,a8' is not a valid label for any axis:
a [9]: 'a0' 'a1' 'a2' ... 'a7' 'a8' 'a9'
b [3]: 'b0' 'b1' 'b2'
```
FWIW, as a quick workaround, I had to resort to this to know which key was missing:
```python
>>> arr.a.union('a0,a7,a2,a5,a3,a4,a8').difference(arr.a)
Axis(['a5'], 'a')
```
| 2024-07-18T11:38:24.000 | -1.0 | [
"larray/tests/test_array.py::test_getitem_guess_axis"
] | [
"larray/tests/test_array.py::test_ufuncs",
"larray/tests/test_array.py::test_group_agg_on_group_agg",
"larray/tests/test_array.py::test_items",
"larray/tests/test_array.py::test_getitem_ndarray_key_guess",
"larray/tests/test_array.py::test_group_agg_label_group",
"larray/tests/test_array.py::test_group_agg_guess_axis",
"larray/tests/test_array.py::test_filter",
"larray/tests/test_array.py::test_zip_array_items",
"larray/tests/test_array.py::test_points_indexer_getitem",
"larray/tests/test_array.py::test_meta_arg_array_creation",
"larray/tests/test_array.py::test_keys",
"larray/tests/test_array.py::test_getitem_axis_object",
"larray/tests/test_array.py::test_bool",
"larray/tests/test_array.py::test_getitem_bool_ndarray_key_arr_wh_bool_axis",
"larray/tests/test_array.py::test_setitem_ndarray",
"larray/tests/test_array.py::test_value_string_union",
"larray/tests/test_array.py::test_from_series",
"larray/tests/test_array.py::test_value_string_range",
"larray/tests/test_array.py::test_zip_array_values",
"larray/tests/test_array.py::test_sum_full_axes_with_nan",
"larray/tests/test_array.py::test_sum_full_axes_keep_axes",
"larray/tests/test_array.py::test_stack",
"larray/tests/test_array.py::test_sequence",
"larray/tests/test_array.py::test_stack_dict_no_axis_labels",
"larray/tests/test_array.py::test_getitem_empty_tuple",
"larray/tests/test_array.py::test_group_agg_one_axis",
"larray/tests/test_array.py::test_ratio",
"larray/tests/test_array.py::test_getitem_bool_larray_and_group_key",
"larray/tests/test_array.py::test_getattr",
"larray/tests/test_array.py::test_np_array",
"larray/tests/test_array.py::test_cumsum",
"larray/tests/test_array.py::test_getitem_int_larray_key_guess",
"larray/tests/test_array.py::test_getitem_multiple_larray_key_guess",
"larray/tests/test_array.py::test_eq",
"larray/tests/test_array.py::test_percentile_groups",
"larray/tests/test_array.py::test_rmatmul",
"larray/tests/test_array.py::test_getitem_int_larray_lgroup_key",
"larray/tests/test_array.py::test_getitem_single_larray_key_guess",
"larray/tests/test_array.py::test_group_agg_on_group_agg_nokw",
"larray/tests/test_array.py::test_median_full_axes",
"larray/tests/test_array.py::test_str",
"larray/tests/test_array.py::test_values",
"larray/tests/test_array.py::test_set",
"larray/tests/test_array.py::test_iter",
"larray/tests/test_array.py::test_plot",
"larray/tests/test_array.py::test_comparison_ops",
"larray/tests/test_array.py::test_getitem",
"larray/tests/test_array.py::test_total",
"larray/tests/test_array.py::test_to_series",
"larray/tests/test_array.py::test_contains",
"larray/tests/test_array.py::test_broadcast_with",
"larray/tests/test_array.py::test_dump",
"larray/tests/test_array.py::test_from_string",
"larray/tests/test_array.py::test_positional_indexer_getitem",
"larray/tests/test_array.py::test_percent",
"larray/tests/test_array.py::test_reindex",
"larray/tests/test_array.py::test_key_string_split",
"larray/tests/test_array.py::test_sum_full_axes",
"larray/tests/test_array.py::test_zeros",
"larray/tests/test_array.py::test_agg_by",
"larray/tests/test_array.py::test_group_agg_anonymous_axis",
"larray/tests/test_array.py::test_ipoints_indexer_getitem",
"larray/tests/test_array.py::test_setitem_larray",
"larray/tests/test_array.py::test_getitem_abstract_positional",
"larray/tests/test_array.py::test_info",
"larray/tests/test_array.py::test_expand",
"larray/tests/test_array.py::test_key_string_nonstring",
"larray/tests/test_array.py::test_read_csv",
"larray/tests/test_array.py::test_ipoints_indexer_setitem",
"larray/tests/test_array.py::test_set_axes",
"larray/tests/test_array.py::test_group_agg_label_group_no_axis",
"larray/tests/test_array.py::test_broadcasting_no_name",
"larray/tests/test_array.py::test_group_agg_on_int_array",
"larray/tests/test_array.py::test_filter_on_group_agg",
"larray/tests/test_array.py::test_to_frame",
"larray/tests/test_array.py::test_zeros_like",
"larray/tests/test_array.py::test_agg_kwargs",
"larray/tests/test_array.py::test_group_agg_on_bool_array",
"larray/tests/test_array.py::test_sort_values",
"larray/tests/test_array.py::test_sum_with_groups_from_other_axis",
"larray/tests/test_array.py::test_0darray_convert",
"larray/tests/test_array.py::test_setitem_bool_array_key",
"larray/tests/test_array.py::test_setitem_scalar",
"larray/tests/test_array.py::test_unary_ops",
"larray/tests/test_array.py::test_deprecated_methods",
"larray/tests/test_array.py::test_read_eurostat",
"larray/tests/test_array.py::test_group_agg_kwargs",
"larray/tests/test_array.py::test_getitem_bool_larray_key_arr_wh_bool_axis",
"larray/tests/test_array.py::test_getitem_igroup_on_int_axis",
"larray/tests/test_array.py::test_read_set_update_delete_metadata",
"larray/tests/test_array.py::test_mean",
"larray/tests/test_array.py::test_getitem_int_ndarray_key_guess",
"larray/tests/test_array.py::test_from_frame",
"larray/tests/test_array.py::test_binary_ops_with_scalar_group",
"larray/tests/test_array.py::test_getitem_bool_larray_key_arr_whout_bool_axis",
"larray/tests/test_array.py::test_diag",
"larray/tests/test_array.py::test_from_lists",
"larray/tests/test_array.py::test_shift_axis",
"larray/tests/test_array.py::test_split_axes",
"larray/tests/test_array.py::test_unique",
"larray/tests/test_array.py::test_transpose",
"larray/tests/test_array.py::test_positional_indexer_setitem",
"larray/tests/test_array.py::test_getitem_on_group_agg",
"larray/tests/test_array.py::test_growth_rate",
"larray/tests/test_array.py::test_filter_multiple_axes",
"larray/tests/test_array.py::test_to_csv",
"larray/tests/test_array.py::test_getitem_bool_anonymous_axes",
"larray/tests/test_array.py::test_where",
"larray/tests/test_array.py::test_transpose_anonymous",
"larray/tests/test_array.py::test_nonzero",
"larray/tests/test_array.py::test_mean_full_axes",
"larray/tests/test_array.py::test_getitem_bool_ndarray_key_arr_whout_bool_axis",
"larray/tests/test_array.py::test_combine_axes",
"larray/tests/test_array.py::test_getitem_structured_key_with_groups",
"larray/tests/test_array.py::test_binary_ops",
"larray/tests/test_array.py::test_group_agg_zero_padded_label",
"larray/tests/test_array.py::test_rename",
"larray/tests/test_array.py::test_getitem_anonymous_axes",
"larray/tests/test_array.py::test_mean_groups",
"larray/tests/test_array.py::test_matmul",
"larray/tests/test_array.py::test_set_labels",
"larray/tests/test_array.py::test_stack_kwargs_no_axis_labels",
"larray/tests/test_array.py::test_sum_several_lg_groups",
"larray/tests/test_array.py::test_eye",
"larray/tests/test_array.py::test_getitem_positional_group",
"larray/tests/test_array.py::test_extend",
"larray/tests/test_array.py::test_agg_igroup",
"larray/tests/test_array.py::test_points_indexer_setitem",
"larray/tests/test_array.py::test_insert",
"larray/tests/test_array.py::test_key_string_slice_strings",
"larray/tests/test_array.py::test_binary_ops_expressions",
"larray/tests/test_array.py::test_append",
"larray/tests/test_array.py::test_getitem_str_positional_group",
"larray/tests/test_array.py::test_ndtest",
"larray/tests/test_array.py::test_getitem_on_group_agg_nokw",
"larray/tests/test_array.py::test_drop",
"larray/tests/test_array.py::test_larray_renamed_as_array",
"larray/tests/test_array.py::test_getitem_abstract_axes",
"larray/tests/test_array.py::test_percentile_full_axes",
"larray/tests/test_array.py::test_value_string_split",
"larray/tests/test_array.py::test_group_agg_axis_ref_label_group",
"larray/tests/test_array.py::test_median_groups",
"larray/tests/test_array.py::test_getitem_integer_string_axes",
"larray/tests/test_array.py::test_binary_ops_no_name_axes"
] |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 64