instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
django__asgiref-191
diff --git a/README.rst b/README.rst index ab1abc7..d1a9369 100644 --- a/README.rst +++ b/README.rst @@ -43,7 +43,11 @@ ASGI server. Note that exactly what threads things run in is very specific, and aimed to keep maximum compatibility with old synchronous code. See -"Synchronous code & Threads" below for a full explanation. +"Synchronous code & Threads" below for a full explanation. By default, +``sync_to_async`` will run all synchronous code in the program in the same +thread for safety reasons; you can disable this for more performance with +``@sync_to_async(thread_sensitive=False)``, but make sure that your code does +not rely on anything bound to threads (like database connections) when you do. Threadlocal replacement diff --git a/asgiref/sync.py b/asgiref/sync.py index a46f7d4..97b5d31 100644 --- a/asgiref/sync.py +++ b/asgiref/sync.py @@ -61,9 +61,17 @@ class AsyncToSync: except RuntimeError: # There's no event loop in this thread. Look for the threadlocal if # we're inside SyncToAsync - self.main_event_loop = getattr( - SyncToAsync.threadlocal, "main_event_loop", None + main_event_loop_pid = getattr( + SyncToAsync.threadlocal, "main_event_loop_pid", None ) + # We make sure the parent loop is from the same process - if + # they've forked, this is not going to be valid any more (#194) + if main_event_loop_pid and main_event_loop_pid == os.getpid(): + self.main_event_loop = getattr( + SyncToAsync.threadlocal, "main_event_loop", None + ) + else: + self.main_event_loop = None def __call__(self, *args, **kwargs): # You can't call AsyncToSync from a thread with a running event loop @@ -247,7 +255,7 @@ class SyncToAsync: # Single-thread executor for thread-sensitive code single_thread_executor = ThreadPoolExecutor(max_workers=1) - def __init__(self, func, thread_sensitive=False): + def __init__(self, func, thread_sensitive=True): self.func = func functools.update_wrapper(self, func) self._thread_sensitive = thread_sensitive @@ -312,6 +320,7 @@ class SyncToAsync: """ # Set the threadlocal for AsyncToSync self.threadlocal.main_event_loop = loop + self.threadlocal.main_event_loop_pid = os.getpid() # Set the task mapping (used for the locals module) current_thread = threading.current_thread() if AsyncToSync.launch_map.get(source_task) == current_thread: @@ -356,6 +365,11 @@ class SyncToAsync: return None -# Lowercase is more sensible for most things -sync_to_async = SyncToAsync +# Lowercase aliases (and decorator friendliness) async_to_sync = AsyncToSync + + +def sync_to_async(func=None, thread_sensitive=True): + if func is None: + return lambda f: SyncToAsync(f, thread_sensitive=thread_sensitive) + return SyncToAsync(func, thread_sensitive=thread_sensitive) diff --git a/asgiref/wsgi.py b/asgiref/wsgi.py index 8811118..40fba20 100644 --- a/asgiref/wsgi.py +++ b/asgiref/wsgi.py @@ -29,6 +29,7 @@ class WsgiToAsgiInstance: def __init__(self, wsgi_application): self.wsgi_application = wsgi_application self.response_started = False + self.response_content_length = None async def __call__(self, scope, receive, send): if scope["type"] != "http": @@ -114,6 +115,11 @@ class WsgiToAsgiInstance: (name.lower().encode("ascii"), value.encode("ascii")) for name, value in response_headers ] + # Extract content-length + self.response_content_length = None + for name, value in response_headers: + if name.lower() == "content-length": + self.response_content_length = int(value) # Build and send response start message. self.response_start = { "type": "http.response.start", @@ -130,14 +136,25 @@ class WsgiToAsgiInstance: # Translate the scope and incoming request body into a WSGI environ environ = self.build_environ(self.scope, body) # Run the WSGI app + bytes_sent = 0 for output in self.wsgi_application(environ, self.start_response): # If this is the first response, include the response headers if not self.response_started: self.response_started = True self.sync_send(self.response_start) + # If the application supplies a Content-Length header + if self.response_content_length is not None: + # The server should not transmit more bytes to the client than the header allows + bytes_allowed = self.response_content_length - bytes_sent + if len(output) > bytes_allowed: + output = output[:bytes_allowed] self.sync_send( {"type": "http.response.body", "body": output, "more_body": True} ) + bytes_sent += len(output) + # The server should stop iterating over the response when enough data has been sent + if bytes_sent == self.response_content_length: + break # Close connection if not self.response_started: self.response_started = True diff --git a/docs/conf.py b/docs/conf.py index 40499c5..6935f11 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -55,9 +55,9 @@ author = 'ASGI Team' # built documents. # # The short X.Y version. -version = '2.0' +version = '3.0' # The full version, including alpha/beta/rc tags. -release = '2.0' +release = '3.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/docs/extensions.rst b/docs/extensions.rst index 372ba20..aaf5764 100644 --- a/docs/extensions.rst +++ b/docs/extensions.rst @@ -77,3 +77,54 @@ and treat it as if the client had made a request. The ASGI server should set the pseudo ``:authority`` header value to be the same value as the request that triggered the push promise. + +Zero Copy Send +-------------- + +Zero Copy Send allows you to send the contents of a file descriptor to the +HTTP client with zero copy (where the underlying OS directly handles the data +transfer from a source file or socket without loading it into Python and +writing it out again). + +ASGI servers that implement this extension will provide +``http.response.zerocopysend`` in the extensions part of the scope:: + + "scope": { + ... + "extensions": { + "http.response.zerocopysend": {}, + }, + } + +The ASGI framework can initiate a zero-copy send by sending a message with +the following keys. This message can be sent at any time after the +*Response Start* message but before the final *Response Body* message, +and can be mixed with ``http.response.body``. It can also be called +multiple times in one response. Except for the characteristics of +zero-copy, it should behave the same as ordinary ``http.response.body``. + +Keys: + +* ``type`` (*Unicode string*): ``"http.response.zerocopysend"`` + +* ``file`` (*file descriptor object*): An opened file descriptor object + with an underlying OS file descriptor that can be used to call + ``os.sendfile``. (e.g. not BytesIO) + +* ``offset`` (*int*): Optional. If this value exists, it will specify + the offset at which sendfile starts to read data from ``file``. + Otherwise, it will be read from the current position of ``file``. + +* ``count`` (*int*): Optional. ``count`` is the number of bytes to + copy between the file descriptors. If omitted, the file will be read until + its end. + +* ``more_body`` (*bool*): Signifies if there is additional content + to come (as part of a Response Body message). If ``False``, response + will be taken as complete and closed, and any further messages on + the channel will be ignored. Optional; if missing defaults to + ``False``. + +After calling this extension to respond, the ASGI application itself should +actively close the used file descriptor - ASGI servers are not responsible for +closing descriptors. diff --git a/docs/implementations.rst b/docs/implementations.rst index 8b4da65..b4043af 100644 --- a/docs/implementations.rst +++ b/docs/implementations.rst @@ -75,3 +75,14 @@ Starlette Starlette is a minimalist ASGI library for writing against basic but powerful ``Request`` and ``Response`` classes. Supports HTTP. + + +rpc.py +------ + +*Beta* / https://github.com/abersheeran/rpc.py + +An easy-to-use and powerful RPC framework. RPC server base on WSGI & ASGI, client base +on ``httpx``. Supports synchronous functions, asynchronous functions, synchronous +generator functions, and asynchronous generator functions. Optional use of Type hint +for type conversion. Optional OpenAPI document generation.
django/asgiref
1c9d06329dbd679a7c564b0652147855a721edb4
diff --git a/tests/test_sync.py b/tests/test_sync.py index 5a4b342..911e719 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -1,4 +1,5 @@ import asyncio +import multiprocessing import threading import time from concurrent.futures import ThreadPoolExecutor @@ -279,11 +280,10 @@ def test_thread_sensitive_outside_sync(): await inner() # Inner sync function + @sync_to_async def inner(): result["thread"] = threading.current_thread() - inner = sync_to_async(inner, thread_sensitive=True) - # Run it middle() assert result["thread"] == threading.current_thread() @@ -300,22 +300,20 @@ async def test_thread_sensitive_outside_async(): result_2 = {} # Outer sync function + @sync_to_async def outer(result): middle(result) - outer = sync_to_async(outer, thread_sensitive=True) - # Middle async function @async_to_sync async def middle(result): await inner(result) # Inner sync function + @sync_to_async def inner(result): result["thread"] = threading.current_thread() - inner = sync_to_async(inner, thread_sensitive=True) - # Run it (in supposed parallel!) await asyncio.wait([outer(result_1), inner(result_2)]) @@ -338,22 +336,20 @@ def test_thread_sensitive_double_nested_sync(): await level2() # Sync level 2 + @sync_to_async def level2(): level3() - level2 = sync_to_async(level2, thread_sensitive=True) - # Async level 3 @async_to_sync async def level3(): await level4() # Sync level 2 + @sync_to_async def level4(): result["thread"] = threading.current_thread() - level4 = sync_to_async(level4, thread_sensitive=True) - # Run it level1() assert result["thread"] == threading.current_thread() @@ -369,22 +365,20 @@ async def test_thread_sensitive_double_nested_async(): result = {} # Sync level 1 + @sync_to_async def level1(): level2() - level1 = sync_to_async(level1, thread_sensitive=True) - # Async level 2 @async_to_sync async def level2(): await level3() # Sync level 3 + @sync_to_async def level3(): level4() - level3 = sync_to_async(level3, thread_sensitive=True) - # Async level 4 @async_to_sync async def level4(): @@ -395,6 +389,29 @@ async def test_thread_sensitive_double_nested_async(): assert result["thread"] == threading.current_thread() +def test_thread_sensitive_disabled(): + """ + Tests that we can disable thread sensitivity and make things run in + separate threads. + """ + + result = {} + + # Middle async function + @async_to_sync + async def middle(): + await inner() + + # Inner sync function + @sync_to_async(thread_sensitive=False) + def inner(): + result["thread"] = threading.current_thread() + + # Run it + middle() + assert result["thread"] != threading.current_thread() + + class ASGITest(TestCase): """ Tests collection of async cases inside classes @@ -415,3 +432,32 @@ def test_sync_to_async_detected_as_coroutinefunction(): assert not asyncio.iscoroutinefunction(sync_to_async) assert asyncio.iscoroutinefunction(sync_to_async(sync_func)) + + [email protected] +async def test_multiprocessing(): + """ + Tests that a forked process can use async_to_sync without it looking for + the event loop from the parent process. + """ + + test_queue = multiprocessing.Queue() + + async def async_process(): + test_queue.put(42) + + def sync_process(): + """Runs async_process synchronously""" + async_to_sync(async_process)() + + def fork_first(): + """Forks process before running sync_process""" + fork = multiprocessing.Process(target=sync_process) + fork.start() + fork.join(3) + # Force cleanup in failed test case + if fork.is_alive(): + fork.terminate() + return test_queue.get(True, 1) + + assert await sync_to_async(fork_first)() == 42 diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 3490573..6dcee1c 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -1,3 +1,5 @@ +import sys + import pytest from asgiref.testing import ApplicationCommunicator @@ -126,6 +128,130 @@ async def test_wsgi_empty_body(): assert (await instance.receive_output(1)) == {"type": "http.response.body"} [email protected] +async def test_wsgi_clamped_body(): + """ + Makes sure WsgiToAsgi clamps a body response longer than Content-Length + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "8")]) + return [b"0123", b"45", b"6789"] + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 200, + "headers": [(b"content-length", b"8")], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"0123", + "more_body": True, + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"45", + "more_body": True, + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"67", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + [email protected] +async def test_wsgi_stops_iterating_after_content_length_bytes(): + """ + Makes sure WsgiToAsgi does not iterate after than Content-Length bytes + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "4")]) + yield b"0123" + pytest.fail("WsgiToAsgi should not iterate after Content-Length bytes") + yield b"4567" + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 200, + "headers": [(b"content-length", b"4")], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"0123", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + [email protected] +async def test_wsgi_multiple_start_response(): + """ + Makes sure WsgiToAsgi only keep Content-Length from the last call to start_response + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "5")]) + try: + raise ValueError("Application Error") + except ValueError: + start_response("500 Server Error", [], sys.exc_info()) + return [b"Some long error message"] + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 500, + "headers": [], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"Some long error message", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + @pytest.mark.asyncio async def test_wsgi_multi_body(): """
Proposal: "http.response.sendfile" extension. Add the sendfile extension to allow ASGI programs to return response through `sendfile`. In `scope`: ```python "scope": { ... "extensions": { "http.response.sendfile": {}, }, } ``` Response: ```python await send({"type": "http.response.start", ...}) await send({"type": "http.response.sendfile", "file": file-obj}) ``` Some related links: https://docs.python.org/3.7/library/asyncio-eventloop.html#asyncio.loop.sendfile https://github.com/encode/uvicorn/issues/35
0.0
1c9d06329dbd679a7c564b0652147855a721edb4
[ "tests/test_sync.py::test_thread_sensitive_outside_sync", "tests/test_sync.py::test_thread_sensitive_outside_async", "tests/test_sync.py::test_thread_sensitive_double_nested_sync", "tests/test_sync.py::test_thread_sensitive_disabled", "tests/test_wsgi.py::test_wsgi_clamped_body", "tests/test_wsgi.py::test_wsgi_stops_iterating_after_content_length_bytes" ]
[ "tests/test_sync.py::test_sync_to_async", "tests/test_sync.py::test_sync_to_async_decorator", "tests/test_sync.py::test_nested_sync_to_async_retains_wrapped_function_attributes", "tests/test_sync.py::test_sync_to_async_method_decorator", "tests/test_sync.py::test_sync_to_async_method_self_attribute", "tests/test_sync.py::test_async_to_sync_to_async", "tests/test_sync.py::test_async_to_sync", "tests/test_sync.py::test_async_to_sync_decorator", "tests/test_sync.py::test_async_to_sync_method_decorator", "tests/test_sync.py::test_async_to_sync_in_async", "tests/test_sync.py::test_async_to_sync_in_thread", "tests/test_sync.py::test_async_to_async_method_self_attribute", "tests/test_sync.py::test_thread_sensitive_double_nested_async", "tests/test_sync.py::ASGITest::test_wrapped_case_is_collected", "tests/test_sync.py::test_sync_to_async_detected_as_coroutinefunction", "tests/test_sync.py::test_multiprocessing", "tests/test_wsgi.py::test_basic_wsgi", "tests/test_wsgi.py::test_wsgi_path_encoding", "tests/test_wsgi.py::test_wsgi_empty_body", "tests/test_wsgi.py::test_wsgi_multiple_start_response", "tests/test_wsgi.py::test_wsgi_multi_body" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-09-01 16:18:43+00:00
bsd-3-clause
1,935
django__asgiref-196
diff --git a/asgiref/wsgi.py b/asgiref/wsgi.py index 8811118..40fba20 100644 --- a/asgiref/wsgi.py +++ b/asgiref/wsgi.py @@ -29,6 +29,7 @@ class WsgiToAsgiInstance: def __init__(self, wsgi_application): self.wsgi_application = wsgi_application self.response_started = False + self.response_content_length = None async def __call__(self, scope, receive, send): if scope["type"] != "http": @@ -114,6 +115,11 @@ class WsgiToAsgiInstance: (name.lower().encode("ascii"), value.encode("ascii")) for name, value in response_headers ] + # Extract content-length + self.response_content_length = None + for name, value in response_headers: + if name.lower() == "content-length": + self.response_content_length = int(value) # Build and send response start message. self.response_start = { "type": "http.response.start", @@ -130,14 +136,25 @@ class WsgiToAsgiInstance: # Translate the scope and incoming request body into a WSGI environ environ = self.build_environ(self.scope, body) # Run the WSGI app + bytes_sent = 0 for output in self.wsgi_application(environ, self.start_response): # If this is the first response, include the response headers if not self.response_started: self.response_started = True self.sync_send(self.response_start) + # If the application supplies a Content-Length header + if self.response_content_length is not None: + # The server should not transmit more bytes to the client than the header allows + bytes_allowed = self.response_content_length - bytes_sent + if len(output) > bytes_allowed: + output = output[:bytes_allowed] self.sync_send( {"type": "http.response.body", "body": output, "more_body": True} ) + bytes_sent += len(output) + # The server should stop iterating over the response when enough data has been sent + if bytes_sent == self.response_content_length: + break # Close connection if not self.response_started: self.response_started = True
django/asgiref
cfd82e48a2059ff93ce20b94e1755c455e3c3d29
diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 3490573..6dcee1c 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -1,3 +1,5 @@ +import sys + import pytest from asgiref.testing import ApplicationCommunicator @@ -126,6 +128,130 @@ async def test_wsgi_empty_body(): assert (await instance.receive_output(1)) == {"type": "http.response.body"} [email protected] +async def test_wsgi_clamped_body(): + """ + Makes sure WsgiToAsgi clamps a body response longer than Content-Length + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "8")]) + return [b"0123", b"45", b"6789"] + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 200, + "headers": [(b"content-length", b"8")], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"0123", + "more_body": True, + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"45", + "more_body": True, + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"67", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + [email protected] +async def test_wsgi_stops_iterating_after_content_length_bytes(): + """ + Makes sure WsgiToAsgi does not iterate after than Content-Length bytes + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "4")]) + yield b"0123" + pytest.fail("WsgiToAsgi should not iterate after Content-Length bytes") + yield b"4567" + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 200, + "headers": [(b"content-length", b"4")], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"0123", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + [email protected] +async def test_wsgi_multiple_start_response(): + """ + Makes sure WsgiToAsgi only keep Content-Length from the last call to start_response + """ + + def wsgi_application(environ, start_response): + start_response("200 OK", [("Content-Length", "5")]) + try: + raise ValueError("Application Error") + except ValueError: + start_response("500 Server Error", [], sys.exc_info()) + return [b"Some long error message"] + + application = WsgiToAsgi(wsgi_application) + instance = ApplicationCommunicator( + application, + { + "type": "http", + "http_version": "1.0", + "method": "GET", + "path": "/", + "query_string": b"", + "headers": [], + }, + ) + await instance.send_input({"type": "http.request"}) + assert (await instance.receive_output(1)) == { + "type": "http.response.start", + "status": 500, + "headers": [], + } + assert (await instance.receive_output(1)) == { + "type": "http.response.body", + "body": b"Some long error message", + "more_body": True, + } + assert (await instance.receive_output(1)) == {"type": "http.response.body"} + + @pytest.mark.asyncio async def test_wsgi_multi_body(): """
WsgiToAsgi should stop sending response body after content-length bytes Hi, I was having issues when serving partial requests (using Range headers) from [whitenoise](https://github.com/evansd/whitenoise) wrapped in WsgiToAsgi. Some HTTP and ASGI servers in front of that complained about extra content in the response body (I've had the issue with traefik in front of uvicorn and with [uvicorn itself when using the httptools protocol handler](https://github.com/encode/uvicorn/blob/master/uvicorn/protocols/http/httptools_impl.py#L517)). One contributing factor is whitenoise which returns the file handle to the whole file in a [wsgiref.FileWrapper](https://github.com/python/cpython/blob/master/Lib/wsgiref/util.py#L11), seeked to the correct position for the range request. It then expects the server to only read as many bytes as defined in the Content-Length header. The [WSGI specs allows for this behavior](https://www.python.org/dev/peps/pep-3333/#handling-the-content-length-header) and [gunicorn implements it](https://github.com/benoitc/gunicorn/blob/master/gunicorn/http/wsgi.py#L333) and stops reading after as many bytes as specified in Content-Length. The [ASGI spec](https://asgi.readthedocs.io/en/latest/specs/www.html#http) does not say much about the consistency between Content-Length header and the "http.response.body" events. The relevant parts could be : > Protocol servers must flush any data passed to them into the send buffer before returning from a send call. > Yielding content from the WSGI application maps to sending http.response.body messages. The first one suggests that any piece of body from an "http.response.body" event must be sent, the other one could mean that all behavior defined for WSGI should apply to ASGI, including not-sending extra body, maybe ? [uvicorn](https://github.com/encode/uvicorn/blob/master/uvicorn/protocols/http/h11_impl.py#L475), [daphe](https://github.com/django/daphne/blob/master/daphne/http_protocol.py#L255) and [hypercorn](https://gitlab.com/pgjones/hypercorn/-/blob/master/src/hypercorn/protocol/http_stream.py#L147) lean more towards the first interpretation and pass through the whole readable content or simply raise an exception. If you agree that the WsgiToAsgi adapter should clamp the body I can work on a patch. Aside from this, the ASGI spec could probably be improved by defining this point. I don't really know if ASGI servers should prefer clamping or forwarding extra body responses but I have the vague feeling that allowing ASGI events to generate incorrectly framed HTTP messages could generate hard to diagnose issues in the future without providing any benefit. If the sendfile extension from #184 is added, the same point will probably arise, it would be very inconvenient to only be able to use sendfile when serving whole files. WSGI also specifies the clamping behavior [when using sendfile](https://www.python.org/dev/peps/pep-3333/#optional-platform-specific-file-handling) and [gunicorn](https://github.com/benoitc/gunicorn/blob/master/gunicorn/http/wsgi.py#L365) implements it.
0.0
cfd82e48a2059ff93ce20b94e1755c455e3c3d29
[ "tests/test_wsgi.py::test_wsgi_clamped_body", "tests/test_wsgi.py::test_wsgi_stops_iterating_after_content_length_bytes" ]
[ "tests/test_wsgi.py::test_basic_wsgi", "tests/test_wsgi.py::test_wsgi_path_encoding", "tests/test_wsgi.py::test_wsgi_empty_body", "tests/test_wsgi.py::test_wsgi_multiple_start_response", "tests/test_wsgi.py::test_wsgi_multi_body" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2020-09-16 19:11:25+00:00
bsd-3-clause
1,936
django__asgiref-211
diff --git a/asgiref/server.py b/asgiref/server.py index 9fd2e0c..a83b7bf 100644 --- a/asgiref/server.py +++ b/asgiref/server.py @@ -3,6 +3,8 @@ import logging import time import traceback +from .compatibility import guarantee_single_callable + logger = logging.getLogger(__name__) @@ -84,10 +86,11 @@ class StatelessServer: self.delete_oldest_application_instance() # Make an instance of the application input_queue = asyncio.Queue() - application_instance = self.application(scope=scope) + application_instance = guarantee_single_callable(self.application) # Run it, and stash the future for later checking future = asyncio.ensure_future( application_instance( + scope=scope, receive=input_queue.get, send=lambda message: self.application_send(scope, message), )
django/asgiref
5c249e818bd5e7acef957e236535098c3aff7b42
diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..77bbd4d --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,11 @@ +from asgiref.server import StatelessServer + + +def test_stateless_server(): + """StatlessServer can be instantiated with an ASGI 3 application.""" + + async def app(scope, receive, send): + pass + + server = StatelessServer(app) + server.get_or_create_application_instance("scope_id", {})
Has StatelessServer been updated to the ASGI 3.0 spec? I'm currently trying to upgrade my app from Channels 2.4.0 to Channels 3.0.0 and I'm having issues with running my worker. After some investigation, I'm under the impression that the `StatelessServer` provided in `asgiref` hasn't been updated to the new Application specifications in ASGI 3.0. Part of StatelessServer that is trying to instantiate an application with a scope, then call it using the receive and send arguments: https://github.com/django/asgiref/blob/5c249e818bd5e7acef957e236535098c3aff7b42/asgiref/server.py#L87-L94 Specification for the new Application format: https://asgi.readthedocs.io/en/latest/specs/main.html#applications That is: `coroutine application(scope, receive, send)` Since the Worker in Channels is based on `StatelessServer`, this is breaking the worker functionality in Channels 3.0.0. Is this something that is in the works? Anything I can do to help with this?
0.0
5c249e818bd5e7acef957e236535098c3aff7b42
[ "tests/test_server.py::test_stateless_server" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-11-05 02:42:27+00:00
bsd-3-clause
1,937
django__asgiref-239
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 3c617e8..e4ed96f 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,9 @@ +Pending +------- + +* async_to_sync and sync_to_async now check their arguments are functions of + the correct type. + 3.3.1 (2020-11-09) ------------------ diff --git a/asgiref/sync.py b/asgiref/sync.py index 869fb48..a8d91ea 100644 --- a/asgiref/sync.py +++ b/asgiref/sync.py @@ -101,6 +101,8 @@ class AsyncToSync: executors = Local() def __init__(self, awaitable, force_new_loop=False): + if not callable(awaitable) or not asyncio.iscoroutinefunction(awaitable): + raise TypeError("async_to_sync can only be applied to async functions.") self.awaitable = awaitable try: self.__self__ = self.awaitable.__self__ @@ -325,6 +327,8 @@ class SyncToAsync: ) def __init__(self, func, thread_sensitive=True): + if not callable(func) or asyncio.iscoroutinefunction(func): + raise TypeError("sync_to_async can only be applied to sync functions.") self.func = func functools.update_wrapper(self, func) self._thread_sensitive = thread_sensitive
django/asgiref
6469d0f3486dae0b6229e12d32ae6695600ed3ec
diff --git a/tests/test_sync.py b/tests/test_sync.py index 5e9c171..5f9d9ec 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -45,6 +45,34 @@ async def test_sync_to_async(): loop.set_default_executor(old_executor) +def test_sync_to_async_fail_non_function(): + """ + async_to_sync raises a TypeError when called with a non-function. + """ + with pytest.raises(TypeError) as excinfo: + sync_to_async(1) + + assert excinfo.value.args == ( + "sync_to_async can only be applied to sync functions.", + ) + + [email protected] +async def test_sync_to_async_fail_async(): + """ + sync_to_async raises a TypeError when applied to a sync function. + """ + with pytest.raises(TypeError) as excinfo: + + @sync_to_async + async def test_function(): + pass + + assert excinfo.value.args == ( + "sync_to_async can only be applied to sync functions.", + ) + + @pytest.mark.asyncio async def test_sync_to_async_decorator(): """ @@ -152,6 +180,33 @@ async def test_async_to_sync_to_async(): assert result["thread"] == threading.current_thread() +def test_async_to_sync_fail_non_function(): + """ + async_to_sync raises a TypeError when applied to a non-function. + """ + with pytest.raises(TypeError) as excinfo: + async_to_sync(1) + + assert excinfo.value.args == ( + "async_to_sync can only be applied to async functions.", + ) + + +def test_async_to_sync_fail_sync(): + """ + async_to_sync raises a TypeError when applied to a sync function. + """ + with pytest.raises(TypeError) as excinfo: + + @async_to_sync + def test_function(self): + pass + + assert excinfo.value.args == ( + "async_to_sync can only be applied to async functions.", + ) + + def test_async_to_sync(): """ Tests we can call async_to_sync outside of an outer event loop.
Prevent accidental mixup of sync_to_async / async_to_sync Putting `sync_to_async` onto an `async def` silently breaks it. Instead, it would be good if that raised an error at decorator application time - and likewise for the opposite case.
0.0
6469d0f3486dae0b6229e12d32ae6695600ed3ec
[ "tests/test_sync.py::test_sync_to_async_fail_non_function", "tests/test_sync.py::test_sync_to_async_fail_async", "tests/test_sync.py::test_async_to_sync_fail_non_function", "tests/test_sync.py::test_async_to_sync_fail_sync" ]
[ "tests/test_sync.py::test_sync_to_async", "tests/test_sync.py::test_sync_to_async_decorator", "tests/test_sync.py::test_nested_sync_to_async_retains_wrapped_function_attributes", "tests/test_sync.py::test_sync_to_async_method_decorator", "tests/test_sync.py::test_sync_to_async_method_self_attribute", "tests/test_sync.py::test_async_to_sync_to_async", "tests/test_sync.py::test_async_to_sync", "tests/test_sync.py::test_async_to_sync_decorator", "tests/test_sync.py::test_async_to_sync_method_decorator", "tests/test_sync.py::test_async_to_sync_in_async", "tests/test_sync.py::test_async_to_sync_in_thread", "tests/test_sync.py::test_async_to_async_method_self_attribute", "tests/test_sync.py::test_thread_sensitive_outside_sync", "tests/test_sync.py::test_thread_sensitive_outside_async", "tests/test_sync.py::test_thread_sensitive_with_context_matches", "tests/test_sync.py::test_thread_sensitive_nested_context", "tests/test_sync.py::test_thread_sensitive_context_without_sync_work", "tests/test_sync.py::test_thread_sensitive_double_nested_sync", "tests/test_sync.py::test_thread_sensitive_double_nested_async", "tests/test_sync.py::test_thread_sensitive_disabled", "tests/test_sync.py::ASGITest::test_wrapped_case_is_collected", "tests/test_sync.py::test_sync_to_async_detected_as_coroutinefunction", "tests/test_sync.py::test_multiprocessing" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-02-09 09:21:06+00:00
bsd-3-clause
1,938
django__asgiref-320
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8a05077..0379a31 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,7 +6,7 @@ repos: args: ["--py37-plus"] - repo: https://github.com/psf/black - rev: 20.8b1 + rev: 22.3.0 hooks: - id: black args: ["--target-version=py37"] diff --git a/asgiref/sync.py b/asgiref/sync.py index b71b379..a70dac1 100644 --- a/asgiref/sync.py +++ b/asgiref/sync.py @@ -1,3 +1,4 @@ +import asyncio import asyncio.coroutines import contextvars import functools @@ -101,6 +102,10 @@ class AsyncToSync: # Local, not a threadlocal, so that tasks can work out what their parent used. executors = Local() + # When we can't find a CurrentThreadExecutor from the context, such as + # inside create_task, we'll look it up here from the running event loop. + loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {} + def __init__(self, awaitable, force_new_loop=False): if not callable(awaitable) or not _iscoroutinefunction_or_partial(awaitable): # Python does not have very reliable detection of async functions @@ -164,6 +169,7 @@ class AsyncToSync: old_current_executor = None current_executor = CurrentThreadExecutor() self.executors.current = current_executor + loop = None # Use call_soon_threadsafe to schedule a synchronous callback on the # main event loop's thread if it's there, otherwise make a new loop # in this thread. @@ -175,6 +181,7 @@ class AsyncToSync: if not (self.main_event_loop and self.main_event_loop.is_running()): # Make our own event loop - in a new thread - and run inside that. loop = asyncio.new_event_loop() + self.loop_thread_executors[loop] = current_executor loop_executor = ThreadPoolExecutor(max_workers=1) loop_future = loop_executor.submit( self._run_event_loop, loop, awaitable @@ -194,6 +201,8 @@ class AsyncToSync: current_executor.run_until_future(call_result) finally: # Clean up any executor we were running + if loop is not None: + del self.loop_thread_executors[loop] if hasattr(self.executors, "current"): del self.executors.current if old_current_executor: @@ -378,6 +387,9 @@ class SyncToAsync: # Create new thread executor in current context executor = ThreadPoolExecutor(max_workers=1) self.context_to_thread_executor[thread_sensitive_context] = executor + elif loop in AsyncToSync.loop_thread_executors: + # Re-use thread executor for running loop + executor = AsyncToSync.loop_thread_executors[loop] elif self.deadlock_context and self.deadlock_context.get(False): raise RuntimeError( "Single thread executor already being used, would deadlock"
django/asgiref
cde961b13c69b90216c4c1c81d1ad1ca1bc22b48
diff --git a/tests/test_server.py b/tests/test_server.py index 8f86096..616ccf2 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -21,7 +21,8 @@ class Server(StatelessServer): application, max_applications=max_applications, ) - self._sock = sock.socket(sock.AF_INET, sock.SOCK_DGRAM | sock.SOCK_NONBLOCK) + self._sock = sock.socket(sock.AF_INET, sock.SOCK_DGRAM) + self._sock.setblocking(False) self._sock.bind(("127.0.0.1", 0)) @property @@ -54,7 +55,8 @@ class Server(StatelessServer): class Client: def __init__(self, name): - self._sock = sock.socket(sock.AF_INET, sock.SOCK_DGRAM | sock.SOCK_NONBLOCK) + self._sock = sock.socket(sock.AF_INET, sock.SOCK_DGRAM) + self._sock.setblocking(False) self.name = name async def register(self, server_addr, name=None): diff --git a/tests/test_sync.py b/tests/test_sync.py index 8f563d9..2837423 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -397,15 +397,21 @@ def test_thread_sensitive_outside_sync(): @async_to_sync async def middle(): await inner() + await asyncio.create_task(inner_task()) - # Inner sync function + # Inner sync functions @sync_to_async def inner(): result["thread"] = threading.current_thread() + @sync_to_async + def inner_task(): + result["thread2"] = threading.current_thread() + # Run it middle() assert result["thread"] == threading.current_thread() + assert result["thread2"] == threading.current_thread() @pytest.mark.asyncio
sync_to_async does not find root thread inside a task When you use `create_task` (or any way of making a coroutine not through asgiref), and the root thread is synchronous, then `sync_to_async` in thread-sensitive mode will use the root thread outside of tasks and a single, specific new thread inside of tasks, ruining the thread-sensitive guarantee. Instead, we should make `sync_to_async` always first look for an executor on the root thread and, if it finds it, use that to run code.
0.0
cde961b13c69b90216c4c1c81d1ad1ca1bc22b48
[ "tests/test_sync.py::test_thread_sensitive_outside_sync" ]
[ "tests/test_server.py::test_stateless_server", "tests/test_server.py::test_server_delete_instance", "tests/test_sync.py::test_sync_to_async", "tests/test_sync.py::test_sync_to_async_fail_non_function", "tests/test_sync.py::test_sync_to_async_fail_async", "tests/test_sync.py::test_async_to_sync_fail_partial", "tests/test_sync.py::test_sync_to_async_decorator", "tests/test_sync.py::test_nested_sync_to_async_retains_wrapped_function_attributes", "tests/test_sync.py::test_sync_to_async_method_decorator", "tests/test_sync.py::test_sync_to_async_method_self_attribute", "tests/test_sync.py::test_async_to_sync_to_async", "tests/test_sync.py::test_async_to_sync_fail_non_function", "tests/test_sync.py::test_async_to_sync_fail_sync", "tests/test_sync.py::test_async_to_sync", "tests/test_sync.py::test_async_to_sync_decorator", "tests/test_sync.py::test_async_to_sync_method_decorator", "tests/test_sync.py::test_async_to_sync_in_async", "tests/test_sync.py::test_async_to_sync_in_thread", "tests/test_sync.py::test_async_to_sync_in_except", "tests/test_sync.py::test_async_to_sync_partial", "tests/test_sync.py::test_async_to_sync_method_self_attribute", "tests/test_sync.py::test_thread_sensitive_outside_async", "tests/test_sync.py::test_thread_sensitive_with_context_matches", "tests/test_sync.py::test_thread_sensitive_nested_context", "tests/test_sync.py::test_thread_sensitive_context_without_sync_work", "tests/test_sync.py::test_thread_sensitive_double_nested_sync", "tests/test_sync.py::test_thread_sensitive_double_nested_async", "tests/test_sync.py::test_thread_sensitive_disabled", "tests/test_sync.py::ASGITest::test_wrapped_case_is_collected", "tests/test_sync.py::test_sync_to_async_detected_as_coroutinefunction", "tests/test_sync.py::test_multiprocessing", "tests/test_sync.py::test_sync_to_async_uses_executor", "tests/test_sync.py::test_sync_to_async_deadlock_raises", "tests/test_sync.py::test_sync_to_async_deadlock_ignored_with_exception", "tests/test_sync.py::test_sync_to_async_with_blocker_non_thread_sensitive" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-18 19:33:50+00:00
bsd-3-clause
1,939
django__asgiref-325
diff --git a/asgiref/sync.py b/asgiref/sync.py index a70dac1..d02bd4a 100644 --- a/asgiref/sync.py +++ b/asgiref/sync.py @@ -107,7 +107,12 @@ class AsyncToSync: loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {} def __init__(self, awaitable, force_new_loop=False): - if not callable(awaitable) or not _iscoroutinefunction_or_partial(awaitable): + if not callable(awaitable) or ( + not _iscoroutinefunction_or_partial(awaitable) + and not _iscoroutinefunction_or_partial( + getattr(awaitable, "__call__", awaitable) + ) + ): # Python does not have very reliable detection of async functions # (lots of false negatives) so this is just a warning. warnings.warn(
django/asgiref
12f6355d50c271aab821a37dbf2cde5863cc2643
diff --git a/tests/test_sync.py b/tests/test_sync.py index 2837423..c5677fc 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -3,6 +3,7 @@ import functools import multiprocessing import threading import time +import warnings from concurrent.futures import ThreadPoolExecutor from functools import wraps from unittest import TestCase @@ -365,6 +366,29 @@ def test_async_to_sync_partial(): assert result["worked"] +def test_async_to_sync_on_callable_object(): + """ + Tests async_to_sync on a callable class instance + """ + + result = {} + + class CallableClass: + async def __call__(self, value): + await asyncio.sleep(0) + result["worked"] = True + return value + + # Run it (without warnings) + with warnings.catch_warnings(): + warnings.simplefilter("error") + sync_function = async_to_sync(CallableClass()) + out = sync_function(42) + + assert out == 42 + assert result["worked"] is True + + def test_async_to_sync_method_self_attribute(): """ Tests async_to_sync on a method copies __self__.
`sync.async_to_sync` incorrectly warns "a non-async-marked callable" for async callable class instance Repro ```python from asgiref.sync import async_to_sync class CallableClass: async def __call__(self): return None async_to_sync(CallableClass()) ``` Yields the `UserWarning` ``` UserWarning: async_to_sync was passed a non-async-marked callable ``` Though the code works at runtime.
0.0
12f6355d50c271aab821a37dbf2cde5863cc2643
[ "tests/test_sync.py::test_async_to_sync_on_callable_object" ]
[ "tests/test_sync.py::test_sync_to_async", "tests/test_sync.py::test_sync_to_async_fail_non_function", "tests/test_sync.py::test_sync_to_async_fail_async", "tests/test_sync.py::test_async_to_sync_fail_partial", "tests/test_sync.py::test_sync_to_async_decorator", "tests/test_sync.py::test_nested_sync_to_async_retains_wrapped_function_attributes", "tests/test_sync.py::test_sync_to_async_method_decorator", "tests/test_sync.py::test_sync_to_async_method_self_attribute", "tests/test_sync.py::test_async_to_sync_to_async", "tests/test_sync.py::test_async_to_sync_fail_non_function", "tests/test_sync.py::test_async_to_sync_fail_sync", "tests/test_sync.py::test_async_to_sync", "tests/test_sync.py::test_async_to_sync_decorator", "tests/test_sync.py::test_async_to_sync_method_decorator", "tests/test_sync.py::test_async_to_sync_in_async", "tests/test_sync.py::test_async_to_sync_in_thread", "tests/test_sync.py::test_async_to_sync_in_except", "tests/test_sync.py::test_async_to_sync_partial", "tests/test_sync.py::test_async_to_sync_method_self_attribute", "tests/test_sync.py::test_thread_sensitive_outside_sync", "tests/test_sync.py::test_thread_sensitive_outside_async", "tests/test_sync.py::test_thread_sensitive_with_context_matches", "tests/test_sync.py::test_thread_sensitive_nested_context", "tests/test_sync.py::test_thread_sensitive_context_without_sync_work", "tests/test_sync.py::test_thread_sensitive_double_nested_sync", "tests/test_sync.py::test_thread_sensitive_double_nested_async", "tests/test_sync.py::test_thread_sensitive_disabled", "tests/test_sync.py::ASGITest::test_wrapped_case_is_collected", "tests/test_sync.py::test_sync_to_async_detected_as_coroutinefunction", "tests/test_sync.py::test_multiprocessing", "tests/test_sync.py::test_sync_to_async_uses_executor", "tests/test_sync.py::test_sync_to_async_deadlock_raises", "tests/test_sync.py::test_sync_to_async_deadlock_ignored_with_exception", "tests/test_sync.py::test_sync_to_async_with_blocker_non_thread_sensitive" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-05-10 11:58:24+00:00
bsd-3-clause
1,940
django__channels_redis-274
diff --git a/channels_redis/core.py b/channels_redis/core.py index af288bd..94531e9 100644 --- a/channels_redis/core.py +++ b/channels_redis/core.py @@ -1,6 +1,5 @@ import asyncio import base64 -import binascii import collections import functools import hashlib @@ -18,6 +17,8 @@ import msgpack from channels.exceptions import ChannelFull from channels.layers import BaseChannelLayer +from .utils import _consistent_hash + logger = logging.getLogger(__name__) AIOREDIS_VERSION = tuple(map(int, aioredis.__version__.split("."))) @@ -858,15 +859,7 @@ class RedisChannelLayer(BaseChannelLayer): ### Internal functions ### def consistent_hash(self, value): - """ - Maps the value to a node value between 0 and 4095 - using CRC, then down to one of the ring nodes. - """ - if isinstance(value, str): - value = value.encode("utf8") - bigval = binascii.crc32(value) & 0xFFF - ring_divisor = 4096 / float(self.ring_size) - return int(bigval / ring_divisor) + return _consistent_hash(value, self.ring_size) def make_fernet(self, key): """ diff --git a/channels_redis/pubsub.py b/channels_redis/pubsub.py index 62907d5..b8d549e 100644 --- a/channels_redis/pubsub.py +++ b/channels_redis/pubsub.py @@ -8,6 +8,8 @@ import uuid import aioredis import msgpack +from .utils import _consistent_hash + logger = logging.getLogger(__name__) @@ -106,11 +108,7 @@ class RedisPubSubLoopLayer: """ Return the shard that is used exclusively for this channel or group. """ - if len(self._shards) == 1: - # Avoid the overhead of hashing and modulo when it is unnecessary. - return self._shards[0] - shard_index = abs(hash(channel_or_group_name)) % len(self._shards) - return self._shards[shard_index] + return self._shards[_consistent_hash(channel_or_group_name, len(self._shards))] def _get_group_channel_name(self, group): """ diff --git a/channels_redis/utils.py b/channels_redis/utils.py new file mode 100644 index 0000000..7b30fdc --- /dev/null +++ b/channels_redis/utils.py @@ -0,0 +1,17 @@ +import binascii + + +def _consistent_hash(value, ring_size): + """ + Maps the value to a node value between 0 and 4095 + using CRC, then down to one of the ring nodes. + """ + if ring_size == 1: + # Avoid the overhead of hashing and modulo when it is unnecessary. + return 0 + + if isinstance(value, str): + value = value.encode("utf8") + bigval = binascii.crc32(value) & 0xFFF + ring_divisor = 4096 / float(ring_size) + return int(bigval / ring_divisor)
django/channels_redis
49e419dce642b7aef12daa3fa8495f6b9beb1fbe
diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..3a78330 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,20 @@ +import pytest + +from channels_redis.utils import _consistent_hash + + [email protected]( + "value,ring_size,expected", + [ + ("key_one", 1, 0), + ("key_two", 1, 0), + ("key_one", 2, 1), + ("key_two", 2, 0), + ("key_one", 10, 6), + ("key_two", 10, 4), + (b"key_one", 10, 6), + (b"key_two", 10, 4), + ], +) +def test_consistent_hash_result(value, ring_size, expected): + assert _consistent_hash(value, ring_size) == expected
PubSub: Sharding broken with multiple workers or worker restarts The "classic" implementation selects shards like this: ``` def consistent_hash(self, value): """ Maps the value to a node value between 0 and 4095 using CRC, then down to one of the ring nodes. """ if isinstance(value, str): value = value.encode("utf8") bigval = binascii.crc32(value) & 0xFFF ring_divisor = 4096 / float(self.ring_size) return int(bigval / ring_divisor) ``` The PUBSUB implementation does this: ``` def _get_shard(self, channel_or_group_name): """ Return the shard that is used exclusively for this channel or group. """ if len(self._shards) == 1: # Avoid the overhead of hashing and modulo when it is unnecessary. return self._shards[0] shard_index = abs(hash(channel_or_group_name)) % len(self._shards) return self._shards[shard_index] ``` I was surprised that there's a difference when I first looked at this, but now this started to really bite us in production after we introduced sharding: `hash()` is not guaranteed to return the same thing across multiple invocations of `python`, even on the same machine, unless `PYTHONHASHSEED` is set manually, which probably no-one ever does. See https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED I think we should just use the same hash function across implementations. I'll send a PR :)
0.0
49e419dce642b7aef12daa3fa8495f6b9beb1fbe
[ "tests/test_utils.py::test_consistent_hash_result[key_one-1-0]", "tests/test_utils.py::test_consistent_hash_result[key_two-1-0]", "tests/test_utils.py::test_consistent_hash_result[key_one-2-1]", "tests/test_utils.py::test_consistent_hash_result[key_two-2-0]", "tests/test_utils.py::test_consistent_hash_result[key_one-10-6_0]", "tests/test_utils.py::test_consistent_hash_result[key_two-10-4_0]", "tests/test_utils.py::test_consistent_hash_result[key_one-10-6_1]", "tests/test_utils.py::test_consistent_hash_result[key_two-10-4_1]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-09-01 20:09:19+00:00
bsd-3-clause
1,941
django__daphne-396
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 630c0fa..31e4650 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -11,7 +11,14 @@ Unreleased range of versions does not represent a good use of maintainer time. Going forward the latest Twisted version will be required. -* Added `log-fmt` CLI argument. +* Set ``daphne`` as default ``Server`` header. + + This can be configured with the ``--server-name`` CLI argument. + + Added the new ``--no-server-name`` CLI argument to disable the ``Server`` + header, which is equivalent to ``--server-name=` (an empty name). + +* Added ``--log-fmt`` CLI argument. 3.0.2 (2021-04-07) ------------------ diff --git a/daphne/cli.py b/daphne/cli.py index 2e83a5c..accafe1 100755 --- a/daphne/cli.py +++ b/daphne/cli.py @@ -93,7 +93,7 @@ class CommandLineInterface: self.parser.add_argument( "--log-fmt", help="Log format to use", - default="%(asctime)-15s %(levelname)-8s %(message)s" + default="%(asctime)-15s %(levelname)-8s %(message)s", ) self.parser.add_argument( "--ping-interval", @@ -162,7 +162,10 @@ class CommandLineInterface: "--server-name", dest="server_name", help="specify which value should be passed to response header Server attribute", - default="Daphne", + default="daphne", + ) + self.parser.add_argument( + "--no-server-name", dest="server_name", action="store_const", const="" ) self.server = None diff --git a/daphne/http_protocol.py b/daphne/http_protocol.py index a289e93..f0657fd 100755 --- a/daphne/http_protocol.py +++ b/daphne/http_protocol.py @@ -249,8 +249,8 @@ class WebRequest(http.Request): # Write headers for header, value in message.get("headers", {}): self.responseHeaders.addRawHeader(header, value) - if self.server.server_name and self.server.server_name.lower() != "daphne": - self.setHeader(b"server", self.server.server_name.encode("utf-8")) + if self.server.server_name and not self.responseHeaders.hasHeader("server"): + self.setHeader(b"server", self.server.server_name.encode()) logger.debug( "HTTP %s response started for %s", message["status"], self.client_addr ) diff --git a/daphne/server.py b/daphne/server.py index 0d463d0..4334217 100755 --- a/daphne/server.py +++ b/daphne/server.py @@ -56,7 +56,7 @@ class Server: websocket_handshake_timeout=5, application_close_timeout=10, ready_callable=None, - server_name="Daphne", + server_name="daphne", # Deprecated and does not work, remove in version 2.2 ws_protocols=None, ):
django/daphne
87bc5a7975e3e77ec64a183058b6e875cf744cf4
diff --git a/tests/test_cli.py b/tests/test_cli.py index 17335ed..51eab2e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -240,3 +240,18 @@ class TestCLIInterface(TestCase): exc.exception.message, "--proxy-headers has to be passed for this parameter.", ) + + def test_custom_servername(self): + """ + Passing `--server-name` will set the default server header + from 'daphne' to the passed one. + """ + self.assertCLI([], {"server_name": "daphne"}) + self.assertCLI(["--server-name", ""], {"server_name": ""}) + self.assertCLI(["--server-name", "python"], {"server_name": "python"}) + + def test_no_servername(self): + """ + Passing `--no-server-name` will set server name to '' (empty string) + """ + self.assertCLI(["--no-server-name"], {"server_name": ""}) diff --git a/tests/test_http_response.py b/tests/test_http_response.py index 1fc2439..22f6480 100644 --- a/tests/test_http_response.py +++ b/tests/test_http_response.py @@ -13,9 +13,12 @@ class TestHTTPResponse(DaphneTestCase): Lowercases and sorts headers, and strips transfer-encoding ones. """ return sorted( - (name.lower(), value.strip()) - for name, value in headers - if name.lower() != b"transfer-encoding" + [(b"server", b"daphne")] + + [ + (name.lower(), value.strip()) + for name, value in headers + if name.lower() not in (b"server", b"transfer-encoding") + ] ) def encode_headers(self, headers):
`Daphne` sets `server='daphne'` header for `websocket` connections, but not for `http-requests` # Hi there, ( Correct me if i am wrong here ) Daphne ( by default ) doesn't set a server header. By default these servers sets a header to identify backend technologies: - [Uvicorn](github.com/encode/uvicorn) : uvicorn - [Hypercorn](https://gitlab.com/pgjones/hypercorn) : hypercorn-{implementation} - [Gunicorn](https://github.com/benoitc/gunicorn) : gunicorn/{version} # Why should we do it ? To allow technology detection by extensions like [Wappalyzer](https://github.com/AliasIO/wappalyzer/)
0.0
87bc5a7975e3e77ec64a183058b6e875cf744cf4
[ "tests/test_cli.py::TestCLIInterface::test_custom_servername", "tests/test_cli.py::TestCLIInterface::test_no_servername" ]
[ "tests/test_cli.py::TestEndpointDescriptions::testBasics", "tests/test_cli.py::TestEndpointDescriptions::testFileDescriptorBinding", "tests/test_cli.py::TestEndpointDescriptions::testMultipleEnpoints", "tests/test_cli.py::TestEndpointDescriptions::testTcpPortBindings", "tests/test_cli.py::TestEndpointDescriptions::testUnixSocketBinding", "tests/test_cli.py::TestCLIInterface::testCLIBasics", "tests/test_cli.py::TestCLIInterface::testCustomEndpoints", "tests/test_cli.py::TestCLIInterface::testMixedCLIEndpointCreation", "tests/test_cli.py::TestCLIInterface::testUnixSockets", "tests/test_cli.py::TestCLIInterface::test_custom_proxyhost", "tests/test_cli.py::TestCLIInterface::test_custom_proxyport", "tests/test_cli.py::TestCLIInterface::test_default_proxyheaders", "tests/test_http_response.py::TestHTTPResponse::test_body", "tests/test_http_response.py::TestHTTPResponse::test_chunked_response", "tests/test_http_response.py::TestHTTPResponse::test_chunked_response_empty", "tests/test_http_response.py::TestHTTPResponse::test_custom_status_code", "tests/test_http_response.py::TestHTTPResponse::test_headers", "tests/test_http_response.py::TestHTTPResponse::test_headers_type", "tests/test_http_response.py::TestHTTPResponse::test_headers_type_raw", "tests/test_http_response.py::TestHTTPResponse::test_minimal_response", "tests/test_http_response.py::TestHTTPResponse::test_status_code_required" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-28 12:08:39+00:00
bsd-3-clause
1,942
django__daphne-406
diff --git a/daphne/http_protocol.py b/daphne/http_protocol.py index 7df7bae..a289e93 100755 --- a/daphne/http_protocol.py +++ b/daphne/http_protocol.py @@ -50,6 +50,8 @@ class WebRequest(http.Request): ) # Shorten it a bit, bytes wise def __init__(self, *args, **kwargs): + self.client_addr = None + self.server_addr = None try: http.Request.__init__(self, *args, **kwargs) # Easy server link @@ -77,9 +79,6 @@ class WebRequest(http.Request): # requires unicode string. self.client_addr = [str(self.client.host), self.client.port] self.server_addr = [str(self.host.host), self.host.port] - else: - self.client_addr = None - self.server_addr = None self.client_scheme = "https" if self.isSecure() else "http"
django/daphne
6a5093982ca1eaffbc41f0114ac5bea7cb3902be
diff --git a/tests/test_http_protocol.py b/tests/test_http_protocol.py new file mode 100644 index 0000000..024479d --- /dev/null +++ b/tests/test_http_protocol.py @@ -0,0 +1,49 @@ +import unittest + +from daphne.http_protocol import WebRequest + + +class MockServer: + """ + Mock server object for testing. + """ + + def protocol_connected(self, *args, **kwargs): + pass + + +class MockFactory: + """ + Mock factory object for testing. + """ + + def __init__(self): + self.server = MockServer() + + +class MockChannel: + """ + Mock channel object for testing. + """ + + def __init__(self): + self.factory = MockFactory() + self.transport = None + + def getPeer(self, *args, **kwargs): + return "peer" + + def getHost(self, *args, **kwargs): + return "host" + + +class TestHTTPProtocol(unittest.TestCase): + """ + Tests the HTTP protocol classes. + """ + + def test_web_request_initialisation(self): + channel = MockChannel() + request = WebRequest(channel) + self.assertIsNone(request.client_addr) + self.assertIsNone(request.server_addr)
'WebRequest' object has no attribute 'client_addr' Hi, I've recently migrated my Django project from WSGI + gunicorn to ASGI + daphne. It's working great apart from an occasional error in my Sentry/logs `builtins.AttributeError: 'WebRequest' object has no attribute 'client_addr'`. It just seems to be the problem in the `log.debug` call on `connectionLost` in https://github.com/django/daphne/blob/main/daphne/http_protocol.py#L213 Looking at the class it seems that there is a chance that the `client_addr` is not set until later in the `process` method https://github.com/django/daphne/blob/main/daphne/http_protocol.py#L81 so there's a chance that the `self.client_addr` is simply not set. I can't replicate this error by any means, it happens only occasionally (I guess that's why it pops up in the `connectionLost` method). Should the `client_addr` be set to None by default so that this log message doesn't cause fatals? BTW I've seen https://github.com/django/daphne/issues/304 and https://github.com/django/daphne/issues/244. First one is giving 404 on SO, second one seems similar but they're mentioning websockets whereas I haven't even got to the point where I'm supporting websockets in my app. - Your OS and runtime environment, and browser if applicable Presumably platform browser agnostic. I don't have a reproduction method. - A `pip freeze` output showing your package versions channels==3.0.3 channels_redis==3.3.0 daphne==3.0.2 Django==3.2.6 - How you're running Channels (runserver? daphne/runworker? Nginx/Apache in front?) daphne on Heroku with `daphne my_app.asgi:application --port $PORT --bind 0.0.0.0 --verbosity 2` in Procfile - Console logs and full tracebacks of any errors ``` Jan 28 11:55:38 app/web.3 Unhandled Error Jan 28 11:55:38 app/web.3 Traceback (most recent call last): Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py", line 257, in run Jan 28 11:55:38 app/web.3 self._asyncioEventloop.run_forever() Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/asyncio/base_events.py", line 570, in run_forever Jan 28 11:55:38 app/web.3 self._run_once() Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once Jan 28 11:55:38 app/web.3 handle._run() Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/asyncio/events.py", line 81, in _run Jan 28 11:55:38 app/web.3 self._context.run(self._callback, *self._args) Jan 28 11:55:38 app/web.3 --- <exception caught here> --- Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/python/log.py", line 101, in callWithLogger Jan 28 11:55:38 app/web.3 return callWithContext({"system": lp}, func, *args, **kw) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/python/log.py", line 85, in callWithContext Jan 28 11:55:38 app/web.3 return context.call({ILogContext: newCtx}, func, *args, **kw) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/python/context.py", line 118, in callWithContext Jan 28 11:55:38 app/web.3 return self.currentContext().callWithContext(ctx, func, *args, **kw) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/python/context.py", line 83, in callWithContext Jan 28 11:55:38 app/web.3 return func(*args, **kw) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py", line 145, in _readOrWrite Jan 28 11:55:38 app/web.3 self._disconnectSelectable(selectable, why, read) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/internet/posixbase.py", line 300, in _disconnectSelectable Jan 28 11:55:38 app/web.3 selectable.readConnectionLost(f) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/internet/tcp.py", line 308, in readConnectionLost Jan 28 11:55:38 app/web.3 self.connectionLost(reason) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/internet/tcp.py", line 325, in connectionLost Jan 28 11:55:38 app/web.3 protocol.connectionLost(reason) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/twisted/web/http.py", line 2508, in connectionLost Jan 28 11:55:38 app/web.3 request.connectionLost(reason) Jan 28 11:55:38 app/web.3 File "/app/.heroku/python/lib/python3.8/site-packages/daphne/http_protocol.py", line 213, in connectionLost Jan 28 11:55:38 app/web.3 logger.debug("HTTP disconnect for %s", self.client_addr) Jan 28 11:55:38 app/web.3 builtins.AttributeError: 'WebRequest' object has no attribute 'client_addr' ```
0.0
6a5093982ca1eaffbc41f0114ac5bea7cb3902be
[ "tests/test_http_protocol.py::TestHTTPProtocol::test_web_request_initialisation" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-02-13 22:18:11+00:00
bsd-3-clause
1,943
django__daphne-500
diff --git a/daphne/http_protocol.py b/daphne/http_protocol.py index f0657fd..b7da1bf 100755 --- a/daphne/http_protocol.py +++ b/daphne/http_protocol.py @@ -9,7 +9,7 @@ from twisted.protocols.policies import ProtocolWrapper from twisted.web import http from zope.interface import implementer -from .utils import parse_x_forwarded_for +from .utils import HEADER_NAME_RE, parse_x_forwarded_for logger = logging.getLogger(__name__) @@ -69,6 +69,13 @@ class WebRequest(http.Request): def process(self): try: self.request_start = time.time() + + # Validate header names. + for name, _ in self.requestHeaders.getAllRawHeaders(): + if not HEADER_NAME_RE.fullmatch(name): + self.basic_error(400, b"Bad Request", "Invalid header name") + return + # Get upgrade header upgrade_header = None if self.requestHeaders.hasHeader(b"Upgrade"): diff --git a/daphne/utils.py b/daphne/utils.py index 81f1f9d..0699314 100644 --- a/daphne/utils.py +++ b/daphne/utils.py @@ -1,7 +1,12 @@ import importlib +import re from twisted.web.http_headers import Headers +# Header name regex as per h11. +# https://github.com/python-hyper/h11/blob/a2c68948accadc3876dffcf979d98002e4a4ed27/h11/_abnf.py#L10-L21 +HEADER_NAME_RE = re.compile(rb"[-!#$%&'*+.^_`|~0-9a-zA-Z]+") + def import_by_path(path): """
django/daphne
9a282dd6277f4b921e494a9fc30a534a7f0d6ca6
diff --git a/tests/test_http_request.py b/tests/test_http_request.py index 52f6dd1..dca5bd7 100644 --- a/tests/test_http_request.py +++ b/tests/test_http_request.py @@ -310,3 +310,15 @@ class TestHTTPRequest(DaphneTestCase): b"GET /?\xc3\xa4\xc3\xb6\xc3\xbc HTTP/1.0\r\n\r\n" ) self.assertTrue(response.startswith(b"HTTP/1.0 400 Bad Request")) + + def test_invalid_header_name(self): + """ + Tests that requests with invalid header names fail. + """ + # Test cases follow those used by h11 + # https://github.com/python-hyper/h11/blob/a2c68948accadc3876dffcf979d98002e4a4ed27/h11/tests/test_headers.py#L24-L35 + for header_name in [b"foo bar", b"foo\x00bar", b"foo\xffbar", b"foo\x01bar"]: + response = self.run_daphne_raw( + f"GET / HTTP/1.0\r\n{header_name}: baz\r\n\r\n".encode("ascii") + ) + self.assertTrue(response.startswith(b"HTTP/1.0 400 Bad Request"))
Daphne allows invalid characters within header names # The bug RFC 9110 defines the header names must consist of a single token, which is defined as follows: ``` token = 1*tchar tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA ; any VCHAR, except delimiters ``` When Daphne receives a request with a header name containing any or all of the following characters, it does not reject the message: ``` \x00\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f "(),/;<=>?@[/]{}\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef ``` Thus, when you send the following request: ``` GET / HTTP/1.1\r\n \x00\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f "(),/;<=>?@[/]{}\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef: whatever\r\n \r\n ``` Daphne's interpretation is as follows: ``` [ HTTPRequest( method=b'GET', uri=b'/', version=b'1.1', headers=[ (b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f "(),/;<=>?@[/]{}\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef', b'whatever'), ], body=b'', ), ] ``` (i.e. the invalid header name made it into the request unchanged) Nearly all other HTTP implementations reject the above request, including Uvicorn, Hypercorn, AIOHTTP, Apache httpd, Bun, CherryPy, Deno, FastHTTP, Go net/http, Gunicorn, H2O, Hyper, Jetty, libsoup, Lighttpd, Mongoose, Nginx, Node.js LiteSpeed, Passenger, Puma, Tomcat, OpenWrt uhttpd, Uvicorn, Waitress, WEBrick, and OpenBSD httpd. ## Your OS and runtime environment: ``` $ uname -a Linux de8a63fbb2f4 6.7.2-arch1-2 #1 SMP PREEMPT_DYNAMIC Wed, 31 Jan 2024 09:22:15 +0000 x86_64 GNU/Linux ``` ## `pip freeze`: ``` asgiref==3.7.2 attrs==23.2.0 autobahn==23.6.2 Automat==22.10.0 cffi==1.16.0 constantly==23.10.4 cryptography==42.0.2 Cython==0.29.32 daphne @ file:///app/daphne h2==4.1.0 hpack==4.0.0 hyperframe==6.0.1 hyperlink==21.0.0 idna==3.6 incremental==22.10.0 priority==1.3.0 pyasn1==0.5.1 pyasn1-modules==0.3.0 pycparser==2.21 Pygments==2.14.0 pyOpenSSL==24.0.0 python-afl==0.7.4 PyYAML==6.0 service-identity==24.1.0 six==1.16.0 Twisted==23.10.0 txaio==23.1.1 typing_extensions==4.9.0 zope.interface==6.1 ``` (Using Daphne built from main, with the latest commit being https://github.com/django/daphne/commit/993efe62ce9e9c1cd64c81b6ee7dfa7b819482c7 at the time of writing) ## How you're running Channels (runserver? daphne/runworker? Nginx/Apache in front?) Directly invoking Daphne from the command line. ## Console logs and full tracebacks of any errors N/A
0.0
9a282dd6277f4b921e494a9fc30a534a7f0d6ca6
[ "tests/test_http_request.py::TestHTTPRequest::test_invalid_header_name" ]
[ "tests/test_http_request.py::TestHTTPRequest::test_bad_requests", "tests/test_http_request.py::TestHTTPRequest::test_duplicate_headers", "tests/test_http_request.py::TestHTTPRequest::test_get_request", "tests/test_http_request.py::TestHTTPRequest::test_headers", "tests/test_http_request.py::TestHTTPRequest::test_headers_are_lowercased_and_stripped", "tests/test_http_request.py::TestHTTPRequest::test_kitchen_sink", "tests/test_http_request.py::TestHTTPRequest::test_minimal_request", "tests/test_http_request.py::TestHTTPRequest::test_post_request", "tests/test_http_request.py::TestHTTPRequest::test_raw_path", "tests/test_http_request.py::TestHTTPRequest::test_request_body_chunking", "tests/test_http_request.py::TestHTTPRequest::test_root_path_header", "tests/test_http_request.py::TestHTTPRequest::test_x_forwarded_for_ignored", "tests/test_http_request.py::TestHTTPRequest::test_x_forwarded_for_no_port", "tests/test_http_request.py::TestHTTPRequest::test_x_forwarded_for_parsed" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-02-10 14:23:01+00:00
bsd-3-clause
1,944
django__daphne-84
diff --git a/daphne/utils.py b/daphne/utils.py index b066433..8fc339b 100644 --- a/daphne/utils.py +++ b/daphne/utils.py @@ -1,6 +1,13 @@ from twisted.web.http_headers import Headers +def header_value(headers, header_name): + value = headers[header_name] + if isinstance(value, list): + value = value[0] + return value.decode("utf-8") + + def parse_x_forwarded_for(headers, address_header_name='X-Forwarded-For', port_header_name='X-Forwarded-Port', @@ -27,7 +34,7 @@ def parse_x_forwarded_for(headers, address_header_name = address_header_name.lower().encode("utf-8") result = original if address_header_name in headers: - address_value = headers[address_header_name][0].decode("utf-8") + address_value = header_value(headers, address_header_name) if ',' in address_value: address_value = address_value.split(",")[-1].strip() @@ -47,7 +54,7 @@ def parse_x_forwarded_for(headers, # header to avoid inconsistent results. port_header_name = port_header_name.lower().encode("utf-8") if port_header_name in headers: - port_value = headers[port_header_name][0].decode("utf-8") + port_value = header_value(headers, port_header_name) try: result[1] = int(port_value) except ValueError:
django/daphne
412d9a48dc30b0d43d8348f246f4b61efb6fca82
diff --git a/daphne/tests/test_utils.py b/daphne/tests/test_utils.py index 61fe1a3..10a10f3 100644 --- a/daphne/tests/test_utils.py +++ b/daphne/tests/test_utils.py @@ -7,9 +7,9 @@ from twisted.web.http_headers import Headers from ..utils import parse_x_forwarded_for -class TestXForwardedForParsing(TestCase): +class TestXForwardedForHttpParsing(TestCase): """ - Tests that the parse_x_forwarded_for util correcly parses headers. + Tests that the parse_x_forwarded_for util correctly parses twisted Header. """ def test_basic(self): @@ -59,3 +59,57 @@ class TestXForwardedForParsing(TestCase): def test_no_original(self): headers = Headers({}) self.assertIsNone(parse_x_forwarded_for(headers)) + + +class TestXForwardedForWsParsing(TestCase): + """ + Tests that the parse_x_forwarded_for util correctly parses dict headers. + """ + + def test_basic(self): + headers = { + b'X-Forwarded-For': b'10.1.2.3', + b'X-Forwarded-Port': b'1234', + } + self.assertEqual( + parse_x_forwarded_for(headers), + ['10.1.2.3', 1234] + ) + + def test_address_only(self): + headers = { + b'X-Forwarded-For': b'10.1.2.3', + } + self.assertEqual( + parse_x_forwarded_for(headers), + ['10.1.2.3', 0] + ) + + def test_port_in_address(self): + headers = { + b'X-Forwarded-For': b'10.1.2.3:5123', + } + self.assertEqual( + parse_x_forwarded_for(headers), + ['10.1.2.3', 5123] + ) + + def test_multiple_proxys(self): + headers = { + b'X-Forwarded-For': b'10.1.2.3, 10.1.2.4', + } + self.assertEqual( + parse_x_forwarded_for(headers), + ['10.1.2.4', 0] + ) + + def test_original(self): + headers = {} + self.assertEqual( + parse_x_forwarded_for(headers, original=['127.0.0.1', 80]), + ['127.0.0.1', 80] + ) + + def test_no_original(self): + headers = {} + self.assertIsNone(parse_x_forwarded_for(headers))
--proxy-headers error Hi, I just tested `daphne` with `--proxy-headers` behind a nginx server, and got the following exception when my browser initiates the websocket connection: ``` 2017-02-07 15:13:43,115 ERROR Traceback (most recent call last): File "/path/ve/local/lib/python2.7/site-packages/daphne/ws_protocol.py", line 62, in onConnect self.requestHeaders, AttributeError: 'WebSocketProtocol' object has no attribute 'requestHeaders' ``` I'm using the channels-examples/databinding app with the following virtualenv content: ``` appdirs==1.4.0 asgi-redis==1.0.0 asgiref==1.0.0 autobahn==0.17.1 channels==1.0.3 constantly==15.1.0 daphne==1.0.2 Django==1.10.5 incremental==16.10.1 msgpack-python==0.4.8 packaging==16.8 pyparsing==2.1.10 redis==2.10.5 six==1.10.0 Twisted==16.6.0 txaio==2.6.0 uWSGI==2.0.14 zope.interface==4.3.3 ``` Is it a version compatibility issue, or a bug maybe ? Thanks !
0.0
412d9a48dc30b0d43d8348f246f4b61efb6fca82
[ "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_address_only", "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_basic", "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_multiple_proxys", "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_port_in_address" ]
[ "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_address_only", "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_basic", "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_multiple_proxys", "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_no_original", "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_original", "daphne/tests/test_utils.py::TestXForwardedForHttpParsing::test_port_in_address", "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_no_original", "daphne/tests/test_utils.py::TestXForwardedForWsParsing::test_original" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-02-13 08:54:21+00:00
bsd-3-clause
1,945
dlce-eva__python-newick-45
diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ed832ef --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changes + +The `newick` package adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [v1.3.0] - 2021-05-04 + +Added support for reading and writing of node annotations (in comments). diff --git a/README.md b/README.md index f9cd4c8..4f6f695 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,44 @@ a `list` of `newick.Node` objects. >>> trees = read(pathlib.Path('fname')) ``` +### Supported Newick dialects + +The ["Newick specification"](http://biowiki.org/wiki/index.php/Newick_Format) states + +> Comments are enclosed in square brackets and may appear anywhere + +This has spawned a host of ad-hoc mechanisms to insert additional data into Newick trees. + +The `newick` package allows to deal with comments in two ways. + +- Ignoring comments: + ```python + >>> newick.loads('[a comment](a,b)c;', strip_comments=True)[0].newick + '(a,b)c' + ``` +- Reading comments as node annotations: Several software packages use Newick comments to + store node annotations, e.g. *BEAST, MrBayes or TreeAnnotator. Provided there are no + comments in places where they cannot be interpreted as node annotations, `newick` supports + reading and writing these annotations: + ```python + >>> newick.loads('(a[annotation],b)c;')[0].descendants[0].name + 'a' + >>> newick.loads('(a[annotation],b)c;')[0].descendants[0].comment + 'annotation' + >>> newick.loads('(a[annotation],b)c;')[0].newick + '(a[annotation],b)c' + ``` + +Note that square brackets inside *quoted labels* will **not** be interpreted as comments +or annotations: +```python +>>> newick.loads("('a[label]',b)c;")[0].descendants[0].name +"'a[label]'" +>>> newick.loads("('a[label]',b)c;")[0].newick +"('a[label]',b)c" +``` + + ## Writing Newick In parallel to the read operations there are three functions to serialize a single `Node` object or a `list` of `Node` diff --git a/src/newick.py b/src/newick.py index ac31951..b27c958 100644 --- a/src/newick.py +++ b/src/newick.py @@ -28,7 +28,7 @@ class Node(object): descendants. It further has an ancestor, which is *None* if the node is the root node of a tree. """ - def __init__(self, name=None, length=None, **kw): + def __init__(self, name=None, length=None, comment=None, **kw): """ :param name: Node label. :param length: Branch length from the new node to its parent. @@ -42,6 +42,7 @@ class Node(object): raise ValueError( 'Node names or branch lengths must not contain "%s"' % char) self.name = name + self.comment = comment self._length = length self.descendants = [] self.ancestor = None @@ -63,7 +64,7 @@ class Node(object): self._length = self._length_formatter(length_) @classmethod - def create(cls, name=None, length=None, descendants=None, **kw): + def create(cls, name=None, length=None, descendants=None, comment=None, **kw): """ Create a new `Node` object. @@ -73,7 +74,7 @@ class Node(object): :param kw: Additonal keyword arguments are passed through to `Node.__init__`. :return: `Node` instance. """ - node = cls(name=name, length=length, **kw) + node = cls(name=name, length=length, comment=comment, **kw) for descendant in descendants or []: node.add_descendant(descendant) return node @@ -86,6 +87,8 @@ class Node(object): def newick(self): """The representation of the Node in Newick format.""" label = self.name or '' + if self.comment: + label += '[{}]'.format(self.comment) if self._length: label += ':' + self._length descendants = ','.join([n.newick for n in self.descendants]) @@ -423,10 +426,16 @@ def write(tree, fname, encoding='utf8'): def _parse_name_and_length(s): - length = None + length, comment = None, None if ':' in s: - s, length = s.split(':', 1) - return s or None, length or None + parts = s.split(':') + if ']' not in parts[-1]: # A ] in length doesn't make sense - the : must be in a comment. + s = ':'.join(parts[:-1]) + length = parts[-1] + if '[' in s and s.endswith(']'): # This looks like a node annotation in a comment. + s, comment = s.split('[', maxsplit=1) + comment = comment[:-1] + return s or None, length or None, comment def _parse_siblings(s, **kw): @@ -434,11 +443,12 @@ def _parse_siblings(s, **kw): http://stackoverflow.com/a/26809037 """ bracket_level = 0 + square_bracket_level = 0 current = [] # trick to remove special-case of trailing chars for c in (s + ","): - if c == "," and bracket_level == 0: + if c == "," and bracket_level == 0 and square_bracket_level == 0: yield parse_node("".join(current), **kw) current = [] else: @@ -446,6 +456,10 @@ def _parse_siblings(s, **kw): bracket_level += 1 elif c == ")": bracket_level -= 1 + elif c == "[": + square_bracket_level += 1 + elif c == "]": + square_bracket_level -= 1 current.append(c) @@ -470,5 +484,5 @@ def parse_node(s, strip_comments=False, **kw): raise ValueError('unmatched braces %s' % parts[0][:100]) descendants = list(_parse_siblings(')'.join(parts[:-1])[1:], **kw)) label = parts[-1] - name, length = _parse_name_and_length(label) - return Node.create(name=name, length=length, descendants=descendants, **kw) + name, length, comment = _parse_name_and_length(label) + return Node.create(name=name, length=length, comment=comment, descendants=descendants, **kw)
dlce-eva/python-newick
da9132522ba05700fc0af50e5431eab36c294b3d
diff --git a/tests/test_newick.py b/tests/test_newick.py index 93dcace..24b4078 100644 --- a/tests/test_newick.py +++ b/tests/test_newick.py @@ -95,6 +95,7 @@ class TestNodeDescendantsFunctionality(unittest.TestCase): def test_read_write(tmp_path): trees = read(pathlib.Path(__file__).parent / 'fixtures' / 'tree-glottolog-newick.txt') + assert '[' in trees[0].descendants[0].name descs = [len(tree.descendants) for tree in trees] # The bookkeeping family has 391 languages assert descs[0] == 391 @@ -372,3 +373,22 @@ def test_prune_node(): t2 = loads(tree)[0] t2.prune_by_names(["E"]) assert t1.newick == t2.newick + + +def test_with_comments(): + nwk = "(1[x&dmv={1},dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range=" \ + "{0.001,1.336},height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0," \ + "height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634}," \ + "length_median=2.182,length_range={1.307,3.236}]:1.14538397925438," \ + "2[&dmv={1},dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range=" \ + "{0.001,1.336},height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0," \ + "height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634}," \ + "length_median=2.182,length_range={1.307,3.236}]:1.14538397925438)[y&dmv={1}," \ + "dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range={0.001,1.336}," \ + "height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0," \ + "height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634}," \ + "length_median=2.182,length_range={1.307,3.236}]" + tree = loads(nwk)[0] + assert tree.comment.startswith('y') + assert tree.descendants[0].name == '1' and tree.descendants[0].comment.startswith('x') + assert tree.newick == nwk \ No newline at end of file
Extended newick support I'd like to process trees output by StarBEAST, but it uses nested annotations that aren't supported. An example 2 leaf tree: ```python import newick tree = "(1[&dmv={1},dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range={0.001,1.336},height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0,height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634},length_median=2.182,length_range={1.307,3.236}]:1.14538397925438,2[&dmv={1},dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range={0.001,1.336},height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0,height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634},length_median=2.182,length_range={1.307,3.236}]:1.14538397925438)[&dmv={1},dmv1=0.260,dmv1_95%_hpd={0.003,0.625},dmv1_median=0.216,dmv1_range={0.001,1.336},height=1.310e-15,height_95%_hpd={0.0,3.552e-15},height_median=0.0,height_range={0.0,7.105e-15},length=2.188,length_95%_hpd={1.725,2.634},length_median=2.182,length_range={1.307,3.236}]" newick.loads(tree) ``` This fails with: ``` newick.loads(tree) File "/home/jk/.local/lib/python3.8/site-packages/newick.py", line 369, in loads return [parse_node(ss.strip(), **kw) for ss in s.split(';') if ss.strip()] File "/home/jk/.local/lib/python3.8/site-packages/newick.py", line 369, in <listcomp> return [parse_node(ss.strip(), **kw) for ss in s.split(';') if ss.strip()] File "/home/jk/.local/lib/python3.8/site-packages/newick.py", line 471, in parse_node return Node.create(name=name, length=length, descendants=descendants, **kw) File "/home/jk/.local/lib/python3.8/site-packages/newick.py", line 76, in create node = cls(name=name, length=length, **kw) File "/home/jk/.local/lib/python3.8/site-packages/newick.py", line 42, in __init__ raise ValueError( ValueError: Node names or branch lengths must not contain "," ``` It should be possible to make the parser a bit more sophisticated using regex so that stuff nested in the comment brackets isn't split. Would it be possible to add this feature, or is it outside the remit of the package? Thanks.
0.0
da9132522ba05700fc0af50e5431eab36c294b3d
[ "tests/test_newick.py::test_with_comments" ]
[ "tests/test_newick.py::test_empty_node", "tests/test_newick.py::test_empty_node_newick_representation", "tests/test_newick.py::test_empty_node_as_descendants_list", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_length_changeability", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_newick_representation_with_length", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_newick_representation_without_length", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_parameters_changeability", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_with_parameters_1", "tests/test_newick.py::TestNodeBasicFunctionality::test_node_with_parameters_2", "tests/test_newick.py::TestNodeDescendantsFunctionality::test_node_as_descendants_list", "tests/test_newick.py::TestNodeDescendantsFunctionality::test_node_representation_with_deeper_descendants_1___D1_1____D1_2____D1_3__", "tests/test_newick.py::TestNodeDescendantsFunctionality::test_node_representation_with_deeper_descendants_2___D__________", "tests/test_newick.py::TestNodeDescendantsFunctionality::test_node_representation_with_deeper_descendants_3_____________", "tests/test_newick.py::test_read_write", "tests/test_newick.py::test_Node", "tests/test_newick.py::test_repr", "tests/test_newick.py::test_Node_custom_length", "tests/test_newick.py::test_Node_ascii_art", "tests/test_newick.py::test_Node_ascii_art_singleton", "tests/test_newick.py::test_loads", "tests/test_newick.py::test_dumps", "tests/test_newick.py::test_clone", "tests/test_newick.py::test_leaf_functions", "tests/test_newick.py::test_prune[(A,((B,C),(D,E)))-A", "tests/test_newick.py::test_prune[((A,B),((C,D),(E,F)))-A", "tests/test_newick.py::test_prune[(b,(c,(d,(e,(f,g))h)i)a)-b", "tests/test_newick.py::test_prune[(b,(c,(d,(e,(f,g))h)i)a)-c", "tests/test_newick.py::test_prune_single_node_tree", "tests/test_newick.py::test_redundant_node_removal[((B:0.2,(C:0.3,D:0.4)E:0.5)F:0.1)A;-kw0-(B:0.2,(C:0.3,D:0.4)E:0.5)A:0.1]", "tests/test_newick.py::test_redundant_node_removal[((C)B)A-kw1-A]", "tests/test_newick.py::test_redundant_node_removal[((C)B)A-kw2-C]", "tests/test_newick.py::test_redundant_node_removal[((aiw),((aas,(kbt)),((abg),abf)))-kw3-(((aas,kbt),(abf,abg)),aiw)]", "tests/test_newick.py::test_prune_and_node_removal", "tests/test_newick.py::test_stacked_redundant_node_removal", "tests/test_newick.py::test_polytomy_resolution", "tests/test_newick.py::test_name_removal", "tests/test_newick.py::test_internal_name_removal", "tests/test_newick.py::test_leaf_name_removal", "tests/test_newick.py::test_length_removal", "tests/test_newick.py::test_all_removal", "tests/test_newick.py::test_singletons", "tests/test_newick.py::test_comments", "tests/test_newick.py::test_get_node", "tests/test_newick.py::test_prune_node" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-04 18:11:44+00:00
apache-2.0
1,946
dlce-eva__python-nexus-27
diff --git a/src/nexus/reader.py b/src/nexus/reader.py index e42d8a8..8df69cd 100644 --- a/src/nexus/reader.py +++ b/src/nexus/reader.py @@ -161,10 +161,18 @@ class NexusReader(object): :return: String """ out = ["#NEXUS\n"] - for block in self.blocks: - out.append(self.blocks[block].write()) + blocks = [] + for block in self.blocks.values(): + if block in blocks: + # We skip copies of blocks - which might have happened to provide shortcuts for + # semantically identical but differently named blocks, such as "data" and + # "characters". + continue + blocks.append(block) + for block in blocks: + out.append(block.write()) # empty line after block if needed - if len(self.blocks) > 1: + if len(blocks) > 1: out.append("\n") return "\n".join(out)
dlce-eva/python-nexus
071aaca665cc9bfde15201a31c836c6587d04483
diff --git a/tests/test_reader.py b/tests/test_reader.py index 41e72e4..df9bd01 100644 --- a/tests/test_reader.py +++ b/tests/test_reader.py @@ -19,6 +19,11 @@ def test_reader_from_blocks(): assert hasattr(n, 'custom') +def test_roundtrip(examples): + nex = NexusReader(examples.joinpath('example2.nex')) + _ = NexusReader.from_string(nex.write()) + + def test_read_file(nex, examples): """Test the Core functionality of NexusReader""" assert 'data' in nex.blocks
Round tripping a nexus with a characters block leads to two character blocks ...which means the resulting nexus can't be read. Example [here](https://github.com/phlorest/walker_and_ribeiro2011/blob/main/cldf/data.nex). ...which means: ```python >>> from nexus import NexusReader >>> NexusReader("walker_and_riberio2015/cldf/data.nex") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/simon/.pyenv/versions/3.9.6/lib/python3.9/site-packages/nexus/reader.py", line 42, in __init__ self._set_blocks(NexusReader._blocks_from_file(filename)) File "/Users/simon/.pyenv/versions/3.9.6/lib/python3.9/site-packages/nexus/reader.py", line 77, in _set_blocks raise NexusFormatException("Duplicate Block %s" % block) nexus.exceptions.NexusFormatException: Duplicate Block characters ``` This is because of this: https://github.com/dlce-eva/python-nexus/blob/071aaca665cc9bfde15201a31c836c6587d04483/src/nexus/reader.py#L80-L81 (which, I admit, I implemented as cheap way to always have a `data` block rather than looking for `data` or `characters`). What's the best solution here @xrotwang ? 1. remove these two lines so this change doesn't happen (simplest solution, but means we need to keep a closer eye in e.g. phlorest, and add standardisation there (nex.blocks['data'] = nex.blocks['characters'], del(nex.blocks['characters'])). 2. delete blocks['characters'] once it's been copied to blocks['data']. This keeps the status quo but adds a magic invisible change so seems like a bad idea. 3. fix the handlers to create a data and a characters block. Round-tripping will duplicate data and characters but they'll be named differently at least. 4. revise `NexusWriter` to check for duplicate blocks, and perhaps allow writing of specific blocks only (nex.write(filename, blocks=['data']) The fact that the moved block still thinks of itself as a characters block rather than a data block is a bug.
0.0
071aaca665cc9bfde15201a31c836c6587d04483
[ "tests/test_reader.py::test_roundtrip" ]
[ "tests/test_reader.py::test_reader_from_blocks", "tests/test_reader.py::test_read_file", "tests/test_reader.py::test_error_on_missing_file", "tests/test_reader.py::test_read_gzip_file", "tests/test_reader.py::test_from_string", "tests/test_reader.py::test_read_string_returns_self", "tests/test_reader.py::test_write", "tests/test_reader.py::test_write_to_file", "tests/test_reader.py::test_error_on_duplicate_block" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-12-02 06:58:22+00:00
bsd-2-clause
1,947
dlr-eoc__ukis-pysat-156
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f0e3b22..d331e63 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -7,10 +7,11 @@ Changelog Changed ^^^^^^^ -``requirements``: Pystac version updated to 1.0.0, STAC version 1.0.0 #147 +- ``data``: Removed pylandsat dependency and added methods for downloading landsat products from GCS in data module #106 Fixed ^^^^^ -- ``data``: Removed pylandsat dependency and added methods for downloading landsat products from GCS in data module #106 +- ``data``: Consistency for Landsat & Sentinel #151 Added ^^^^^ diff --git a/ukis_pysat/data.py b/ukis_pysat/data.py index 507609b..63ff25b 100644 --- a/ukis_pysat/data.py +++ b/ukis_pysat/data.py @@ -306,6 +306,20 @@ class Source: f"It is much easier to stream the asset yourself now using `requests.get(url, stream=True)`" ) + def _get_srcid_from_product_uuid_ee(self, product_uuid): + """ + query EarthExplorer for srcid and meta (e.g. for url and bounds of product) + :param product_uuid: UUID of the satellite image product (String). + + :return: product_uuid, meta_src of product + """ + from landsatxplore.util import parse_scene_id, landsat_dataset + + meta = parse_scene_id(product_uuid) + metadata = self.api.metadata(product_uuid, landsat_dataset(int(meta["satellite"]))) + + return metadata["display_id"], metadata + def download_image(self, product_uuid, target_dir): """Downloads satellite image data to a target directory for a specific product_id. Incomplete downloads are continued and complete files are skipped. @@ -322,19 +336,19 @@ class Source: ) elif self.src == Datahub.EarthExplorer: - if not Path(target_dir.joinpath(product_uuid + ".zip")).is_file(): - + product_srcid, _ = self._get_srcid_from_product_uuid_ee(product_uuid) + if not Path(target_dir.joinpath(product_srcid + ".zip")).is_file(): # download data from GCS if file does not already exist - product = Product(product_uuid) + product = Product(product_srcid) product.download(out_dir=target_dir, progressbar=False) # compress download directory and remove original files shutil.make_archive( - target_dir.joinpath(product_uuid), + target_dir.joinpath(product_srcid), "zip", - root_dir=target_dir.joinpath(product_uuid), + root_dir=target_dir.joinpath(product_srcid), ) - shutil.rmtree(target_dir.joinpath(product_uuid)) + shutil.rmtree(target_dir.joinpath(product_srcid)) else: self.api.download(product_uuid, target_dir, checksum=True) @@ -356,17 +370,9 @@ class Source: ) elif self.src == Datahub.EarthExplorer: - # query EarthExplorer for url, srcid and bounds of product - meta_src = self.api.request( - "metadata", - **{ - "datasetName": self.src.value, - "entityIds": [product_uuid], - }, - ) + product_srcid, meta_src = self._get_srcid_from_product_uuid_ee(product_uuid) url = meta_src[0]["browseUrl"] bounds = geometry.shape(meta_src[0]["spatialFootprint"]).bounds - product_srcid = meta_src[0]["displayId"] else: # query Scihub for url, srcid and bounds of product
dlr-eoc/ukis-pysat
a079d5f05a8205d1b492e41c70841912b29bb684
diff --git a/tests/test_data.py b/tests/test_data.py index 0b3c903..7fea666 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -220,6 +220,38 @@ class DataTest(unittest.TestCase): product._url("B1.tif"), ) + @requests_mock.Mocker(real_http=True) + def test_get_srcid_from_product_uuid_ee(self, m): + m.post( + "https://m2m.cr.usgs.gov/api/api/json/stable/login", + content=b'{"requestId": 241064318, "version": "stable", "data": "token", "errorCode": null, "errorMessage": null, "sessionId": 51372983}', + ) + m.get( + "https://m2m.cr.usgs.gov/api/api/json/stable/scene-list-add", + content=b'{"requestId": 241159456, "version": "stable", "sessionId": 51393323, "data": {"browse":[{"id":"5e83d0b86f2c3061","browseRotationEnabled":false,"browseName":"LandsatLook Natural Color Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1.jpg"},{"id":"5e83d0b85da62c02","browseRotationEnabled":false,"browseName":"LandsatLook Thermal Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_TIR.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00_tir","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_TIR.jpg"},{"id":"5e83d0b8b814a0e6","browseRotationEnabled":false,"browseName":"LandsatLook Quality Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_QB.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00_qb","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_QB.jpg"}],"cloudCover":"12.47","entityId":"LC81930242020082LGN00","displayId":"LC08_L1TP_193024_20200322_20200326_01_T1","orderingId":"LC81930242020082LGN00","metadata":[{"id":"5e83d0b82af07b21","fieldName":"Landsat Product Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#landsat_product_id","value":"LC08_L1TP_193024_20200322_20200326_01_T1"},{"id":"5e83d0b88275745","fieldName":"Landsat Scene Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#landsat_scene_id","value":"LC81930242020082LGN00"},{"id":"5e83d0b92ff6b5e8","fieldName":"Acquisition Date","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"2020\\/03\\/22"},{"id":"5e83d0b9332fd122","fieldName":"Collection Category","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"T1"},{"id":"5e83d0b9948e2596","fieldName":"Collection Number","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":1},{"id":"5e83d0b922c5f981","fieldName":"WRS Path","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 193"},{"id":"5e83d0b94328e34e","fieldName":"WRS Row","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 024"},{"id":"5e83d0b9a34ebe01","fieldName":"Target WRS Path","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 193"},{"id":"5e83d0b8852f2e23","fieldName":"Target WRS Row","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 024"},{"id":"5e83d0b9173b715a","fieldName":"Nadir\\/Off Nadir","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"NADIR"},{"id":"5e83d0b820eaa311","fieldName":"Roll Angle","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#roll_angle","value":"-0.001"},{"id":"5e83d0b8379c9dae","fieldName":"Date L-1 Generated","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#date_l1_generated","value":"2020\\/03\\/26"},{"id":"5e83d0b9a78d1dbe","fieldName":"Start Time","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#start_time","value":"2020:082:10:02:29.1296010"},{"id":"5e83d0b887e40f8e","fieldName":"Stop Time","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#stop_time","value":"2020:082:10:03:00.8996000"},{"id":"5e83d0b926d7d304","fieldName":"Station Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#distribution_site","value":"LGN"},{"id":"5e83d0b91ad332e3","fieldName":"Day\\/Night Indicator","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#day_or_night","value":"DAY"},{"id":"5e83d0b864f5722e","fieldName":"Land Cloud Cover","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cloud_cover_land","value":"12.47"},{"id":"5e83d0b92e9d1b11","fieldName":"Scene Cloud Cover","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cloud_cover","value":"12.47"},{"id":"5e83d0b991213d01","fieldName":"Ground Control Points Model","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ground_control_points_model","value":253},{"id":"5e83d0b9e4a26b2a","fieldName":"Ground Control Points Version","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ground_control_points_version","value":4},{"id":"5e83d0b9bb19d4cc","fieldName":"Geometric RMSE Model (meters)","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model","value":"8.296"},{"id":"5e83d0b8f922f1d3","fieldName":"Geometric RMSE Model X","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model_x","value":"5.809"},{"id":"5e83d0b93b83213d","fieldName":"Geometric RMSE Model Y","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model_y","value":"5.924"},{"id":"5e83d0b9c9fa1556","fieldName":"Image Quality","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#image_quality_landsat_8","value":9},{"id":"5e83d0b8a926bb3e","fieldName":"Processing Software Version","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#processing_software_version","value":"LPGS_13.1.0"},{"id":"5e83d0b84092b361","fieldName":"Sun Elevation L1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sun_elevation","value":"36.94009856"},{"id":"5e83d0b8bf763033","fieldName":"Sun Azimuth L1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sun_azimuth","value":"156.99969272"},{"id":"5e83d0b97cb734c3","fieldName":"TIRS SSM Model","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#tirs_ssm_model","value":"FINAL"},{"id":"5e83d0b861614fa4","fieldName":"Data Type Level-1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#data_type_l1","value":"OLI_TIRS_L1TP"},{"id":"5e83d0b993a4fa4a","fieldName":"Sensor Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sensor_id ","value":"OLI_TIRS"},{"id":"5e83d0b9de23d772","fieldName":"Panchromatic Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#panchromatic_lines","value":16301},{"id":"5e83d0b8100f0577","fieldName":"Panchromatic Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#panchromatic_samples","value":16101},{"id":"5e83d0b92bc96899","fieldName":"Reflective Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#reflective_lines","value":8151},{"id":"5e83d0b8bbb70baf","fieldName":"Reflective Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#reflective_samples","value":8051},{"id":"5e83d0b955642ca4","fieldName":"Thermal Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#thermal_lines","value":8151},{"id":"5e83d0b96b1a0d35","fieldName":"Thermal Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#thermal_samples","value":8051},{"id":"5e83d0b9104800de","fieldName":"Map Projection Level-1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#map_projection_l1","value":"UTM"},{"id":"5e83d0b9fb0dce2d","fieldName":"UTM Zone","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#utm_zone","value":33},{"id":"5e83d0b8fd64f557","fieldName":"Datum","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#datum","value":"WGS84"},{"id":"5e83d0b84cc2632e","fieldName":"Ellipsoid","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ellipsoid","value":"WGS84"},{"id":"5e83d0b98f651440","fieldName":"Grid Cell Size Panchromatic","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_panchromatic","value":"15.00"},{"id":"5e83d0b9c6eaa87d","fieldName":"Grid Cell Size Reflective","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_reflective","value":"30.00"},{"id":"5e83d0b8c810ced","fieldName":"Grid Cell Size Thermal","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_thermal","value":"30.00"},{"id":"5e83d0b8a40bafa4","fieldName":"Bias Parameter File Name OLI","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#bpf_name_oli","value":"LO8BPF20200322095233_20200322113039.01"},{"id":"5e83d0b964a91d93","fieldName":"Bias Parameter File Name TIRS","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#bpf_name_tirs","value":"LT8BPF20200310060739_20200324104153.01"},{"id":"5e83d0b9b5d81214","fieldName":"Calibration Parameter File","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cpf_name","value":"LC08CPF_20200101_20200331_01.04"},{"id":"5e83d0b9c67b22a3","fieldName":"RLUT File Name","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#rlut_file_name","value":"LC08RLUT_20150303_20431231_01_12.h5"},{"id":"5e83d0b9a610a996","fieldName":"Center Latitude","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"51&deg;41\'35.34\\"N"},{"id":"5e83d0b94fad23df","fieldName":"Center Longitude","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"12&deg;48\'15.73\\"E"},{"id":"5e83d0b9c1d54551","fieldName":"UL Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"52&deg;45\'50.58\\"N"},{"id":"5e83d0b8d91068e","fieldName":"UL Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"11&deg;49\'23.52\\"E"},{"id":"5e83d0b94ff6f17e","fieldName":"UR Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"52&deg;17\'44.92\\"N"},{"id":"5e83d0b9a76119fe","fieldName":"UR Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"14&deg;32\'32.78\\"E"},{"id":"5e83d0b9f29120e3","fieldName":"LL Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"51&deg;03\'53.57\\"N"},{"id":"5e83d0b988d2162b","fieldName":"LL Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"11&deg;06\'35.75\\"E"},{"id":"5e83d0b96162233","fieldName":"LR Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"50&deg;36\'17.24\\"N"},{"id":"5e83d0b894a09772","fieldName":"LR Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"13&deg;43\'57.40\\"E"},{"id":"5e83d0b87f203a10","fieldName":"Center Latitude dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"51.69315"},{"id":"5e83d0b9b2a9a299","fieldName":"Center Longitude dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"12.80437"},{"id":"5e83d0b8bc51bf5b","fieldName":"UL Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"52.76405"},{"id":"5e83d0b95071b3bf","fieldName":"UL Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"11.82320"},{"id":"5e83d0b9842b0429","fieldName":"UR Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"52.29581"},{"id":"5e83d0b931a16a9","fieldName":"UR Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"14.54244"},{"id":"5e83d0b8abad8ec9","fieldName":"LL Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"51.06488"},{"id":"5e83d0b92a9532e0","fieldName":"LL Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"11.10993"},{"id":"5e83d0b834fea374","fieldName":"LR Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"50.60479"},{"id":"5e83d0b9f619dbbe","fieldName":"LR Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"13.73261"}],"hasCustomizedMetadata":false,"options":{"bulk":true,"download":true,"order":true,"secondary":false},"selected":null,"spatialBounds":{"type":"Polygon","coordinates":[[[11.10993,50.60479],[11.10993,52.76405],[14.54244,52.76405],[14.54244,50.60479],[11.10993,50.60479]]]},"spatialCoverage":{"type":"Polygon","coordinates":[[[11.10993,51.06488],[13.73261,50.60479],[14.54244,52.29581],[11.8232,52.76405],[11.10993,51.06488]]]},"temporalCoverage":{"endDate":"2020-03-22 00:00:00","startDate":"2020-03-22 00:00:00"},"publishDate":"2020-03-22T09:56:49"}, "errorCode": null, "errorMessage": null}', + ) + m.get( + "https://m2m.cr.usgs.gov/api/api/json/stable/scene-list-get", + content=b'{"requestId": 241160510, "version": "stable", "sessionId": 51393558, "data": [{"entityId":"LC81930242020082LGN00","datasetName":"landsat_8_c1"}], "errorCode": null, "errorMessage": null}', + ) + m.get( + "https://m2m.cr.usgs.gov/api/api/json/stable/scene-list-remove", + content=b'{"requestId": 241161482, "version": "stable", "sessionId": 51393761, "data": null, "errorCode": null, "errorMessage": null}', + ) + m.get( + "https://m2m.cr.usgs.gov/api/api/json/stable/scene-metadata", + content=b'{"requestId": 241162488, "version": "stable", "sessionId": 51393950, "data": {"browse":[{"id":"5e83d0b86f2c3061","browseRotationEnabled":false,"browseName":"LandsatLook Natural Color Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1.jpg"},{"id":"5e83d0b85da62c02","browseRotationEnabled":false,"browseName":"LandsatLook Thermal Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_TIR.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00_tir","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_TIR.jpg"},{"id":"5e83d0b8b814a0e6","browseRotationEnabled":false,"browseName":"LandsatLook Quality Preview Image","browsePath":"https:\\/\\/ims.cr.usgs.gov\\/browse\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_QB.jpg","overlayPath":"https:\\/\\/ims.cr.usgs.gov\\/wms\\/landsat_8_c1?sceneId=lc81930242020082lgn00_qb","overlayType":"dmid_wms","thumbnailPath":"https:\\/\\/ims.cr.usgs.gov\\/thumbnail\\/landsat_8_c1\\/2020\\/193\\/024\\/LC08_L1TP_193024_20200322_20200326_01_T1_QB.jpg"}],"cloudCover":"12.47","entityId":"LC81930242020082LGN00","displayId":"LC08_L1TP_193024_20200322_20200326_01_T1","orderingId":"LC81930242020082LGN00","metadata":[{"id":"5e83d0b82af07b21","fieldName":"Landsat Product Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#landsat_product_id","value":"LC08_L1TP_193024_20200322_20200326_01_T1"},{"id":"5e83d0b88275745","fieldName":"Landsat Scene Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#landsat_scene_id","value":"LC81930242020082LGN00"},{"id":"5e83d0b92ff6b5e8","fieldName":"Acquisition Date","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"2020\\/03\\/22"},{"id":"5e83d0b9332fd122","fieldName":"Collection Category","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"T1"},{"id":"5e83d0b9948e2596","fieldName":"Collection Number","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":1},{"id":"5e83d0b922c5f981","fieldName":"WRS Path","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 193"},{"id":"5e83d0b94328e34e","fieldName":"WRS Row","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 024"},{"id":"5e83d0b9a34ebe01","fieldName":"Target WRS Path","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 193"},{"id":"5e83d0b8852f2e23","fieldName":"Target WRS Row","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":" 024"},{"id":"5e83d0b9173b715a","fieldName":"Nadir\\/Off Nadir","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_c2_dictionary.html#acquisition_date","value":"NADIR"},{"id":"5e83d0b820eaa311","fieldName":"Roll Angle","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#roll_angle","value":"-0.001"},{"id":"5e83d0b8379c9dae","fieldName":"Date L-1 Generated","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#date_l1_generated","value":"2020\\/03\\/26"},{"id":"5e83d0b9a78d1dbe","fieldName":"Start Time","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#start_time","value":"2020:082:10:02:29.1296010"},{"id":"5e83d0b887e40f8e","fieldName":"Stop Time","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#stop_time","value":"2020:082:10:03:00.8996000"},{"id":"5e83d0b926d7d304","fieldName":"Station Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#distribution_site","value":"LGN"},{"id":"5e83d0b91ad332e3","fieldName":"Day\\/Night Indicator","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#day_or_night","value":"DAY"},{"id":"5e83d0b864f5722e","fieldName":"Land Cloud Cover","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cloud_cover_land","value":"12.47"},{"id":"5e83d0b92e9d1b11","fieldName":"Scene Cloud Cover","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cloud_cover","value":"12.47"},{"id":"5e83d0b991213d01","fieldName":"Ground Control Points Model","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ground_control_points_model","value":253},{"id":"5e83d0b9e4a26b2a","fieldName":"Ground Control Points Version","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ground_control_points_version","value":4},{"id":"5e83d0b9bb19d4cc","fieldName":"Geometric RMSE Model (meters)","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model","value":"8.296"},{"id":"5e83d0b8f922f1d3","fieldName":"Geometric RMSE Model X","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model_x","value":"5.809"},{"id":"5e83d0b93b83213d","fieldName":"Geometric RMSE Model Y","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#geometric_rmse_model_y","value":"5.924"},{"id":"5e83d0b9c9fa1556","fieldName":"Image Quality","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#image_quality_landsat_8","value":9},{"id":"5e83d0b8a926bb3e","fieldName":"Processing Software Version","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#processing_software_version","value":"LPGS_13.1.0"},{"id":"5e83d0b84092b361","fieldName":"Sun Elevation L1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sun_elevation","value":"36.94009856"},{"id":"5e83d0b8bf763033","fieldName":"Sun Azimuth L1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sun_azimuth","value":"156.99969272"},{"id":"5e83d0b97cb734c3","fieldName":"TIRS SSM Model","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#tirs_ssm_model","value":"FINAL"},{"id":"5e83d0b861614fa4","fieldName":"Data Type Level-1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#data_type_l1","value":"OLI_TIRS_L1TP"},{"id":"5e83d0b993a4fa4a","fieldName":"Sensor Identifier","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#sensor_id ","value":"OLI_TIRS"},{"id":"5e83d0b9de23d772","fieldName":"Panchromatic Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#panchromatic_lines","value":16301},{"id":"5e83d0b8100f0577","fieldName":"Panchromatic Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#panchromatic_samples","value":16101},{"id":"5e83d0b92bc96899","fieldName":"Reflective Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#reflective_lines","value":8151},{"id":"5e83d0b8bbb70baf","fieldName":"Reflective Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#reflective_samples","value":8051},{"id":"5e83d0b955642ca4","fieldName":"Thermal Lines","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#thermal_lines","value":8151},{"id":"5e83d0b96b1a0d35","fieldName":"Thermal Samples","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#thermal_samples","value":8051},{"id":"5e83d0b9104800de","fieldName":"Map Projection Level-1","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#map_projection_l1","value":"UTM"},{"id":"5e83d0b9fb0dce2d","fieldName":"UTM Zone","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#utm_zone","value":33},{"id":"5e83d0b8fd64f557","fieldName":"Datum","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#datum","value":"WGS84"},{"id":"5e83d0b84cc2632e","fieldName":"Ellipsoid","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#ellipsoid","value":"WGS84"},{"id":"5e83d0b98f651440","fieldName":"Grid Cell Size Panchromatic","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_panchromatic","value":"15.00"},{"id":"5e83d0b9c6eaa87d","fieldName":"Grid Cell Size Reflective","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_reflective","value":"30.00"},{"id":"5e83d0b8c810ced","fieldName":"Grid Cell Size Thermal","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#grid_cell_size_thermal","value":"30.00"},{"id":"5e83d0b8a40bafa4","fieldName":"Bias Parameter File Name OLI","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#bpf_name_oli","value":"LO8BPF20200322095233_20200322113039.01"},{"id":"5e83d0b964a91d93","fieldName":"Bias Parameter File Name TIRS","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#bpf_name_tirs","value":"LT8BPF20200310060739_20200324104153.01"},{"id":"5e83d0b9b5d81214","fieldName":"Calibration Parameter File","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#cpf_name","value":"LC08CPF_20200101_20200331_01.04"},{"id":"5e83d0b9c67b22a3","fieldName":"RLUT File Name","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#rlut_file_name","value":"LC08RLUT_20150303_20431231_01_12.h5"},{"id":"5e83d0b9a610a996","fieldName":"Center Latitude","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"51&deg;41\'35.34\\"N"},{"id":"5e83d0b94fad23df","fieldName":"Center Longitude","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"12&deg;48\'15.73\\"E"},{"id":"5e83d0b9c1d54551","fieldName":"UL Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"52&deg;45\'50.58\\"N"},{"id":"5e83d0b8d91068e","fieldName":"UL Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"11&deg;49\'23.52\\"E"},{"id":"5e83d0b94ff6f17e","fieldName":"UR Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"52&deg;17\'44.92\\"N"},{"id":"5e83d0b9a76119fe","fieldName":"UR Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"14&deg;32\'32.78\\"E"},{"id":"5e83d0b9f29120e3","fieldName":"LL Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"51&deg;03\'53.57\\"N"},{"id":"5e83d0b988d2162b","fieldName":"LL Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"11&deg;06\'35.75\\"E"},{"id":"5e83d0b96162233","fieldName":"LR Corner Lat","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"50&deg;36\'17.24\\"N"},{"id":"5e83d0b894a09772","fieldName":"LR Corner Long","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_degrees","value":"13&deg;43\'57.40\\"E"},{"id":"5e83d0b87f203a10","fieldName":"Center Latitude dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"51.69315"},{"id":"5e83d0b9b2a9a299","fieldName":"Center Longitude dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"12.80437"},{"id":"5e83d0b8bc51bf5b","fieldName":"UL Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"52.76405"},{"id":"5e83d0b95071b3bf","fieldName":"UL Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"11.82320"},{"id":"5e83d0b9842b0429","fieldName":"UR Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"52.29581"},{"id":"5e83d0b931a16a9","fieldName":"UR Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"14.54244"},{"id":"5e83d0b8abad8ec9","fieldName":"LL Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"51.06488"},{"id":"5e83d0b92a9532e0","fieldName":"LL Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"11.10993"},{"id":"5e83d0b834fea374","fieldName":"LR Corner Lat dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"50.60479"},{"id":"5e83d0b9f619dbbe","fieldName":"LR Corner Long dec","dictionaryLink":"https:\\/\\/lta.cr.usgs.gov\\/DD\\/landsat_dictionary.html#coordinates_decimal","value":"13.73261"}],"hasCustomizedMetadata":false,"options":{"bulk":true,"download":true,"order":true,"secondary":false},"selected":null,"spatialBounds":{"type":"Polygon","coordinates":[[[11.10993,50.60479],[11.10993,52.76405],[14.54244,52.76405],[14.54244,50.60479],[11.10993,50.60479]]]},"spatialCoverage":{"type":"Polygon","coordinates":[[[11.10993,51.06488],[13.73261,50.60479],[14.54244,52.29581],[11.8232,52.76405],[11.10993,51.06488]]]},"temporalCoverage":{"endDate":"2020-03-22 00:00:00","startDate":"2020-03-22 00:00:00"},"publishDate":"2020-03-22T09:56:49"}, "errorCode": null, "errorMessage": null}', + ) + m.get( + "https://m2m.cr.usgs.gov/api/api/json/stable/logout", + content=b'{"errorCode":null,"error":"","data":true,"api_version":"1.4.1","access_level":"user","catalog_id":"EE","executionTime":0.4}', + ) + with Source(datahub=Datahub.EarthExplorer) as src: + product_srcid, _ = src._get_srcid_from_product_uuid_ee( + product_uuid="LC81930242020082LGN00", + ) + self.assertEqual(product_srcid, "LC08_L1TP_193024_20200322_20200326_01_T1") + if __name__ == "__main__": unittest.main()
Download Method Conflict in SCIHUB and EARTHEXPLORER **Describe the bug** when the item is created we set a value for the [ID's](https://github.com/dlr-eoc/ukis-pysat/blob/master/ukis_pysat/data.py#L394), But when we query the hub we take another value of the item ìtem.id for Landsat and ```item. Properties['uuid'] for sentinel to download. **To Reproduce** To download we can give the ```item.id``` (product "ID") [here ](https://github.com/dlr-eoc/ukis-pysat/blob/master/ukis_pysat/data.py#L448) always and solve this internally. **Expected behavior** ```UKIS_PYSAT``` download method for ```SCIHUB``` and ```EARTHEXPLORER``` both should have used either```product_uuid``` or ``product_id"``` .
0.0
a079d5f05a8205d1b492e41c70841912b29bb684
[ "tests/test_data.py::DataTest::test_get_srcid_from_product_uuid_ee" ]
[ "tests/test_data.py::DataTest::test_aoi_geointerface", "tests/test_data.py::DataTest::test_compute_md5", "tests/test_data.py::DataTest::test_exception_false_aoi", "tests/test_data.py::DataTest::test_init_exception_other_enum", "tests/test_data.py::DataTest::test_init_exception_other_hub", "tests/test_data.py::DataTest::test_init_stac_catalog", "tests/test_data.py::DataTest::test_init_stac_url", "tests/test_data.py::DataTest::test_meta_from_pid", "tests/test_data.py::DataTest::test_product_available", "tests/test_data.py::DataTest::test_url" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-27 10:10:48+00:00
apache-2.0
1,948
dls-controls__aioca-25
diff --git a/aioca/_catools.py b/aioca/_catools.py index 91b5012..bc41e02 100644 --- a/aioca/_catools.py +++ b/aioca/_catools.py @@ -412,7 +412,7 @@ class Subscription(object): self.dropped_callbacks: int = 0 self.__event_loop = asyncio.get_event_loop() self.__values: Deque[AugmentedValue] = collections.deque( - maxlen=0 if all_updates else 1 + maxlen=None if all_updates else 1 ) self.__lock = asyncio.Lock()
dls-controls/aioca
69ea466daf84a8bd371411c9902d1ba6fbee87f8
diff --git a/tests/test_aioca.py b/tests/test_aioca.py index ec7938f..2a5fbb0 100644 --- a/tests/test_aioca.py +++ b/tests/test_aioca.py @@ -46,6 +46,8 @@ BAD_EGUS = PV_PREFIX + "bad_egus" WAVEFORM = PV_PREFIX + "waveform" # A read only PV RO = PV_PREFIX + "waveform.NELM" +# Longer test timeouts as GHA has slow runners on Mac +TIMEOUT = 10 def boom(value, *args) -> None: @@ -80,7 +82,7 @@ def ioc(): pass -def wait_for_ioc(ioc, timeout=5): +def wait_for_ioc(ioc, timeout=TIMEOUT): start = time.time() while True: assert time.time() - start < timeout @@ -91,7 +93,7 @@ def wait_for_ioc(ioc, timeout=5): @pytest.mark.asyncio async def test_connect(ioc: subprocess.Popen) -> None: - conn = await connect(LONGOUT) + conn = await connect(LONGOUT, timeout=TIMEOUT) assert type(conn) is CANothing conn2 = await connect([SI, NE], throw=False, timeout=1.0) assert len(conn2) == 2 @@ -103,7 +105,7 @@ async def test_connect(ioc: subprocess.Popen) -> None: @pytest.mark.asyncio async def test_cainfo(ioc: subprocess.Popen) -> None: - conn2 = await cainfo([WAVEFORM, SI]) + conn2 = await cainfo([WAVEFORM, SI], timeout=TIMEOUT) assert conn2[0].datatype == 1 # array assert conn2[1].datatype == 0 # string conn = await cainfo(LONGOUT) @@ -157,20 +159,20 @@ async def test_get_non_existent_pvs_no_throw(ioc: subprocess.Popen) -> None: async def test_get_two_pvs( ioc: subprocess.Popen, pvs: Union[List[str], Tuple[str]] ) -> None: - value = await caget(pvs) + value = await caget(pvs, timeout=TIMEOUT) assert [42, "me"] == value @pytest.mark.asyncio async def test_get_pv_with_bad_egus(ioc: subprocess.Popen) -> None: - value = await caget(BAD_EGUS, format=FORMAT_CTRL) + value = await caget(BAD_EGUS, format=FORMAT_CTRL, timeout=TIMEOUT) assert 32 == value assert value.units == "\ufffd" # unicode REPLACEMENT CHARACTER @pytest.mark.asyncio async def test_get_waveform_pv(ioc: subprocess.Popen) -> None: - value = await caget(WAVEFORM) + value = await caget(WAVEFORM, timeout=TIMEOUT) assert len(value) == 0 assert isinstance(value, dbr.ca_array) await caput(WAVEFORM, [1, 2, 3, 4]) @@ -183,7 +185,7 @@ async def test_get_waveform_pv(ioc: subprocess.Popen) -> None: @pytest.mark.asyncio async def test_caput(ioc: subprocess.Popen) -> None: # Need to test the timeout=None branch, but wrap with wait_for in case it fails - v1 = await asyncio.wait_for(caput(LONGOUT, 43, wait=True, timeout=None), 5) + v1 = await asyncio.wait_for(caput(LONGOUT, 43, wait=True, timeout=None), TIMEOUT) assert isinstance(v1, CANothing) v2 = await caget(LONGOUT) assert 43 == v2 @@ -192,7 +194,7 @@ async def test_caput(ioc: subprocess.Popen) -> None: @pytest.mark.asyncio async def test_caput_on_ro_pv_fails(ioc: subprocess.Popen) -> None: with pytest.raises(cadef.CAException): - await caput(RO, 43) + await caput(RO, 43, timeout=TIMEOUT) result = await caput(RO, 43, throw=False) assert str(result).endswith("Write access denied") @@ -202,7 +204,7 @@ async def test_caput_on_ro_pv_fails(ioc: subprocess.Popen) -> None: async def test_caput_two_pvs_same_value( ioc: subprocess.Popen, pvs: Union[List[str], Tuple[str]] ) -> None: - await caput([LONGOUT, SI], 43) + await caput([LONGOUT, SI], 43, timeout=TIMEOUT) value = await caget([LONGOUT, SI]) assert [43, "43"] == value await caput([LONGOUT, SI], "44") @@ -212,7 +214,7 @@ async def test_caput_two_pvs_same_value( @pytest.mark.asyncio async def test_caput_two_pvs_different_value(ioc: subprocess.Popen) -> None: - await caput([LONGOUT, SI], [44, "blah"]) + await caput([LONGOUT, SI], [44, "blah"], timeout=TIMEOUT) value = await caget([LONGOUT, SI]) assert [44, "blah"] == value @@ -232,7 +234,7 @@ async def test_caget_non_existent() -> None: @pytest.mark.asyncio async def test_caget_non_existent_and_good(ioc: subprocess.Popen) -> None: - await caput(WAVEFORM, [1, 2, 3, 4]) + await caput(WAVEFORM, [1, 2, 3, 4], timeout=TIMEOUT) try: await caget([NE, WAVEFORM], timeout=1.0) except CANothing: @@ -246,7 +248,7 @@ async def test_caget_non_existent_and_good(ioc: subprocess.Popen) -> None: assert len(x) == 0 -async def poll_length(array, gt=0, timeout=5): +async def poll_length(array, gt=0, timeout=TIMEOUT): start = time.time() while not len(array) > gt: await asyncio.sleep(0.01) @@ -307,7 +309,7 @@ async def test_monitor_with_failing_dbr(ioc: subprocess.Popen, capsys) -> None: @pytest.mark.asyncio async def test_monitor_two_pvs(ioc: subprocess.Popen) -> None: values: List[Tuple[AugmentedValue, int]] = [] - await caput(WAVEFORM, [1, 2], wait=True) + await caput(WAVEFORM, [1, 2], wait=True, timeout=TIMEOUT) ms = camonitor([WAVEFORM, LONGOUT], lambda v, n: values.append((v, n)), count=-1) # Wait for connection @@ -369,6 +371,35 @@ async def test_long_monitor_callback(ioc: subprocess.Popen) -> None: assert m.dropped_callbacks == 1 [email protected] +async def test_long_monitor_all_updates(ioc: subprocess.Popen) -> None: + # Like above, but check all_updates gives us everything + values = [] + wait_for_ioc(ioc) + + async def cb(value): + values.append(value) + await asyncio.sleep(0.4) + + m = camonitor(LONGOUT, cb, connect_timeout=(time.time() + 0.5,), all_updates=True) + # Wait for connection, calling first cb + await poll_length(values) + assert values == [42] + assert m.dropped_callbacks == 0 + # These two caputs happen during the sleep of the first cb, + # they shouldn't be squashed as we ask for all_updates + await caput(LONGOUT, 43) + await caput(LONGOUT, 44) + # Wait until the second cb has finished + await asyncio.sleep(0.6) + assert [42, 43] == values + assert m.dropped_callbacks == 0 + # Wait until the third cb (which is not dropped) has finished + await asyncio.sleep(0.6) + assert [42, 43, 44] == values + assert m.dropped_callbacks == 0 + + @pytest.mark.asyncio async def test_exception_raising_monitor_callback( ioc: subprocess.Popen, capsys
camonitor all_updates=True not doing what it should? After noticing I was missing some (very close) updates I decided that this was due to the default merging behavior of `camonitor`, so I tried monitoring with `all_updates=True`. But then I got **no** updates at all. Turns out that `all_updates` has effects on the size of the underlying deque. Relevant code: ``` self.__values: Deque[AugmentedValue] = collections.deque( maxlen=0 if all_updates else 1 ) ``` Now, `collections.deque(maxlen=0)` gives us a deque that effectively is **always full**. Maybe the original intention was to make it `collections.deque(maxlen=None)` (the default)?
0.0
69ea466daf84a8bd371411c9902d1ba6fbee87f8
[ "tests/test_aioca.py::test_long_monitor_all_updates" ]
[ "tests/test_aioca.py::flake-8::FLAKE8", "tests/test_aioca.py::mypy", "tests/test_aioca.py::mypy-status", "tests/test_aioca.py::BLACK", "tests/test_aioca.py::test_connect", "tests/test_aioca.py::test_cainfo", "tests/test_aioca.py::test_get_non_existent_pvs_no_throw", "tests/test_aioca.py::test_get_two_pvs[pvs0]", "tests/test_aioca.py::test_get_two_pvs[pvs1]", "tests/test_aioca.py::test_get_pv_with_bad_egus", "tests/test_aioca.py::test_get_waveform_pv", "tests/test_aioca.py::test_caput", "tests/test_aioca.py::test_caput_on_ro_pv_fails", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs0]", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs1]", "tests/test_aioca.py::test_caput_two_pvs_different_value", "tests/test_aioca.py::test_caget_non_existent", "tests/test_aioca.py::test_caget_non_existent_and_good", "tests/test_aioca.py::test_monitor", "tests/test_aioca.py::test_monitor_with_failing_dbr", "tests/test_aioca.py::test_monitor_two_pvs", "tests/test_aioca.py::test_long_monitor_callback", "tests/test_aioca.py::test_exception_raising_monitor_callback", "tests/test_aioca.py::test_camonitor_non_existent", "tests/test_aioca.py::test_monitor_gc", "tests/test_aioca.py::test_closing_event_loop", "tests/test_aioca.py::test_value_event_raises", "tests/test_aioca.py::test_ca_nothing_dunder_methods", "tests/test_aioca.py::test_run_forever", "tests/test_aioca.py::test_import_in_a_different_thread" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-04-26 08:20:56+00:00
apache-2.0
1,949
dls-controls__aioca-27
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 6c5a2eb..2dd7afa 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -12,6 +12,7 @@ Unreleased_ Fixed: - `camonitor(all_updates=True) now works <../../pull/24>`_ +- `Fixed memory leak in camonitor <../../pull/26>` 1.3_ - 2021-10-15 ----------------- diff --git a/aioca/_catools.py b/aioca/_catools.py index bc41e02..7892f9e 100644 --- a/aioca/_catools.py +++ b/aioca/_catools.py @@ -330,7 +330,8 @@ class Subscription(object): def __create_signal_task(self, value): task = asyncio.ensure_future(self.__signal(value)) - self.__tasks.append(task) + self.__tasks.add(task) + task.add_done_callback(self.__tasks.remove) async def __signal(self, value): """Wrapper for performing callbacks safely: only performs the callback @@ -428,13 +429,13 @@ class Subscription(object): # background, as we may have to wait for the channel to become # connected. self.state = self.OPENING - self.__tasks = [ + self.__tasks = { asyncio.ensure_future( self.__create_subscription( events, datatype, format, count, connect_timeout ) ) - ] + } async def __wait_for_channel(self, timeout): try:
dls-controls/aioca
47155dce291e30195997b5c51b1487ce79b80771
diff --git a/tests/test_aioca.py b/tests/test_aioca.py index 2a5fbb0..9710564 100644 --- a/tests/test_aioca.py +++ b/tests/test_aioca.py @@ -270,6 +270,9 @@ async def test_monitor(ioc: subprocess.Popen) -> None: ioc.communicate("exit") await asyncio.sleep(0.1) + # Check that all callback tasks have terminated, and all that is left + # is the original __create_subscription task (which has now completed) + assert len(m._Subscription__tasks) == 1 # type: ignore m.close() assert [42, 43, 44] == values[:3]
Possible memory leak In __create_signal_task(), a task is appended to the list self.__tasks, but never removed from the list. This list grows without bound. The list of tasks is needed so that we can cancel them when closing. But do we need that for events?
0.0
47155dce291e30195997b5c51b1487ce79b80771
[ "tests/test_aioca.py::test_monitor" ]
[ "tests/test_aioca.py::flake-8::FLAKE8", "tests/test_aioca.py::mypy", "tests/test_aioca.py::mypy-status", "tests/test_aioca.py::BLACK", "tests/test_aioca.py::test_connect", "tests/test_aioca.py::test_cainfo", "tests/test_aioca.py::test_get_non_existent_pvs_no_throw", "tests/test_aioca.py::test_get_two_pvs[pvs0]", "tests/test_aioca.py::test_get_two_pvs[pvs1]", "tests/test_aioca.py::test_get_pv_with_bad_egus", "tests/test_aioca.py::test_get_waveform_pv", "tests/test_aioca.py::test_caput", "tests/test_aioca.py::test_caput_on_ro_pv_fails", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs0]", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs1]", "tests/test_aioca.py::test_caput_two_pvs_different_value", "tests/test_aioca.py::test_caget_non_existent", "tests/test_aioca.py::test_caget_non_existent_and_good", "tests/test_aioca.py::test_monitor_with_failing_dbr", "tests/test_aioca.py::test_monitor_two_pvs", "tests/test_aioca.py::test_long_monitor_callback", "tests/test_aioca.py::test_long_monitor_all_updates", "tests/test_aioca.py::test_exception_raising_monitor_callback", "tests/test_aioca.py::test_camonitor_non_existent", "tests/test_aioca.py::test_monitor_gc", "tests/test_aioca.py::test_closing_event_loop", "tests/test_aioca.py::test_value_event_raises", "tests/test_aioca.py::test_ca_nothing_dunder_methods", "tests/test_aioca.py::test_run_forever", "tests/test_aioca.py::test_import_in_a_different_thread" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-06-07 16:01:46+00:00
apache-2.0
1,950
dls-controls__aioca-38
diff --git a/.github/workflows/code.yml b/.github/workflows/code.yml index b26b076..95e0c7c 100644 --- a/.github/workflows/code.yml +++ b/.github/workflows/code.yml @@ -42,7 +42,7 @@ jobs: - name: Install Python Dependencies run: | - pip install pipenv build + pip install pipenv==2022.4.8 build pipenv install --dev --${{ matrix.pipenv }} --python $(python -c 'import sys; print(sys.executable)') && pipenv graph - name: Create Sdist and Wheel diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 9522c2b..8245674 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -9,7 +9,9 @@ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0 Unreleased_ ----------- -Nothing yet +Added: + +- `Add methods to allow inspecting Channels <../../pull/38>`_ 1.6_ - 2023-04-06 ----------------- diff --git a/aioca/__init__.py b/aioca/__init__.py index 11d056e..90ba0a4 100644 --- a/aioca/__init__.py +++ b/aioca/__init__.py @@ -24,12 +24,14 @@ from epicscorelibs.ca.dbr import ( from ._catools import ( CAInfo, CANothing, + ChannelInfo, Subscription, caget, cainfo, camonitor, caput, connect, + get_channel_infos, purge_channel_caches, run, ) @@ -45,6 +47,8 @@ __all__ = [ "cainfo", # Returns ca_info describing PV connection "CAInfo", # Ca info object "CANothing", # No value + "ChannelInfo", # Information about a particular channel + "get_channel_infos", # Return information about all channels "purge_channel_caches", # Get rid of old channels "run", # Run one aioca coroutine and clean up # The version of aioca diff --git a/aioca/_catools.py b/aioca/_catools.py index 6b99166..dfb96a8 100644 --- a/aioca/_catools.py +++ b/aioca/_catools.py @@ -54,6 +54,9 @@ class ValueEvent(Generic[T]): self._event.set() self.value = value + def is_set(self) -> bool: + return self._event.is_set() + def clear(self): self._event.clear() self.value = RuntimeError("No value set") @@ -252,6 +255,14 @@ class Channel(object): """Removes the given subscription from the list of receivers.""" self.__subscriptions.remove(subscription) + def count_subscriptions(self) -> int: + """Return the number of currently active subscriptions for this Channel""" + return len(self.__subscriptions) + + def connected(self) -> bool: + """Return whether this Channel is currently connected to a PV""" + return self.__connect_event.is_set() + async def wait(self): """Waits for the channel to become connected if not already connected.""" await self.__connect_event.wait() @@ -278,6 +289,9 @@ class ChannelCache(object): self.__channels[name] = channel return channel + def get_channels(self) -> List[Channel]: + return list(self.__channels.values()) + def purge(self): """Purges all the channels in the cache: closes them right now. Will cause other channel access to fail, so only to be done on shutdown.""" @@ -1081,6 +1095,32 @@ def get_channel(pv: str) -> Channel: return channel +class ChannelInfo: + """Information about a particular Channel + + Attributes: + name: Process Variable name the Channel is targeting + connected: True if the Channel is currently connected + subscriber_count: Number of clients subscribed to this Channel""" + + name: str + connected: bool + subscriber_count: int + + def __init__(self, name, connected, subscriber_count): + self.name = name + self.connected = connected + self.subscriber_count = subscriber_count + + +def get_channel_infos() -> List[ChannelInfo]: + """Return information about all Channels""" + return [ + ChannelInfo(channel.name, channel.connected(), channel.count_subscriptions()) + for channel in _Context.get_channel_cache().get_channels() + ] + + # Another delicacy arising from relying on asynchronous CA event dispatching is # that we need to manually flush IO events such as caget commands. To ensure # that large blocks of channel access activity really are aggregated we used to diff --git a/docs/api.rst b/docs/api.rst index 2a58dc4..ec0888a 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -141,6 +141,11 @@ event loop. A convenience function is provided to do this: .. autofunction:: run +.. autoclass:: ChannelInfo() + :members: + +.. autofunction:: get_channel_infos + .. _Values: Working with Values
dls-controls/aioca
a5500d0ba11b3a91610fc449e5ed6b12530a4b4c
diff --git a/tests/test_aioca.py b/tests/test_aioca.py index bd1c28b..56ef8aa 100644 --- a/tests/test_aioca.py +++ b/tests/test_aioca.py @@ -24,6 +24,7 @@ from aioca import ( camonitor, caput, connect, + get_channel_infos, purge_channel_caches, run, ) @@ -610,3 +611,35 @@ def test_import_in_a_different_thread(ioc: subprocess.Popen) -> None: ] ) assert output.strip() == b"42" + + [email protected] +async def test_channel_connected(ioc: subprocess.Popen) -> None: + values: List[AugmentedValue] = [] + m = camonitor(LONGOUT, values.append, notify_disconnect=True) + + # Wait for connection + await poll_length(values) + + channels = get_channel_infos() + assert len(channels) == 1 + + channel = channels[0] + # Initially the PV is connected and has one monitor + assert channel.name == LONGOUT + assert channel.connected + assert channel.subscriber_count == 1 + + ioc.communicate("exit") + await asyncio.sleep(0.1) + + # After IOC exits the channel is disconnected but still has one monitor + channel = get_channel_infos()[0] + assert not channel.connected + assert channel.subscriber_count == 1 + + m.close() + + # Once the monitor is closed the subscription disappears + channel = get_channel_infos()[0] + assert channel.subscriber_count == 0
Provide mechanism to access Channels It would be useful to be able to interrogate the currently active Channels in `aioca`, to enable things like counting the number of open/closed connections. This will need some new public getter functions, and probably a small amount of re-naming of various files and objects to make them public.
0.0
a5500d0ba11b3a91610fc449e5ed6b12530a4b4c
[ "tests/test_aioca.py::mypy", "tests/test_aioca.py::mypy-status", "tests/test_aioca.py::BLACK", "tests/test_aioca.py::test_connect", "tests/test_aioca.py::test_cainfo", "tests/test_aioca.py::test_get_non_existent_pvs_no_throw", "tests/test_aioca.py::test_get_two_pvs[pvs0]", "tests/test_aioca.py::test_get_two_pvs[pvs1]", "tests/test_aioca.py::test_get_pv_with_bad_egus", "tests/test_aioca.py::test_get_waveform_pv", "tests/test_aioca.py::test_caput", "tests/test_aioca.py::test_caput_on_ro_pv_fails", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs0]", "tests/test_aioca.py::test_caput_two_pvs_same_value[pvs1]", "tests/test_aioca.py::test_caput_two_pvs_different_value", "tests/test_aioca.py::test_caget_non_existent", "tests/test_aioca.py::test_caget_non_existent_and_good", "tests/test_aioca.py::test_monitor", "tests/test_aioca.py::test_monitor_with_failing_dbr", "tests/test_aioca.py::test_monitor_two_pvs", "tests/test_aioca.py::test_long_monitor_callback", "tests/test_aioca.py::test_long_monitor_all_updates", "tests/test_aioca.py::test_exception_raising_monitor_callback", "tests/test_aioca.py::test_async_exception_raising_monitor_callback", "tests/test_aioca.py::test_camonitor_non_existent", "tests/test_aioca.py::test_camonitor_non_existent_async", "tests/test_aioca.py::test_monitor_gc", "tests/test_aioca.py::test_closing_event_loop", "tests/test_aioca.py::test_value_event_raises", "tests/test_aioca.py::test_ca_nothing_dunder_methods", "tests/test_aioca.py::test_run_forever", "tests/test_aioca.py::test_import_in_a_different_thread", "tests/test_aioca.py::test_channel_connected" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-04 12:43:21+00:00
apache-2.0
1,951
dmvass__sqlalchemy-easy-profile-17
diff --git a/CHANGELOG.md b/CHANGELOG.md index 58e2c0a..d446327 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +## [1.1.1] - 2020-07-26 +- Fixed deprecated time.clock [issue-16] + ## [1.1.0] - 2020-06-29 - Removed support of python 2.7, 3.5 - Updated documentation diff --git a/easy_profile/profiler.py b/easy_profile/profiler.py index bfefff7..bc91152 100644 --- a/easy_profile/profiler.py +++ b/easy_profile/profiler.py @@ -3,20 +3,13 @@ import functools import inspect from queue import Queue import re -import sys -import time +from time import perf_counter from sqlalchemy import event from sqlalchemy.engine.base import Engine from .reporters import StreamReporter -# Optimize timer function for the platform -if sys.platform == "win32": # pragma: no cover - _timer = time.clock -else: - _timer = time.time - SQL_OPERATORS = ["select", "insert", "update", "delete"] OPERATOR_REGEX = re.compile("(%s) *." % "|".join(SQL_OPERATORS), re.IGNORECASE) @@ -177,10 +170,10 @@ class SessionProfiler: def _before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): - context._query_start_time = _timer() + context._query_start_time = perf_counter() def _after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): self.queries.put(DebugQuery( - statement, parameters, context._query_start_time, _timer() + statement, parameters, context._query_start_time, perf_counter() ))
dmvass/sqlalchemy-easy-profile
e98f169203de3478a4999376aac03323c5f54786
diff --git a/tests/test_profiler.py b/tests/test_profiler.py index 1a64f49..eee3a40 100644 --- a/tests/test_profiler.py +++ b/tests/test_profiler.py @@ -142,9 +142,9 @@ class TestSessionProfiler(unittest.TestCase): self.assertListEqual(debug_queries, stats["call_stack"]) self.assertDictEqual(stats["duplicates"], duplicates) - @mock.patch("easy_profile.profiler._timer") + @mock.patch("easy_profile.profiler.perf_counter") def test__before_cursor_execute(self, mocked): - expected_time = time.time() + expected_time = time.perf_counter() mocked.return_value = expected_time profiler = SessionProfiler() context = mock.Mock() @@ -158,7 +158,7 @@ class TestSessionProfiler(unittest.TestCase): ) self.assertEqual(context._query_start_time, expected_time) - @mock.patch("easy_profile.profiler._timer") + @mock.patch("easy_profile.profiler.perf_counter") def test__after_cursor_execute(self, mocked): expected_query = debug_queries[0] mocked.return_value = expected_query.end_time
Does not work on python 3.8 Exception raises when trying to use time.clock on profiler.py. timer.clock was deprecated since Python 3.3 and removed in 3.8. From Python DOCs: Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.
0.0
e98f169203de3478a4999376aac03323c5f54786
[ "tests/test_profiler.py::TestSessionProfiler::test__after_cursor_execute", "tests/test_profiler.py::TestSessionProfiler::test__before_cursor_execute" ]
[ "tests/test_profiler.py::TestSessionProfiler::test__get_stats", "tests/test_profiler.py::TestSessionProfiler::test__reset_stats", "tests/test_profiler.py::TestSessionProfiler::test_begin", "tests/test_profiler.py::TestSessionProfiler::test_begin_alive", "tests/test_profiler.py::TestSessionProfiler::test_commit", "tests/test_profiler.py::TestSessionProfiler::test_commit_alive", "tests/test_profiler.py::TestSessionProfiler::test_contextmanager_interface", "tests/test_profiler.py::TestSessionProfiler::test_decorator", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path_and_path_callback", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path_callback", "tests/test_profiler.py::TestSessionProfiler::test_initialization_custom", "tests/test_profiler.py::TestSessionProfiler::test_initialization_default", "tests/test_profiler.py::TestSessionProfiler::test_stats" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-07-26 10:50:58+00:00
mit
1,952
dmvass__sqlalchemy-easy-profile-19
diff --git a/CHANGELOG.md b/CHANGELOG.md index d446327..90450c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +## [1.1.2] - 2020-10-21 +- Fixed queries for UNIX platforms [issue-18] + ## [1.1.1] - 2020-07-26 - Fixed deprecated time.clock [issue-16] diff --git a/easy_profile/profiler.py b/easy_profile/profiler.py index bc91152..ce5793a 100644 --- a/easy_profile/profiler.py +++ b/easy_profile/profiler.py @@ -3,13 +3,20 @@ import functools import inspect from queue import Queue import re -from time import perf_counter +import sys +import time from sqlalchemy import event from sqlalchemy.engine.base import Engine from .reporters import StreamReporter +# Optimize timer function for the platform +if sys.platform == "win32": # pragma: no cover + _timer = time.perf_counter +else: + _timer = time.time + SQL_OPERATORS = ["select", "insert", "update", "delete"] OPERATOR_REGEX = re.compile("(%s) *." % "|".join(SQL_OPERATORS), re.IGNORECASE) @@ -170,10 +177,10 @@ class SessionProfiler: def _before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): - context._query_start_time = perf_counter() + context._query_start_time = _timer() def _after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): self.queries.put(DebugQuery( - statement, parameters, context._query_start_time, perf_counter() + statement, parameters, context._query_start_time, _timer() ))
dmvass/sqlalchemy-easy-profile
889e2dbf43f78743e9d822cbe10c7b843ee234fe
diff --git a/tests/test_profiler.py b/tests/test_profiler.py index eee3a40..1a64f49 100644 --- a/tests/test_profiler.py +++ b/tests/test_profiler.py @@ -142,9 +142,9 @@ class TestSessionProfiler(unittest.TestCase): self.assertListEqual(debug_queries, stats["call_stack"]) self.assertDictEqual(stats["duplicates"], duplicates) - @mock.patch("easy_profile.profiler.perf_counter") + @mock.patch("easy_profile.profiler._timer") def test__before_cursor_execute(self, mocked): - expected_time = time.perf_counter() + expected_time = time.time() mocked.return_value = expected_time profiler = SessionProfiler() context = mock.Mock() @@ -158,7 +158,7 @@ class TestSessionProfiler(unittest.TestCase): ) self.assertEqual(context._query_start_time, expected_time) - @mock.patch("easy_profile.profiler.perf_counter") + @mock.patch("easy_profile.profiler._timer") def test__after_cursor_execute(self, mocked): expected_query = debug_queries[0] mocked.return_value = expected_query.end_time
No report shown in console in 1.1.1 **Describe the bug** A clear and concise description of what the bug is. I have updated to 1.1.1 today. The SQL report no longer shows in console output. I am using a mac but not sure if it has anything to do with it. The setup to enable app - wide console logging of SQL statements is the same. This is the function that is run if env variable SQL_PROFILING = True. The app is simply flask app passed into the function. All of this works fine in 1.0.3 (and worked for last year) and is as per instructions manual. In the newest version nothing is logged to the console. ```python def add_sql_profiling(app, config_: Config): """ Adds profiling of the SQL queries performed by sqlalchemy with number of duplicates and execution times. """ if config_.SQL_PROFILING: try: from easy_profile import EasyProfileMiddleware app.wsgi_app = EasyProfileMiddleware(app.wsgi_app) except ModuleNotFoundError: logging.warning( 'Easy profile not installed, SQL profiling not available. Install using requirements-for-dev.txt' ) ``` **To Reproduce** Steps to reproduce the behavior or test case. pip install sqlalchemy-easy-profile==1.1.1 **Expected behavior** A clear and concise description of what you expected to happen. SQL statements report is logged in the console. **Additional context** Add any other context about the problem here.
0.0
889e2dbf43f78743e9d822cbe10c7b843ee234fe
[ "tests/test_profiler.py::TestSessionProfiler::test__after_cursor_execute", "tests/test_profiler.py::TestSessionProfiler::test__before_cursor_execute" ]
[ "tests/test_profiler.py::TestSessionProfiler::test__get_stats", "tests/test_profiler.py::TestSessionProfiler::test__reset_stats", "tests/test_profiler.py::TestSessionProfiler::test_begin", "tests/test_profiler.py::TestSessionProfiler::test_begin_alive", "tests/test_profiler.py::TestSessionProfiler::test_commit", "tests/test_profiler.py::TestSessionProfiler::test_commit_alive", "tests/test_profiler.py::TestSessionProfiler::test_contextmanager_interface", "tests/test_profiler.py::TestSessionProfiler::test_decorator", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path_and_path_callback", "tests/test_profiler.py::TestSessionProfiler::test_decorator_path_callback", "tests/test_profiler.py::TestSessionProfiler::test_initialization_custom", "tests/test_profiler.py::TestSessionProfiler::test_initialization_default", "tests/test_profiler.py::TestSessionProfiler::test_stats" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-10-15 08:45:19+00:00
mit
1,953
dmytrostriletskyi__pdbe-15
diff --git a/.pylintrc b/.pylintrc index 2a8fb44..5a5467d 100644 --- a/.pylintrc +++ b/.pylintrc @@ -304,7 +304,7 @@ function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_,app_name,logger,urlpatterns,application,server_port +good-names=i,j,k,ex,Run,_,app_name,logger,urlpatterns,application,server_port,multiple_function_declaration_begging_spaces,stored_import_pdb_line_begging_spaces # Include a hint for the correct naming format with invalid-name include-naming-hint=no diff --git a/pdbe/commits.py b/pdbe/commits.py index b5e31a5..425af66 100644 --- a/pdbe/commits.py +++ b/pdbe/commits.py @@ -1,8 +1,9 @@ """ Pdbe commits logic. """ -from datetime import datetime import binascii +import keyword +from datetime import datetime from os import fdopen, getcwd, path, mkdir, walk, urandom, listdir from os.path import join from tempfile import mkstemp @@ -24,48 +25,89 @@ def get_commit_functions(file_path: str) -> list: with open(file_path, 'r') as file: content = [line.strip() for line in file.readlines()] + suggested_function = '' + # pylint:disable=consider-using-enumerate - for index in range(len(content)): - line = content[index] + for line in content: - if utils.does_line_contains_import_pdb(line): - suggested_function = content[index - 1] + if utils.is_one_line_function_declaration_line(line) and not utils.is_commended_function(line): + function_open_bracket_index = line.index('(') + suggested_function = line[4:function_open_bracket_index] - if utils.is_function_sign_in_line(suggested_function): - function_open_bracket_index = suggested_function.index('(') - function_name = suggested_function[4:function_open_bracket_index] + elif 'def' in line and '(' in line and not utils.is_commended_function(line): + function_open_bracket_index = line.index('(') + suggested_function = line[4:function_open_bracket_index] - commit_functions.append(function_name) + if utils.does_line_contains_import_pdb(line): + commit_functions.append(suggested_function) return commit_functions +# too-many-locals, too-many-branches, refactor +# pylint:disable=too-many-locals,too-many-branches def restore_import_pdb_from_commit(commit_content: List[str], call_commit_path: str) -> None: """ Restore import pdb statements from specified commit. """ - file_to_restore = '' + commit_content.append('.py') # mock for algorithm below + + files_to_restore = [] + functions_to_restore = [] + temp_restore = [] + + for content in commit_content: + + if '.py' not in content: + temp_restore.append(content) - for python_file in commit_content: + if '.py' in content: + if temp_restore: + functions_to_restore.append(temp_restore) + temp_restore = [] - if '.py' in python_file: - file_to_restore = call_commit_path + python_file + file_to_restore = call_commit_path + content + files_to_restore.append(file_to_restore) - else: - fh, abs_path = mkstemp() # pylint:disable=invalid-name + for file_to_restore, functions in zip(files_to_restore, functions_to_restore): - with fdopen(fh, 'w') as new_file: - with open(file_to_restore) as old_file: - for line in old_file: - new_file.write(line) + fh, abs_path = mkstemp() # pylint:disable=invalid-name - if 'def ' + python_file + '(' in line: + with fdopen(fh, 'w') as new_file: + with open(file_to_restore) as old_file: + stored_import_pdb_line_begging_spaces = '' + stored_function_name = '' + for line in old_file: + keywords_in_line = list(set(keyword.kwlist).intersection(line.split())) + new_file.write(line) + + if 'def ' in line and '(' in line and '):' in line and not utils.is_commended_function(line): + + strip_line = line.strip() + function_open_bracket_index = strip_line.index('(') + function_name = strip_line[4:function_open_bracket_index] + + if function_name in functions: # pylint:disable=invalid-name import_pdb_line_begging_spaces = utils.get_import_pdb_line_begging_spaces(line) new_file.write(import_pdb_line_begging_spaces + utils.IMPORT_PDB_LINE) - utils.change_files_data(file_to_restore, abs_path) + elif 'def ' in line and '(' in line and '):' not in line: + function_name = line.split()[1][:-1] + + if function_name in functions: + import_pdb_line_begging_spaces = utils.get_import_pdb_line_begging_spaces(line) + stored_import_pdb_line_begging_spaces = import_pdb_line_begging_spaces + stored_function_name = function_name + else: + stored_function_name = '' + + elif 'def' not in line and '):' in line and not keywords_in_line: + if stored_function_name in functions: + new_file.write(stored_import_pdb_line_begging_spaces + utils.IMPORT_PDB_LINE) + + utils.change_files_data(file_to_restore, abs_path) def handle_commits_log() -> None: diff --git a/pdbe/main.py b/pdbe/main.py index a30afcd..d6d26b5 100644 --- a/pdbe/main.py +++ b/pdbe/main.py @@ -21,14 +21,36 @@ def put_import_pdb(file_path: str) -> None: with fdopen(fh, 'w') as new_file: with open(file_path) as old_file: + + # for multiple function declaration + import_pdb_statement_to_write = '' + multiple_function_declaration_begging_spaces = '' + for line in old_file: - if utils.is_function_sign_in_line(line) and not utils.is_commended_function(line): + if multiple_function_declaration_begging_spaces: + if 'def' not in line and '):' in line: + import_pdb_line_begging_spaces = multiple_function_declaration_begging_spaces + import_pdb_statement_to_write = import_pdb_line_begging_spaces + utils.IMPORT_PDB_LINE + multiple_function_declaration_begging_spaces = '' + + if utils.is_one_line_function_declaration_line(line) and not utils.is_commended_function(line): indents_space_count = utils.get_function_indent(line) import_pdb_line_begging_spaces = utils.get_import_pdb_line_st_spaces(indents_space_count) new_file.write(line + import_pdb_line_begging_spaces + utils.IMPORT_PDB_LINE) + else: + if 'def' in line and not utils.is_commended_function(line): + indents_space_count = utils.get_function_indent(line) + multiple_function_declaration_begging_spaces = utils.get_import_pdb_line_st_spaces( + indents_space_count + ) + new_file.write(line) + if import_pdb_statement_to_write: + new_file.write(import_pdb_statement_to_write) + import_pdb_statement_to_write = '' + utils.change_files_data(file_path, abs_path) diff --git a/pdbe/utils.py b/pdbe/utils.py index 327aa9c..687ac76 100644 --- a/pdbe/utils.py +++ b/pdbe/utils.py @@ -8,7 +8,7 @@ IMPORT_PDB_LINE = 'import pdb; pdb.set_trace()\n' LINE_FEED = '\n' -def is_function_sign_in_line(line: str) -> bool: +def is_one_line_function_declaration_line(line: str) -> bool: # pylint:disable=invalid-name """ Check if line contains function declaration. """ @@ -19,7 +19,7 @@ def does_line_contains_import_pdb(line: str) -> bool: """ Check if line contains import pdb statement. """ - return 'import pdb; pdb.set_trace()' in line + return ['import', 'pdb;', 'pdb.set_trace()'] == line.split() def is_commended_function(line: str) -> bool:
dmytrostriletskyi/pdbe
8a611655496b306206ac9e7b4e9ba933ad66ab5b
diff --git a/tests/test_utils.py b/tests/test_utils.py index 17480bc..bd96a5c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -8,7 +8,7 @@ from ddt import data, ddt, unpack from pdbe.utils import ( get_import_pdb_line_st_spaces, get_function_indent, - is_function_sign_in_line, + is_one_line_function_declaration_line, ) @@ -29,7 +29,7 @@ class TestUtils(unittest.TestCase): Case: needs to detect function declaration. Expected: only line, that contains `def`, `(` and `):` substring confirmed. """ - result = is_function_sign_in_line(line) + result = is_one_line_function_declaration_line(line) self.assertEqual(expected, result) @data(
Possible bug in multi-line function definition https://github.com/dmytrostriletskyi/pdbe/blob/e103eb47de9961a1c4f7757cc37ca40eb98c0165/pdbe/utils.py#L11 This propably won't work with multiline function definitions.
0.0
8a611655496b306206ac9e7b4e9ba933ad66ab5b
[ "tests/test_utils.py::TestUtils::test_get_function_indent_1___def_function__args____kwargs_____0_", "tests/test_utils.py::TestUtils::test_get_import_pdb_line_start_spaces_3__8_________________", "tests/test_utils.py::TestUtils::test_get_function_indent_3___________def_function__args____kwargs_____8_", "tests/test_utils.py::TestUtils::test_is_function_sign_in_line_3___def_function__args____kwargs_____True_", "tests/test_utils.py::TestUtils::test_is_function_sign_in_line_2___def_fake_function____False_", "tests/test_utils.py::TestUtils::test_get_import_pdb_line_start_spaces_1__0_________", "tests/test_utils.py::TestUtils::test_get_function_indent_2_______def_function__args____kwargs_____4_", "tests/test_utils.py::TestUtils::test_is_function_sign_in_line_1___import_sys___False_", "tests/test_utils.py::TestUtils::test_get_import_pdb_line_start_spaces_2__4_____________" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-02-10 23:15:03+00:00
mit
1,954
doccano__doccano-1557
diff --git a/backend/api/views/download/data.py b/backend/api/views/download/data.py index 68978184..79bfe7e8 100644 --- a/backend/api/views/download/data.py +++ b/backend/api/views/download/data.py @@ -1,3 +1,4 @@ +import json from typing import Any, Dict, List @@ -16,4 +17,10 @@ class Record: self.metadata = metadata def __str__(self): - return f'{self.data}\t{self.label}' + return json.dumps({ + 'id': self.id, + 'data': self.data, + 'label': self.label, + 'user': self.user, + 'metadata': self.metadata + }) diff --git a/backend/api/views/download/writer.py b/backend/api/views/download/writer.py index dd0e88b4..5de1264e 100644 --- a/backend/api/views/download/writer.py +++ b/backend/api/views/download/writer.py @@ -90,7 +90,7 @@ class CsvWriter(BaseWriter): def create_header(self, records: List[Record]) -> Iterable[str]: header = ['id', 'data', 'label'] - header += list(itertools.chain(*[r.metadata.keys() for r in records])) + header += sorted(set(itertools.chain(*[r.metadata.keys() for r in records]))) return header
doccano/doccano
217cc85348972fcf38f3c58284dd2168db2bd3bb
diff --git a/backend/api/tests/download/__init__.py b/backend/api/tests/download/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/api/tests/download/test_writer.py b/backend/api/tests/download/test_writer.py new file mode 100644 index 00000000..2c48cb92 --- /dev/null +++ b/backend/api/tests/download/test_writer.py @@ -0,0 +1,53 @@ +import unittest +from unittest.mock import call, patch + +from ...views.download.data import Record +from ...views.download.writer import CsvWriter + + +class TestCSVWriter(unittest.TestCase): + + def setUp(self): + self.records = [ + Record(id=0, data='exampleA', label=['labelA'], user='admin', metadata={'hidden': 'secretA'}), + Record(id=1, data='exampleB', label=['labelB'], user='admin', metadata={'hidden': 'secretB'}), + Record(id=2, data='exampleC', label=['labelC'], user='admin', metadata={'meta': 'secretC'}) + ] + + def test_create_header(self): + writer = CsvWriter('.') + header = writer.create_header(self.records) + expected = ['id', 'data', 'label', 'hidden', 'meta'] + self.assertEqual(header, expected) + + def test_create_line(self): + writer = CsvWriter('.') + record = self.records[0] + line = writer.create_line(record) + expected = { + 'id': record.id, + 'data': record.data, + 'label': record.label[0], + 'hidden': 'secretA' + } + self.assertEqual(line, expected) + + @patch('os.remove') + @patch('zipfile.ZipFile') + @patch('csv.DictWriter.writerow') + @patch('builtins.open') + def test_dump(self, mock_open_file, csv_io, zip_io, mock_remove_file): + writer = CsvWriter('.') + writer.write(self.records) + + self.assertEqual(mock_open_file.call_count, 1) + mock_open_file.assert_called_with('./admin.csv', mode='a', encoding='utf-8') + + self.assertEqual(csv_io.call_count, len(self.records) + 1) # +1 is for a header + calls = [ + call({'id': 'id', 'data': 'data', 'label': 'label', 'hidden': 'hidden', 'meta': 'meta'}), + call({'id': 0, 'data': 'exampleA', 'label': 'labelA', 'hidden': 'secretA'}), + call({'id': 1, 'data': 'exampleB', 'label': 'labelB', 'hidden': 'secretB'}), + call({'id': 2, 'data': 'exampleC', 'label': 'labelC', 'meta': 'secretC'}) + ] + csv_io.assert_has_calls(calls)
Metadata column repeated when exported as csv Hi I have recently come across a bug when you export data as csv <environment.--> *   Operating System:MacOS 10.14 *   Python Version Used: 3.9.5 *   Doccano installed through pip3 install     doccano I have created a DocumentClassification project and have imported some json data. The json data is in the format of ```bash {"text":"The ravioli was excellent" , "hidden":"The FOOD was excellent"} ``` When these sentences are imported, the "hidden" : "The FOOD was excellent" becomes part of the Metadata. I have quite a few of these sentences and have labelled them with my own labels The issue is when I export the dataset as csv, the Metadata column repeats. For example if I have 10 labelled sentences, the Metadata column is repeated 10 times per row of data in excel.
0.0
217cc85348972fcf38f3c58284dd2168db2bd3bb
[ "backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_header" ]
[ "backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_line", "backend/api/tests/download/test_writer.py::TestCSVWriter::test_dump" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-11-11 01:37:39+00:00
mit
1,955
doccano__doccano-1558
diff --git a/backend/api/views/download/writer.py b/backend/api/views/download/writer.py index 5de1264e..a4d5293a 100644 --- a/backend/api/views/download/writer.py +++ b/backend/api/views/download/writer.py @@ -84,7 +84,7 @@ class CsvWriter(BaseWriter): return { 'id': record.id, 'data': record.data, - 'label': '#'.join(record.label), + 'label': '#'.join(sorted(record.label)), **record.metadata } @@ -144,6 +144,7 @@ class FastTextWriter(LineWriter): def create_line(self, record): line = [f'__label__{label}' for label in record.label] + line.sort() line.append(record.data) line = ' '.join(line) return line
doccano/doccano
0d7bf054e619c144ec84fcf18f9457af8822a204
diff --git a/backend/api/tests/download/test_writer.py b/backend/api/tests/download/test_writer.py index 2c48cb92..720244dd 100644 --- a/backend/api/tests/download/test_writer.py +++ b/backend/api/tests/download/test_writer.py @@ -32,6 +32,16 @@ class TestCSVWriter(unittest.TestCase): } self.assertEqual(line, expected) + def test_label_order(self): + writer = CsvWriter('.') + record1 = Record(id=0, data='', label=['labelA', 'labelB'], user='', metadata={}) + record2 = Record(id=0, data='', label=['labelB', 'labelA'], user='', metadata={}) + line1 = writer.create_line(record1) + line2 = writer.create_line(record2) + expected = 'labelA#labelB' + self.assertEqual(line1['label'], expected) + self.assertEqual(line2['label'], expected) + @patch('os.remove') @patch('zipfile.ZipFile') @patch('csv.DictWriter.writerow')
Mutli-label text classification export issues: same classes but in different orders How to reproduce the behaviour --------- <!-- Before submitting an issue, make sure to check the docs and closed issues and FAQ to see if any of the solutions work for you. https://github.com/doccano/doccano/wiki/Frequently-Asked-Questions --> We are two annotators on a multi-label classification project. When I export the annotations, for some examples, me and my co-annotator have put the same labels, but on the exported CSV, they do not appear in the same order: Annotator 1: | text | labels | | example 1 | label1#label2#label3 | Annotator 2: | text | labels | | example 1 | label2#label3#label1 | As I try to use these CSVs for comparing our annotations, this brings more difficulty. <!-- Include a code example or the steps that led to the problem. Please try to be as specific as possible. --> Your Environment --------- <!-- Include details of your environment.--> * Operating System: Debian * Python Version Used: Don't know, I pulled the latest version from Docker Hub * When you install doccano: 3 days ago * How did you install doccano (Heroku button etc): Docker
0.0
0d7bf054e619c144ec84fcf18f9457af8822a204
[ "backend/api/tests/download/test_writer.py::TestCSVWriter::test_label_order" ]
[ "backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_header", "backend/api/tests/download/test_writer.py::TestCSVWriter::test_create_line", "backend/api/tests/download/test_writer.py::TestCSVWriter::test_dump" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-11-12 01:01:49+00:00
mit
1,956
docker__docker-py-1022
diff --git a/docker/auth/auth.py b/docker/auth/auth.py index eedb7944..d23e6f3c 100644 --- a/docker/auth/auth.py +++ b/docker/auth/auth.py @@ -117,7 +117,7 @@ def parse_auth(entries, raise_on_error=False): conf = {} for registry, entry in six.iteritems(entries): - if not (isinstance(entry, dict) and 'auth' in entry): + if not isinstance(entry, dict): log.debug( 'Config entry for key {0} is not auth config'.format(registry) ) @@ -130,6 +130,16 @@ def parse_auth(entries, raise_on_error=False): 'Invalid configuration for registry {0}'.format(registry) ) return {} + if 'auth' not in entry: + # Starting with engine v1.11 (API 1.23), an empty dictionary is + # a valid value in the auths config. + # https://github.com/docker/compose/issues/3265 + log.debug( + 'Auth data for {0} is absent. Client might be using a ' + 'credentials store instead.' + ) + return {} + username, password = decode_auth(entry['auth']) log.debug( 'Found entry (registry={0}, username={1})' @@ -189,6 +199,9 @@ def load_config(config_path=None): if data.get('HttpHeaders'): log.debug("Found 'HttpHeaders' section") res.update({'HttpHeaders': data['HttpHeaders']}) + if data.get('credsStore'): + log.debug("Found 'credsStore' section") + res.update({'credsStore': data['credsStore']}) if res: return res else:
docker/docker-py
e743254b42080e6d199fc10f4812a42ecb8d536f
diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py index 921aae00..4ea40477 100644 --- a/tests/unit/auth_test.py +++ b/tests/unit/auth_test.py @@ -459,6 +459,5 @@ class LoadConfigTest(base.Cleanup, base.BaseTestCase): with open(dockercfg_path, 'w') as f: json.dump(config, f) - self.assertRaises( - errors.InvalidConfigFile, auth.load_config, dockercfg_path - ) + cfg = auth.load_config(dockercfg_path) + assert cfg == {}
Empty auth dictionary should be valid docker/compose#3265
0.0
e743254b42080e6d199fc10f4812a42ecb8d536f
[ "tests/unit/auth_test.py::LoadConfigTest::test_load_config_invalid_auth_dict" ]
[ "tests/unit/auth_test.py::RegressionTest::test_803_urlsafe_encode", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_explicit_hub_index_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_explicit_legacy_hub_index_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_invalid_index_name", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_dotted_hub_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_hub_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_hub_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_localhost", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_localhost_with_username", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_no_dots_but_port", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_no_dots_but_port_and_username", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry_with_port", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry_with_username", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_explicit_none", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_fully_explicit", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_hostname_only", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_legacy_config", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_match", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_trailing_slash", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_insecure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_secure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_protocol", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_path_wrong_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_explicit_hub", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_explicit_legacy_hub", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_hub_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_library_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_private_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_unauthenticated_registry", "tests/unit/auth_test.py::LoadConfigTest::test_load_config", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_utf8", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_auths", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_headers", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_no_file", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_unknown_keys", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_with_random_name" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-04-05 19:54:10+00:00
apache-2.0
1,957
docker__docker-py-1130
diff --git a/docker/api/container.py b/docker/api/container.py index 9cc14dbd..b8507d85 100644 --- a/docker/api/container.py +++ b/docker/api/container.py @@ -15,12 +15,18 @@ class ContainerApiMixin(object): 'logs': logs and 1 or 0, 'stdout': stdout and 1 or 0, 'stderr': stderr and 1 or 0, - 'stream': stream and 1 or 0, + 'stream': stream and 1 or 0 } + + headers = { + 'Connection': 'Upgrade', + 'Upgrade': 'tcp' + } + u = self._url("/containers/{0}/attach", container) - response = self._post(u, params=params, stream=stream) + response = self._post(u, headers=headers, params=params, stream=stream) - return self._get_result(container, stream, response) + return self._read_from_socket(response, stream) @utils.check_resource def attach_socket(self, container, params=None, ws=False): @@ -34,9 +40,18 @@ class ContainerApiMixin(object): if ws: return self._attach_websocket(container, params) + headers = { + 'Connection': 'Upgrade', + 'Upgrade': 'tcp' + } + u = self._url("/containers/{0}/attach", container) - return self._get_raw_response_socket(self.post( - u, None, params=self._attach_params(params), stream=True)) + return self._get_raw_response_socket( + self.post( + u, None, params=self._attach_params(params), stream=True, + headers=headers + ) + ) @utils.check_resource def commit(self, container, repository=None, tag=None, message=None, diff --git a/docker/api/exec_api.py b/docker/api/exec_api.py index f0e4afa6..6e499960 100644 --- a/docker/api/exec_api.py +++ b/docker/api/exec_api.py @@ -56,8 +56,6 @@ class ExecApiMixin(object): def exec_start(self, exec_id, detach=False, tty=False, stream=False, socket=False): # we want opened socket if socket == True - if socket: - stream = True if isinstance(exec_id, dict): exec_id = exec_id.get('Id') @@ -66,10 +64,18 @@ class ExecApiMixin(object): 'Detach': detach } + headers = {} if detach else { + 'Connection': 'Upgrade', + 'Upgrade': 'tcp' + } + res = self._post_json( - self._url('/exec/{0}/start', exec_id), data=data, stream=stream + self._url('/exec/{0}/start', exec_id), + headers=headers, + data=data, + stream=True ) if socket: return self._get_raw_response_socket(res) - return self._get_result_tty(stream, res, tty) + return self._read_from_socket(res, stream) diff --git a/docker/client.py b/docker/client.py index b96a78ce..6ca9e57a 100644 --- a/docker/client.py +++ b/docker/client.py @@ -29,6 +29,7 @@ from .ssladapter import ssladapter from .tls import TLSConfig from .transport import UnixAdapter from .utils import utils, check_resource, update_headers, kwargs_from_env +from .utils.socket import frames_iter try: from .transport import NpipeAdapter except ImportError: @@ -305,6 +306,14 @@ class Client( for out in response.iter_content(chunk_size=1, decode_unicode=True): yield out + def _read_from_socket(self, response, stream): + socket = self._get_raw_response_socket(response) + + if stream: + return frames_iter(socket) + else: + return six.binary_type().join(frames_iter(socket)) + def _disable_socket_timeout(self, socket): """ Depending on the combination of python version and whether we're connecting over http or https, we might need to access _sock, which diff --git a/docker/utils/socket.py b/docker/utils/socket.py new file mode 100644 index 00000000..ed343507 --- /dev/null +++ b/docker/utils/socket.py @@ -0,0 +1,68 @@ +import errno +import os +import select +import struct + +import six + + +class SocketError(Exception): + pass + + +def read(socket, n=4096): + """ + Reads at most n bytes from socket + """ + recoverable_errors = (errno.EINTR, errno.EDEADLK, errno.EWOULDBLOCK) + + # wait for data to become available + select.select([socket], [], []) + + try: + if hasattr(socket, 'recv'): + return socket.recv(n) + return os.read(socket.fileno(), n) + except EnvironmentError as e: + if e.errno not in recoverable_errors: + raise + + +def read_exactly(socket, n): + """ + Reads exactly n bytes from socket + Raises SocketError if there isn't enough data + """ + data = six.binary_type() + while len(data) < n: + next_data = read(socket, n - len(data)) + if not next_data: + raise SocketError("Unexpected EOF") + data += next_data + return data + + +def next_frame_size(socket): + """ + Returns the size of the next frame of data waiting to be read from socket, + according to the protocol defined here: + + https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/attach-to-a-container + """ + try: + data = read_exactly(socket, 8) + except SocketError: + return 0 + + _, actual = struct.unpack('>BxxxL', data) + return actual + + +def frames_iter(socket): + """ + Returns a generator of frames read from socket + """ + n = next_frame_size(socket) + while n > 0: + yield read(socket, n) + n = next_frame_size(socket)
docker/docker-py
b511352bea79aff12d565b11662bebee36e362fc
diff --git a/tests/helpers.py b/tests/helpers.py index 21036ace..94ea3887 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -1,9 +1,6 @@ -import errno import os import os.path -import select import shutil -import struct import tarfile import tempfile import unittest @@ -54,7 +51,7 @@ def exec_driver_is_native(): c = docker_client() EXEC_DRIVER = c.info()['ExecutionDriver'] c.close() - return EXEC_DRIVER.startswith('native') + return EXEC_DRIVER.startswith('native') or EXEC_DRIVER == '' def docker_client(**kwargs): @@ -67,49 +64,6 @@ def docker_client_kwargs(**kwargs): return client_kwargs -def read_socket(socket, n=4096): - """ Code stolen from dockerpty to read the socket """ - recoverable_errors = (errno.EINTR, errno.EDEADLK, errno.EWOULDBLOCK) - - # wait for data to become available - select.select([socket], [], []) - - try: - if hasattr(socket, 'recv'): - return socket.recv(n) - return os.read(socket.fileno(), n) - except EnvironmentError as e: - if e.errno not in recoverable_errors: - raise - - -def next_packet_size(socket): - """ Code stolen from dockerpty to get the next packet size """ - data = six.binary_type() - while len(data) < 8: - next_data = read_socket(socket, 8 - len(data)) - if not next_data: - return 0 - data = data + next_data - - if data is None: - return 0 - - if len(data) == 8: - _, actual = struct.unpack('>BxxxL', data) - return actual - - -def read_data(socket, packet_size): - data = six.binary_type() - while len(data) < packet_size: - next_data = read_socket(socket, packet_size - len(data)) - if not next_data: - assert False, "Failed trying to read in the dataz" - data += next_data - return data - - class BaseTestCase(unittest.TestCase): tmp_imgs = [] tmp_containers = [] diff --git a/tests/integration/container_test.py b/tests/integration/container_test.py index 56b648a3..61b33983 100644 --- a/tests/integration/container_test.py +++ b/tests/integration/container_test.py @@ -3,6 +3,8 @@ import signal import tempfile import docker +from docker.utils.socket import next_frame_size +from docker.utils.socket import read_exactly import pytest import six @@ -1025,9 +1027,9 @@ class AttachContainerTest(helpers.BaseTestCase): self.client.start(ident) - next_size = helpers.next_packet_size(pty_stdout) + next_size = next_frame_size(pty_stdout) self.assertEqual(next_size, len(line)) - data = helpers.read_data(pty_stdout, next_size) + data = read_exactly(pty_stdout, next_size) self.assertEqual(data.decode('utf-8'), line) diff --git a/tests/integration/exec_test.py b/tests/integration/exec_test.py index 9f548080..8bf2762a 100644 --- a/tests/integration/exec_test.py +++ b/tests/integration/exec_test.py @@ -1,5 +1,8 @@ import pytest +from docker.utils.socket import next_frame_size +from docker.utils.socket import read_exactly + from .. import helpers BUSYBOX = helpers.BUSYBOX @@ -107,9 +110,9 @@ class ExecTest(helpers.BaseTestCase): socket = self.client.exec_start(exec_id, socket=True) self.addCleanup(socket.close) - next_size = helpers.next_packet_size(socket) + next_size = next_frame_size(socket) self.assertEqual(next_size, len(line)) - data = helpers.read_data(socket, next_size) + data = read_exactly(socket, next_size) self.assertEqual(data.decode('utf-8'), line) def test_exec_inspect(self): diff --git a/tests/unit/api_test.py b/tests/unit/api_test.py index 23fd1913..34bf14f6 100644 --- a/tests/unit/api_test.py +++ b/tests/unit/api_test.py @@ -93,6 +93,10 @@ def fake_put(self, url, *args, **kwargs): def fake_delete(self, url, *args, **kwargs): return fake_request('DELETE', url, *args, **kwargs) + +def fake_read_from_socket(self, response, stream): + return six.binary_type() + url_base = 'http+docker://localunixsocket/' url_prefix = '{0}v{1}/'.format( url_base, @@ -103,7 +107,8 @@ class DockerClientTest(base.Cleanup, base.BaseTestCase): def setUp(self): self.patcher = mock.patch.multiple( 'docker.Client', get=fake_get, post=fake_post, put=fake_put, - delete=fake_delete + delete=fake_delete, + _read_from_socket=fake_read_from_socket ) self.patcher.start() self.client = docker.Client() diff --git a/tests/unit/exec_test.py b/tests/unit/exec_test.py index 3007799c..6ba2a3dd 100644 --- a/tests/unit/exec_test.py +++ b/tests/unit/exec_test.py @@ -51,8 +51,36 @@ class ExecTest(DockerClientTest): } ) - self.assertEqual(args[1]['headers'], - {'Content-Type': 'application/json'}) + self.assertEqual( + args[1]['headers'], { + 'Content-Type': 'application/json', + 'Connection': 'Upgrade', + 'Upgrade': 'tcp' + } + ) + + def test_exec_start_detached(self): + self.client.exec_start(fake_api.FAKE_EXEC_ID, detach=True) + + args = fake_request.call_args + self.assertEqual( + args[0][1], url_prefix + 'exec/{0}/start'.format( + fake_api.FAKE_EXEC_ID + ) + ) + + self.assertEqual( + json.loads(args[1]['data']), { + 'Tty': False, + 'Detach': True + } + ) + + self.assertEqual( + args[1]['headers'], { + 'Content-Type': 'application/json' + } + ) def test_exec_inspect(self): self.client.exec_inspect(fake_api.FAKE_EXEC_ID)
The api client should send connection upgrade headers To hint proxies about connection hijacking, docker clients should send connection upgrade headers like the docker cli does. From https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/4-2-hijacking: > In this version of the API, /attach, uses hijacking to transport stdin, stdout, and stderr on the same socket. > > To hint potential proxies about connection hijacking, Docker client sends connection upgrade headers similarly to websocket. ``` Upgrade: tcp Connection: Upgrade ``` On Docker for Desktop, the proxy that sits between Docker Compose and the daemon will not be aware that the connection will be hijacked. This can lead to an issue where the proxy will install a CloseNotifier and just after that will hijack the connection, which is know to be incompatible. See https://github.com/docker/compose/issues/3685 See also https://github.com/docker/compose/issues/3700
0.0
b511352bea79aff12d565b11662bebee36e362fc
[ "tests/unit/api_test.py::DockerApiTest::test_auto_retrieve_server_version", "tests/unit/api_test.py::DockerApiTest::test_create_host_config_secopt", "tests/unit/api_test.py::DockerApiTest::test_ctor", "tests/unit/api_test.py::DockerApiTest::test_events", "tests/unit/api_test.py::DockerApiTest::test_events_with_filters", "tests/unit/api_test.py::DockerApiTest::test_events_with_since_until", "tests/unit/api_test.py::DockerApiTest::test_info", "tests/unit/api_test.py::DockerApiTest::test_remove_link", "tests/unit/api_test.py::DockerApiTest::test_retrieve_server_version", "tests/unit/api_test.py::DockerApiTest::test_search", "tests/unit/api_test.py::DockerApiTest::test_url_compatibility_http", "tests/unit/api_test.py::DockerApiTest::test_url_compatibility_http_unix_triple_slash", "tests/unit/api_test.py::DockerApiTest::test_url_compatibility_tcp", "tests/unit/api_test.py::DockerApiTest::test_url_compatibility_unix", "tests/unit/api_test.py::DockerApiTest::test_url_compatibility_unix_triple_slash", "tests/unit/api_test.py::DockerApiTest::test_url_invalid_resource", "tests/unit/api_test.py::DockerApiTest::test_url_no_resource", "tests/unit/api_test.py::DockerApiTest::test_url_unversioned_api", "tests/unit/api_test.py::DockerApiTest::test_url_valid_resource", "tests/unit/api_test.py::DockerApiTest::test_version", "tests/unit/api_test.py::DockerApiTest::test_version_no_api_version", "tests/unit/exec_test.py::ExecTest::test_exec_create", "tests/unit/exec_test.py::ExecTest::test_exec_inspect", "tests/unit/exec_test.py::ExecTest::test_exec_resize", "tests/unit/exec_test.py::ExecTest::test_exec_start", "tests/unit/exec_test.py::ExecTest::test_exec_start_detached" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-07-13 21:07:00+00:00
apache-2.0
1,958
docker__docker-py-1143
diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 4d218692..1cfc8acc 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -22,8 +22,8 @@ import tarfile import tempfile import warnings from distutils.version import StrictVersion -from fnmatch import fnmatch from datetime import datetime +from fnmatch import fnmatch import requests import six @@ -33,6 +33,10 @@ from .. import errors from .. import tls from .types import Ulimit, LogConfig +if six.PY2: + from urllib import splitnport +else: + from urllib.parse import splitnport DEFAULT_HTTP_HOST = "127.0.0.1" DEFAULT_UNIX_SOCKET = "http+unix://var/run/docker.sock" @@ -387,7 +391,6 @@ def parse_repository_tag(repo_name): # Protocol translation: tcp -> http, unix -> http+unix def parse_host(addr, is_win32=False, tls=False): proto = "http+unix" - host = DEFAULT_HTTP_HOST port = None path = '' @@ -427,32 +430,27 @@ def parse_host(addr, is_win32=False, tls=False): ) proto = "https" if tls else "http" - if proto != "http+unix" and ":" in addr: - host_parts = addr.split(':') - if len(host_parts) != 2: - raise errors.DockerException( - "Invalid bind address format: {0}".format(addr) - ) - if host_parts[0]: - host = host_parts[0] + if proto in ("http", "https"): + address_parts = addr.split('/', 1) + host = address_parts[0] + if len(address_parts) == 2: + path = '/' + address_parts[1] + host, port = splitnport(host) - port = host_parts[1] - if '/' in port: - port, path = port.split('/', 1) - path = '/{0}'.format(path) - try: - port = int(port) - except Exception: + if port is None: raise errors.DockerException( "Invalid port: {0}".format(addr) ) - elif proto in ("http", "https") and ':' not in addr: - raise errors.DockerException( - "Bind address needs a port: {0}".format(addr)) + if not host: + host = DEFAULT_HTTP_HOST else: host = addr + if proto in ("http", "https") and port == -1: + raise errors.DockerException( + "Bind address needs a port: {0}".format(addr)) + if proto == "http+unix" or proto == 'npipe': return "{0}://{1}".format(proto, host) return "{0}://{1}:{2}{3}".format(proto, host, port, path)
docker/docker-py
2d3bda84de39a75e560fc79512143d43e5d61226
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 68484fe5..0f7a58c9 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -404,10 +404,18 @@ class ParseHostTest(base.BaseTestCase): 'https://kokia.jp:2375': 'https://kokia.jp:2375', 'unix:///var/run/docker.sock': 'http+unix:///var/run/docker.sock', 'unix://': 'http+unix://var/run/docker.sock', + '12.234.45.127:2375/docker/engine': ( + 'http://12.234.45.127:2375/docker/engine' + ), 'somehost.net:80/service/swarm': ( 'http://somehost.net:80/service/swarm' ), 'npipe:////./pipe/docker_engine': 'npipe:////./pipe/docker_engine', + '[fd12::82d1]:2375': 'http://[fd12::82d1]:2375', + 'https://[fd12:5672::12aa]:1090': 'https://[fd12:5672::12aa]:1090', + '[fd12::82d1]:2375/docker/engine': ( + 'http://[fd12::82d1]:2375/docker/engine' + ), } for host in invalid_hosts: @@ -415,7 +423,7 @@ class ParseHostTest(base.BaseTestCase): parse_host(host, None) for host, expected in valid_hosts.items(): - self.assertEqual(parse_host(host, None), expected, msg=host) + assert parse_host(host, None) == expected def test_parse_host_empty_value(self): unix_socket = 'http+unix://var/run/docker.sock'
Support IPv6 addresses in DOCKER_HOST Raised in https://github.com/docker/compose/issues/2879. See https://github.com/docker/docker/pull/16950 for the Engine implementation.
0.0
2d3bda84de39a75e560fc79512143d43e5d61226
[ "tests/unit/utils_test.py::ParseHostTest::test_parse_host" ]
[ "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-07-28 01:43:06+00:00
apache-2.0
1,959
docker__docker-py-1150
diff --git a/docker/utils/decorators.py b/docker/utils/decorators.py index 7c41a5f8..46c28a80 100644 --- a/docker/utils/decorators.py +++ b/docker/utils/decorators.py @@ -40,7 +40,7 @@ def minimum_version(version): def update_headers(f): def inner(self, *args, **kwargs): if 'HttpHeaders' in self._auth_configs: - if 'headers' not in kwargs: + if not kwargs.get('headers'): kwargs['headers'] = self._auth_configs['HttpHeaders'] else: kwargs['headers'].update(self._auth_configs['HttpHeaders'])
docker/docker-py
650cc70e934044fcb5dfd27fd27777f91c337b6c
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 0f7a58c9..47ced433 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -20,9 +20,11 @@ from docker.utils import ( create_host_config, Ulimit, LogConfig, parse_bytes, parse_env_file, exclude_paths, convert_volume_binds, decode_json_header, tar, split_command, create_ipam_config, create_ipam_pool, parse_devices, + update_headers, ) -from docker.utils.utils import create_endpoint_config + from docker.utils.ports import build_port_bindings, split_port +from docker.utils.utils import create_endpoint_config from .. import base from ..helpers import make_tree @@ -34,6 +36,37 @@ TEST_CERT_DIR = os.path.join( ) +class DecoratorsTest(base.BaseTestCase): + def test_update_headers(self): + sample_headers = { + 'X-Docker-Locale': 'en-US', + } + + def f(self, headers=None): + return headers + + client = Client() + client._auth_configs = {} + + g = update_headers(f) + assert g(client, headers=None) is None + assert g(client, headers={}) == {} + assert g(client, headers={'Content-type': 'application/json'}) == { + 'Content-type': 'application/json', + } + + client._auth_configs = { + 'HttpHeaders': sample_headers + } + + assert g(client, headers=None) == sample_headers + assert g(client, headers={}) == sample_headers + assert g(client, headers={'Content-type': 'application/json'}) == { + 'Content-type': 'application/json', + 'X-Docker-Locale': 'en-US', + } + + class HostConfigTest(base.BaseTestCase): def test_create_host_config_no_options(self): config = create_host_config(version='1.19')
Client.build crashes when trying to pull a new image if HttpHeaders are set in config file ```python import docker c = docker.Client() c.build('https://github.com/docker/compose.git') --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-d78c607c9627> in <module>() ----> 1 c.build('https://github.com/docker/compose.git') /home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/api/build.pyc in build(self, path, tag, quiet, fileobj, nocache, rm, stream, timeout, custom_context, encoding, pull, forcerm, dockerfile, container_limits, decode, buildargs, gzip) 102 headers=headers, 103 stream=stream, --> 104 timeout=timeout, 105 ) 106 /home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/utils/decorators.pyc in inner(self, *args, **kwargs) 44 kwargs['headers'] = self._auth_configs['HttpHeaders'] 45 else: ---> 46 kwargs['headers'].update(self._auth_configs['HttpHeaders']) 47 return f(self, *args, **kwargs) 48 return inner AttributeError: 'NoneType' object has no attribute 'update' ```
0.0
650cc70e934044fcb5dfd27fd27777f91c337b6c
[ "tests/unit/utils_test.py::DecoratorsTest::test_update_headers" ]
[ "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2016-08-03 00:27:54+00:00
apache-2.0
1,960
docker__docker-py-1167
diff --git a/docker/client.py b/docker/client.py index d1c6ee5f..ef718a72 100644 --- a/docker/client.py +++ b/docker/client.py @@ -114,7 +114,8 @@ class Client( @classmethod def from_env(cls, **kwargs): - return cls(**kwargs_from_env(**kwargs)) + version = kwargs.pop('version', None) + return cls(version=version, **kwargs_from_env(**kwargs)) def _retrieve_server_version(self): try:
docker/docker-py
2ef02df2f06fafe7d71c96bac1e18d68217703ab
diff --git a/tests/unit/client_test.py b/tests/unit/client_test.py index b21f1d6a..6ceb8cbb 100644 --- a/tests/unit/client_test.py +++ b/tests/unit/client_test.py @@ -25,6 +25,14 @@ class ClientTest(base.BaseTestCase): client = Client.from_env() self.assertEqual(client.base_url, "https://192.168.59.103:2376") + def test_from_env_with_version(self): + os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', + DOCKER_CERT_PATH=TEST_CERT_DIR, + DOCKER_TLS_VERIFY='1') + client = Client.from_env(version='2.32') + self.assertEqual(client.base_url, "https://192.168.59.103:2376") + self.assertEqual(client._version, '2.32') + class DisableSocketTest(base.BaseTestCase): class DummySocket(object):
Feature Request: docker.from_env(version='auto') Feature request to add auto api version support for ```docker.from_env()``` similar to ```docker.Client(version='auto')```? I noticed that one of the suggestions from #402 for the ```version='auto'``` option was now available for ```docker.Client()``` but doesn't work for ```docker.from_env()```.
0.0
2ef02df2f06fafe7d71c96bac1e18d68217703ab
[ "tests/unit/client_test.py::ClientTest::test_from_env_with_version" ]
[ "tests/unit/client_test.py::ClientTest::test_from_env", "tests/unit/client_test.py::DisableSocketTest::test_disable_socket_timeout", "tests/unit/client_test.py::DisableSocketTest::test_disable_socket_timeout2", "tests/unit/client_test.py::DisableSocketTest::test_disable_socket_timout_non_blocking" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2016-08-23 23:53:03+00:00
apache-2.0
1,961
docker__docker-py-1178
diff --git a/docker/api/network.py b/docker/api/network.py index 34cd8987..0ee0dab6 100644 --- a/docker/api/network.py +++ b/docker/api/network.py @@ -22,7 +22,8 @@ class NetworkApiMixin(object): @minimum_version('1.21') def create_network(self, name, driver=None, options=None, ipam=None, - check_duplicate=None, internal=False): + check_duplicate=None, internal=False, labels=None, + enable_ipv6=False): if options is not None and not isinstance(options, dict): raise TypeError('options must be a dictionary') @@ -34,6 +35,22 @@ class NetworkApiMixin(object): 'CheckDuplicate': check_duplicate } + if labels is not None: + if version_lt(self._version, '1.23'): + raise InvalidVersion( + 'network labels were introduced in API 1.23' + ) + if not isinstance(labels, dict): + raise TypeError('labels must be a dictionary') + data["Labels"] = labels + + if enable_ipv6: + if version_lt(self._version, '1.23'): + raise InvalidVersion( + 'enable_ipv6 was introduced in API 1.23' + ) + data['EnableIPv6'] = True + if internal: if version_lt(self._version, '1.22'): raise InvalidVersion('Internal networks are not ' @@ -76,8 +93,15 @@ class NetworkApiMixin(object): @check_resource @minimum_version('1.21') - def disconnect_container_from_network(self, container, net_id): - data = {"container": container} + def disconnect_container_from_network(self, container, net_id, + force=False): + data = {"Container": container} + if force: + if version_lt(self._version, '1.22'): + raise InvalidVersion( + 'Forced disconnect was introduced in API 1.22' + ) + data['Force'] = force url = self._url("/networks/{0}/disconnect", net_id) res = self._post_json(url, data=data) self._raise_for_status(res) diff --git a/docs/api.md b/docs/api.md index 895d7d45..1699344a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -283,22 +283,25 @@ The utility can be used as follows: ```python >>> import docker.utils >>> my_envs = docker.utils.parse_env_file('/path/to/file') ->>> docker.utils.create_container_config('1.18', '_mongodb', 'foobar', environment=my_envs) +>>> client.create_container('myimage', 'command', environment=my_envs) ``` -You can now use this with 'environment' for `create_container`. - - ## create_network -Create a network, similar to the `docker network create` command. +Create a network, similar to the `docker network create` command. See the +[networks documentation](networks.md) for details. **Params**: * name (str): Name of the network * driver (str): Name of the driver used to create the network - * options (dict): Driver options as a key-value dictionary +* ipam (dict): Optional custom IP scheme for the network +* check_duplicate (bool): Request daemon to check for networks with same name. + Default: `True`. +* internal (bool): Restrict external access to the network. Default `False`. +* labels (dict): Map of labels to set on the network. Default `None`. +* enable_ipv6 (bool): Enable IPv6 on the network. Default `False`. **Returns** (dict): The created network reference object @@ -352,6 +355,8 @@ Inspect changes on a container's filesystem. * container (str): container-id/name to be disconnected from a network * net_id (str): network id +* force (bool): Force the container to disconnect from a network. + Default: `False` ## events
docker/docker-py
24bfb99e05d57a7a098a81fb86ea7b93cff62661
diff --git a/tests/integration/network_test.py b/tests/integration/network_test.py index 27e1b14d..6726db4b 100644 --- a/tests/integration/network_test.py +++ b/tests/integration/network_test.py @@ -115,7 +115,8 @@ class TestNetworks(helpers.BaseTestCase): network_data = self.client.inspect_network(net_id) self.assertEqual( list(network_data['Containers'].keys()), - [container['Id']]) + [container['Id']] + ) with pytest.raises(docker.errors.APIError): self.client.connect_container_to_network(container, net_id) @@ -127,6 +128,33 @@ class TestNetworks(helpers.BaseTestCase): with pytest.raises(docker.errors.APIError): self.client.disconnect_container_from_network(container, net_id) + @requires_api_version('1.22') + def test_connect_and_force_disconnect_container(self): + net_name, net_id = self.create_network() + + container = self.client.create_container('busybox', 'top') + self.tmp_containers.append(container) + self.client.start(container) + + network_data = self.client.inspect_network(net_id) + self.assertFalse(network_data.get('Containers')) + + self.client.connect_container_to_network(container, net_id) + network_data = self.client.inspect_network(net_id) + self.assertEqual( + list(network_data['Containers'].keys()), + [container['Id']] + ) + + self.client.disconnect_container_from_network(container, net_id, True) + network_data = self.client.inspect_network(net_id) + self.assertFalse(network_data.get('Containers')) + + with pytest.raises(docker.errors.APIError): + self.client.disconnect_container_from_network( + container, net_id, force=True + ) + @requires_api_version('1.22') def test_connect_with_aliases(self): net_name, net_id = self.create_network() @@ -300,7 +328,8 @@ class TestNetworks(helpers.BaseTestCase): net_name, net_id = self.create_network() with self.assertRaises(docker.errors.APIError): self.client.create_network(net_name, check_duplicate=True) - self.client.create_network(net_name, check_duplicate=False) + net_id = self.client.create_network(net_name, check_duplicate=False) + self.tmp_networks.append(net_id['Id']) @requires_api_version('1.22') def test_connect_with_links(self): @@ -387,3 +416,27 @@ class TestNetworks(helpers.BaseTestCase): _, net_id = self.create_network(internal=True) net = self.client.inspect_network(net_id) assert net['Internal'] is True + + @requires_api_version('1.23') + def test_create_network_with_labels(self): + _, net_id = self.create_network(labels={ + 'com.docker.py.test': 'label' + }) + + net = self.client.inspect_network(net_id) + assert 'Labels' in net + assert len(net['Labels']) == 1 + assert net['Labels'] == { + 'com.docker.py.test': 'label' + } + + @requires_api_version('1.23') + def test_create_network_with_labels_wrong_type(self): + with pytest.raises(TypeError): + self.create_network(labels=['com.docker.py.test=label', ]) + + @requires_api_version('1.23') + def test_create_network_ipv6_enabled(self): + _, net_id = self.create_network(enable_ipv6=True) + net = self.client.inspect_network(net_id) + assert net['EnableIPv6'] is True diff --git a/tests/unit/network_test.py b/tests/unit/network_test.py index 5bba9db2..2521688d 100644 --- a/tests/unit/network_test.py +++ b/tests/unit/network_test.py @@ -184,4 +184,4 @@ class NetworkTest(DockerClientTest): self.assertEqual( json.loads(post.call_args[1]['data']), - {'container': container_id}) + {'Container': container_id})
Support create network EnableIPv6 and Labels options Check the remote API: https://docs.docker.com/engine/reference/api/docker_remote_api_v1.23/#create-a-network There are two missing JSON parameters: ``` EnableIPv6 - Enable IPv6 on the network Labels - Labels to set on the network, specified as a map: {"key":"value" [,"key2":"value2"]} ```
0.0
24bfb99e05d57a7a098a81fb86ea7b93cff62661
[ "tests/unit/network_test.py::NetworkTest::test_disconnect_container_from_network" ]
[ "tests/unit/network_test.py::NetworkTest::test_connect_container_to_network", "tests/unit/network_test.py::NetworkTest::test_create_network", "tests/unit/network_test.py::NetworkTest::test_inspect_network", "tests/unit/network_test.py::NetworkTest::test_list_networks", "tests/unit/network_test.py::NetworkTest::test_remove_network" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-09-01 01:42:42+00:00
apache-2.0
1,962
docker__docker-py-1250
diff --git a/Dockerfile b/Dockerfile index 012a1259..993ac012 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,4 @@ FROM python:2.7 -MAINTAINER Joffrey F <[email protected]> RUN mkdir /home/docker-py WORKDIR /home/docker-py diff --git a/Dockerfile-py3 b/Dockerfile-py3 index 21e713bb..c7466517 100644 --- a/Dockerfile-py3 +++ b/Dockerfile-py3 @@ -1,5 +1,4 @@ FROM python:3.5 -MAINTAINER Joffrey F <[email protected]> RUN mkdir /home/docker-py WORKDIR /home/docker-py diff --git a/docker/api/image.py b/docker/api/image.py index 2c8cbb23..c1ebc69c 100644 --- a/docker/api/image.py +++ b/docker/api/image.py @@ -469,6 +469,11 @@ class ImageApiMixin(object): Raises: :py:class:`docker.errors.APIError` If the server returns an error. + + Example: + + >>> client.tag('ubuntu', 'localhost:5000/ubuntu', 'latest', + force=True) """ params = { 'tag': tag, diff --git a/docker/utils/socket.py b/docker/utils/socket.py index 164b845a..4080f253 100644 --- a/docker/utils/socket.py +++ b/docker/utils/socket.py @@ -69,7 +69,11 @@ def frames_iter(socket): """ Returns a generator of frames read from socket """ - n = next_frame_size(socket) - while n > 0: - yield read(socket, n) + while True: n = next_frame_size(socket) + if n == 0: + break + while n > 0: + result = read(socket, n) + n -= len(result) + yield result diff --git a/docker/utils/utils.py b/docker/utils/utils.py index b107f22e..823894c3 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -735,9 +735,9 @@ def create_host_config(binds=None, port_bindings=None, lxc_conf=None, host_config['ShmSize'] = shm_size - if pid_mode not in (None, 'host'): - raise host_config_value_error('pid_mode', pid_mode) - elif pid_mode: + if pid_mode: + if version_lt(version, '1.24') and pid_mode != 'host': + raise host_config_value_error('pid_mode', pid_mode) host_config['PidMode'] = pid_mode if ipc_mode: @@ -1052,7 +1052,11 @@ def parse_env_file(env_file): if line[0] == '#': continue - parse_line = line.strip().split('=', 1) + line = line.strip() + if not line: + continue + + parse_line = line.split('=', 1) if len(parse_line) == 2: k, v = parse_line environment[k] = v diff --git a/setup.py b/setup.py index edf4b0e5..3f2e3c4a 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +import codecs import os import sys @@ -35,7 +36,7 @@ with open('./test-requirements.txt') as test_reqs_txt: long_description = '' try: - with open('./README.rst') as readme_rst: + with codecs.open('./README.rst', encoding='utf-8') as readme_rst: long_description = readme_rst.read() except IOError: # README.rst is only generated on release. Its absence should not prevent
docker/docker-py
f36c28926cf9d0e3bfe0f2275c084d63cd3c6169
diff --git a/tests/integration/api_build_test.py b/tests/integration/api_build_test.py index 9ae74f4d..3dac0e93 100644 --- a/tests/integration/api_build_test.py +++ b/tests/integration/api_build_test.py @@ -15,7 +15,6 @@ class BuildTest(BaseAPIIntegrationTest): def test_build_streaming(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -32,7 +31,6 @@ class BuildTest(BaseAPIIntegrationTest): return script = io.StringIO(six.text_type('\n').join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -54,7 +52,6 @@ class BuildTest(BaseAPIIntegrationTest): with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("\n".join([ 'FROM busybox', - 'MAINTAINER docker-py', 'ADD . /test', ])) @@ -182,7 +179,6 @@ class BuildTest(BaseAPIIntegrationTest): with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("\n".join([ 'FROM busybox', - 'MAINTAINER docker-py', 'ADD . /test', ])) diff --git a/tests/integration/api_container_test.py b/tests/integration/api_container_test.py index a5be6e76..f09e75ad 100644 --- a/tests/integration/api_container_test.py +++ b/tests/integration/api_container_test.py @@ -361,13 +361,6 @@ class CreateContainerTest(BaseAPIIntegrationTest): host_config = inspect['HostConfig'] self.assertIn('MemorySwappiness', host_config) - def test_create_host_config_exception_raising(self): - self.assertRaises(TypeError, - self.client.create_host_config, mem_swappiness='40') - - self.assertRaises(ValueError, - self.client.create_host_config, pid_mode='40') - def test_create_with_environment_variable_no_value(self): container = self.client.create_container( BUSYBOX, diff --git a/tests/unit/api_build_test.py b/tests/unit/api_build_test.py index 8146fee7..927aa974 100644 --- a/tests/unit/api_build_test.py +++ b/tests/unit/api_build_test.py @@ -11,7 +11,6 @@ class BuildTest(BaseAPIClientTest): def test_build_container(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -23,7 +22,6 @@ class BuildTest(BaseAPIClientTest): def test_build_container_pull(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -35,7 +33,6 @@ class BuildTest(BaseAPIClientTest): def test_build_container_stream(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -47,7 +44,6 @@ class BuildTest(BaseAPIClientTest): def test_build_container_custom_context(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' @@ -60,7 +56,6 @@ class BuildTest(BaseAPIClientTest): def test_build_container_custom_context_gzip(self): script = io.BytesIO('\n'.join([ 'FROM busybox', - 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 57aa226d..19d52c9f 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -205,6 +205,19 @@ class HostConfigTest(unittest.TestCase): version='1.24', isolation={'isolation': 'hyperv'} ) + def test_create_host_config_pid_mode(self): + with pytest.raises(ValueError): + create_host_config(version='1.23', pid_mode='baccab125') + + config = create_host_config(version='1.23', pid_mode='host') + assert config.get('PidMode') == 'host' + config = create_host_config(version='1.24', pid_mode='baccab125') + assert config.get('PidMode') == 'baccab125' + + def test_create_host_config_invalid_mem_swappiness(self): + with pytest.raises(TypeError): + create_host_config(version='1.24', mem_swappiness='40') + class UlimitTest(unittest.TestCase): def test_create_host_config_dict_ulimit(self): @@ -465,10 +478,18 @@ class ParseEnvFileTest(unittest.TestCase): def test_parse_env_file_commented_line(self): env_file = self.generate_tempfile( file_content='USER=jdoe\n#PASS=secret') - get_parse_env_file = parse_env_file((env_file)) + get_parse_env_file = parse_env_file(env_file) self.assertEqual(get_parse_env_file, {'USER': 'jdoe'}) os.unlink(env_file) + def test_parse_env_file_newline(self): + env_file = self.generate_tempfile( + file_content='\nUSER=jdoe\n\n\nPASS=secret') + get_parse_env_file = parse_env_file(env_file) + self.assertEqual(get_parse_env_file, + {'USER': 'jdoe', 'PASS': 'secret'}) + os.unlink(env_file) + def test_parse_env_file_invalid_line(self): env_file = self.generate_tempfile( file_content='USER jdoe')
attach is causing an "Invalid Argument" exception from os.read ``` python stream = client.attach(container, stream=True, stdout=True, stderr=True) for chunk in stream: pass ``` Results in: ``` File "/Users/michael/work/oss/marina/marina/build.py", line 695, in watcher for chunk in stream: File ".venv/lib/python3.5/site-packages/docker/utils/socket.py", line 67, in frames_iter yield read(socket, n) File ".venv/lib/python3.5/site-packages/docker/utils/socket.py", line 25, in read return os.read(socket.fileno(), n) OSError: [Errno 22] Invalid argument ``` Using docker-py 1.10.2 on OS X 10.11.6 with docker for mac 1.12.0-rc3. Reverting to 1.9.0 fixes the issue.
0.0
f36c28926cf9d0e3bfe0f2275c084d63cd3c6169
[ "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_pid_mode", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_newline" ]
[ "tests/unit/api_build_test.py::BuildTest::test_build_container", "tests/unit/api_build_test.py::BuildTest::test_build_container_custom_context", "tests/unit/api_build_test.py::BuildTest::test_build_container_custom_context_gzip", "tests/unit/api_build_test.py::BuildTest::test_build_container_invalid_container_limits", "tests/unit/api_build_test.py::BuildTest::test_build_container_pull", "tests/unit/api_build_test.py::BuildTest::test_build_container_stream", "tests/unit/api_build_test.py::BuildTest::test_build_container_with_container_limits", "tests/unit/api_build_test.py::BuildTest::test_build_container_with_named_dockerfile", "tests/unit/api_build_test.py::BuildTest::test_build_remote_with_registry_auth", "tests/unit/api_build_test.py::BuildTest::test_set_auth_headers_with_dict_and_auth_configs", "tests/unit/api_build_test.py::BuildTest::test_set_auth_headers_with_dict_and_no_auth_configs", "tests/unit/api_build_test.py::BuildTest::test_set_auth_headers_with_empty_dict_and_auth_configs", "tests/unit/utils_test.py::DecoratorsTest::test_update_headers", "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_mem_swappiness", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_dns_opt", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_isolation", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_kernel_memory", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_mem_reservation", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_pids_limit", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_userns_mode", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_trailing_slash", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks", "tests/unit/utils_test.py::FormatEnvironmentTest::test_format_env_binary_unicode_value", "tests/unit/utils_test.py::FormatEnvironmentTest::test_format_env_no_value" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-10-11 07:42:57+00:00
apache-2.0
1,963
docker__docker-py-1255
diff --git a/docker/api/image.py b/docker/api/image.py index 7f25f9d9..262910cd 100644 --- a/docker/api/image.py +++ b/docker/api/image.py @@ -88,9 +88,6 @@ class ImageApiMixin(object): u, data=data, params=params, headers=headers, timeout=None ) ) - return self.import_image( - src=data, repository=repository, tag=tag, changes=changes - ) def import_image_from_file(self, filename, repository=None, tag=None, changes=None): diff --git a/docker/utils/utils.py b/docker/utils/utils.py index b565732d..e1c7ad0c 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -453,8 +453,8 @@ def parse_host(addr, is_win32=False, tls=False): "Bind address needs a port: {0}".format(addr)) if proto == "http+unix" or proto == 'npipe': - return "{0}://{1}".format(proto, host) - return "{0}://{1}:{2}{3}".format(proto, host, port, path) + return "{0}://{1}".format(proto, host).rstrip('/') + return "{0}://{1}:{2}{3}".format(proto, host, port, path).rstrip('/') def parse_devices(devices):
docker/docker-py
008730c670afb2f88c7db308901586fb24f1a60c
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 2a2759d0..059c82d3 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -522,6 +522,11 @@ class ParseHostTest(base.BaseTestCase): expected_result = 'https://myhost.docker.net:3348' assert parse_host(host_value, tls=True) == expected_result + def test_parse_host_trailing_slash(self): + host_value = 'tcp://myhost.docker.net:2376/' + expected_result = 'http://myhost.docker.net:2376' + assert parse_host(host_value) == expected_result + class ParseRepositoryTagTest(base.BaseTestCase): sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
Client should tolerate trailing slashes in base_url docker/compose#3869
0.0
008730c670afb2f88c7db308901586fb24f1a60c
[ "tests/unit/utils_test.py::ParseHostTest::test_parse_host_trailing_slash" ]
[ "tests/unit/utils_test.py::DecoratorsTest::test_update_headers", "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_dns_opt", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_kernel_memory", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_mem_reservation", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_pids_limit", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_userns_mode", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-10-12 23:07:38+00:00
apache-2.0
1,964
docker__docker-py-1385
diff --git a/docker/types/services.py b/docker/types/services.py index b52afd27..93503dc0 100644 --- a/docker/types/services.py +++ b/docker/types/services.py @@ -1,6 +1,7 @@ import six from .. import errors +from ..constants import IS_WINDOWS_PLATFORM from ..utils import format_environment, split_command @@ -175,8 +176,17 @@ class Mount(dict): else: target = parts[1] source = parts[0] + mount_type = 'volume' + if source.startswith('/') or ( + IS_WINDOWS_PLATFORM and source[0].isalpha() and + source[1] == ':' + ): + # FIXME: That windows condition will fail earlier since we + # split on ':'. We should look into doing a smarter split + # if we detect we are on Windows. + mount_type = 'bind' read_only = not (len(parts) == 2 or parts[2] == 'rw') - return cls(target, source, read_only=read_only) + return cls(target, source, read_only=read_only, type=mount_type) class Resources(dict):
docker/docker-py
07b20ce660f4a4b1e64ef3ede346eef9ec08635a
diff --git a/tests/unit/dockertypes_test.py b/tests/unit/dockertypes_test.py index 5cf5f4e7..d11e4f03 100644 --- a/tests/unit/dockertypes_test.py +++ b/tests/unit/dockertypes_test.py @@ -10,6 +10,11 @@ from docker.types import ( EndpointConfig, HostConfig, IPAMConfig, IPAMPool, LogConfig, Mount, Ulimit, ) +try: + from unittest import mock +except: + import mock + def create_host_config(*args, **kwargs): return HostConfig(*args, **kwargs) @@ -258,28 +263,48 @@ class IPAMConfigTest(unittest.TestCase): class TestMounts(unittest.TestCase): def test_parse_mount_string_ro(self): mount = Mount.parse_mount_string("/foo/bar:/baz:ro") - self.assertEqual(mount['Source'], "/foo/bar") - self.assertEqual(mount['Target'], "/baz") - self.assertEqual(mount['ReadOnly'], True) + assert mount['Source'] == "/foo/bar" + assert mount['Target'] == "/baz" + assert mount['ReadOnly'] is True def test_parse_mount_string_rw(self): mount = Mount.parse_mount_string("/foo/bar:/baz:rw") - self.assertEqual(mount['Source'], "/foo/bar") - self.assertEqual(mount['Target'], "/baz") - self.assertEqual(mount['ReadOnly'], False) + assert mount['Source'] == "/foo/bar" + assert mount['Target'] == "/baz" + assert not mount['ReadOnly'] def test_parse_mount_string_short_form(self): mount = Mount.parse_mount_string("/foo/bar:/baz") - self.assertEqual(mount['Source'], "/foo/bar") - self.assertEqual(mount['Target'], "/baz") - self.assertEqual(mount['ReadOnly'], False) + assert mount['Source'] == "/foo/bar" + assert mount['Target'] == "/baz" + assert not mount['ReadOnly'] def test_parse_mount_string_no_source(self): mount = Mount.parse_mount_string("foo/bar") - self.assertEqual(mount['Source'], None) - self.assertEqual(mount['Target'], "foo/bar") - self.assertEqual(mount['ReadOnly'], False) + assert mount['Source'] is None + assert mount['Target'] == "foo/bar" + assert not mount['ReadOnly'] def test_parse_mount_string_invalid(self): with pytest.raises(InvalidArgument): Mount.parse_mount_string("foo:bar:baz:rw") + + def test_parse_mount_named_volume(self): + mount = Mount.parse_mount_string("foobar:/baz") + assert mount['Source'] == 'foobar' + assert mount['Target'] == '/baz' + assert mount['Type'] == 'volume' + + def test_parse_mount_bind(self): + mount = Mount.parse_mount_string('/foo/bar:/baz') + assert mount['Source'] == "/foo/bar" + assert mount['Target'] == "/baz" + assert mount['Type'] == 'bind' + + @pytest.mark.xfail + def test_parse_mount_bind_windows(self): + with mock.patch('docker.types.services.IS_WINDOWS_PLATFORM', True): + mount = Mount.parse_mount_string('C:/foo/bar:/baz') + assert mount['Source'] == "C:/foo/bar" + assert mount['Target'] == "/baz" + assert mount['Type'] == 'bind'
swarm mode create service does not support volumn bind type? hi all, i use docker py create service catch some error. my docker py version is ``` root@node-19:~# pip freeze | grep docker docker==2.0.0 docker-compose==1.9.0 docker-pycreds==0.2.1 dockerpty==0.4.1 ``` my docker version is ``` Client: Version: 1.12.5 API version: 1.24 Go version: go1.6.4 Git commit: 7392c3b Built: Fri Dec 16 02:30:42 2016 OS/Arch: linux/amd64 Server: Version: 1.12.5 API version: 1.24 Go version: go1.6.4 Git commit: 7392c3b Built: Fri Dec 16 02:30:42 2016 OS/Arch: linux/amd64 ``` my use docker py create service code is ```python import docker client = docker.DockerClient(base_url='unix://var/run/docker.sock') client.services.create(name="bab", command=["sleep", "30000"], image="busybox", mounts=["/data:/data:rw"]) ``` look my create service code i just wand to create service and volumn local host dir to container, and dir path is absolute path. but i got some error like this ` invalid volume mount source, must not be an absolute path: /data` so i check docker py code find this ```python def __init__(self, target, source, type='volume', read_only=False, propagation=None, no_copy=False, labels=None, driver_config=None): self['Target'] = target self['Source'] = source if type not in ('bind', 'volume'): raise errors.DockerError( 'Only acceptable mount types are `bind` and `volume`.' ) self['Type'] = type ``` so i want to know what can i create service with volumn bind type . i need help.
0.0
07b20ce660f4a4b1e64ef3ede346eef9ec08635a
[ "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_bind" ]
[ "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_invalid_mem_swappiness", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_pid_mode", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_dns_opt", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_isolation", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_kernel_memory", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_mem_reservation", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_pids_limit", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_userns_mode", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/dockertypes_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/dockertypes_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/dockertypes_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/dockertypes_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/dockertypes_test.py::EndpointConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/dockertypes_test.py::IPAMConfigTest::test_create_ipam_config", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_named_volume", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_string_invalid", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_string_no_source", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_string_ro", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_string_rw", "tests/unit/dockertypes_test.py::TestMounts::test_parse_mount_string_short_form" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-01-09 23:14:24+00:00
apache-2.0
1,965
docker__docker-py-1390
diff --git a/docker/api/service.py b/docker/api/service.py index 0d8421ec..d2621e68 100644 --- a/docker/api/service.py +++ b/docker/api/service.py @@ -1,5 +1,6 @@ import warnings from .. import auth, errors, utils +from ..types import ServiceMode class ServiceApiMixin(object): @@ -18,8 +19,8 @@ class ServiceApiMixin(object): name (string): User-defined name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. - mode (string): Scheduling mode for the service (``replicated`` or - ``global``). Defaults to ``replicated``. + mode (ServiceMode): Scheduling mode for the service (replicated + or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None`` networks (:py:class:`list`): List of network names or IDs to attach @@ -49,6 +50,9 @@ class ServiceApiMixin(object): raise errors.DockerException( 'Missing mandatory Image key in ContainerSpec' ) + if mode and not isinstance(mode, dict): + mode = ServiceMode(mode) + registry, repo_name = auth.resolve_repository_name(image) auth_header = auth.get_config_header(self, registry) if auth_header: @@ -191,8 +195,8 @@ class ServiceApiMixin(object): name (string): New name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. - mode (string): Scheduling mode for the service (``replicated`` or - ``global``). Defaults to ``replicated``. + mode (ServiceMode): Scheduling mode for the service (replicated + or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None``. networks (:py:class:`list`): List of network names or IDs to attach @@ -222,6 +226,8 @@ class ServiceApiMixin(object): if labels is not None: data['Labels'] = labels if mode is not None: + if not isinstance(mode, dict): + mode = ServiceMode(mode) data['Mode'] = mode if task_template is not None: image = task_template.get('ContainerSpec', {}).get('Image', None) diff --git a/docker/types/__init__.py b/docker/types/__init__.py index 7230723e..8e2fc174 100644 --- a/docker/types/__init__.py +++ b/docker/types/__init__.py @@ -4,6 +4,6 @@ from .healthcheck import Healthcheck from .networks import EndpointConfig, IPAMConfig, IPAMPool, NetworkingConfig from .services import ( ContainerSpec, DriverConfig, EndpointSpec, Mount, Resources, RestartPolicy, - TaskTemplate, UpdateConfig + ServiceMode, TaskTemplate, UpdateConfig ) from .swarm import SwarmSpec, SwarmExternalCA diff --git a/docker/types/services.py b/docker/types/services.py index 6e1ad321..ec0fcb15 100644 --- a/docker/types/services.py +++ b/docker/types/services.py @@ -348,3 +348,38 @@ def convert_service_ports(ports): result.append(port_spec) return result + + +class ServiceMode(dict): + """ + Indicate whether a service should be deployed as a replicated or global + service, and associated parameters + + Args: + mode (string): Can be either ``replicated`` or ``global`` + replicas (int): Number of replicas. For replicated services only. + """ + def __init__(self, mode, replicas=None): + if mode not in ('replicated', 'global'): + raise errors.InvalidArgument( + 'mode must be either "replicated" or "global"' + ) + if mode != 'replicated' and replicas is not None: + raise errors.InvalidArgument( + 'replicas can only be used for replicated mode' + ) + self[mode] = {} + if replicas: + self[mode]['Replicas'] = replicas + + @property + def mode(self): + if 'global' in self: + return 'global' + return 'replicated' + + @property + def replicas(self): + if self.mode != 'replicated': + return None + return self['replicated'].get('Replicas') diff --git a/docs/api.rst b/docs/api.rst index 110b0a7f..b5c1e929 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -110,5 +110,6 @@ Configuration types .. autoclass:: Mount .. autoclass:: Resources .. autoclass:: RestartPolicy +.. autoclass:: ServiceMode .. autoclass:: TaskTemplate .. autoclass:: UpdateConfig
docker/docker-py
5f0b469a09421b0d6140661de9466af74ac3e9ec
diff --git a/tests/integration/api_service_test.py b/tests/integration/api_service_test.py index fc794002..77d7d28f 100644 --- a/tests/integration/api_service_test.py +++ b/tests/integration/api_service_test.py @@ -251,3 +251,31 @@ class ServiceTest(BaseAPIIntegrationTest): con_spec = svc_info['Spec']['TaskTemplate']['ContainerSpec'] assert 'Env' in con_spec assert con_spec['Env'] == ['DOCKER_PY_TEST=1'] + + def test_create_service_global_mode(self): + container_spec = docker.types.ContainerSpec( + 'busybox', ['echo', 'hello'] + ) + task_tmpl = docker.types.TaskTemplate(container_spec) + name = self.get_service_name() + svc_id = self.client.create_service( + task_tmpl, name=name, mode='global' + ) + svc_info = self.client.inspect_service(svc_id) + assert 'Mode' in svc_info['Spec'] + assert 'Global' in svc_info['Spec']['Mode'] + + def test_create_service_replicated_mode(self): + container_spec = docker.types.ContainerSpec( + 'busybox', ['echo', 'hello'] + ) + task_tmpl = docker.types.TaskTemplate(container_spec) + name = self.get_service_name() + svc_id = self.client.create_service( + task_tmpl, name=name, + mode=docker.types.ServiceMode('replicated', 5) + ) + svc_info = self.client.inspect_service(svc_id) + assert 'Mode' in svc_info['Spec'] + assert 'Replicated' in svc_info['Spec']['Mode'] + assert svc_info['Spec']['Mode']['Replicated'] == {'Replicas': 5} diff --git a/tests/unit/dockertypes_test.py b/tests/unit/dockertypes_test.py index d11e4f03..5c470ffa 100644 --- a/tests/unit/dockertypes_test.py +++ b/tests/unit/dockertypes_test.py @@ -7,7 +7,8 @@ import pytest from docker.constants import DEFAULT_DOCKER_API_VERSION from docker.errors import InvalidArgument, InvalidVersion from docker.types import ( - EndpointConfig, HostConfig, IPAMConfig, IPAMPool, LogConfig, Mount, Ulimit, + EndpointConfig, HostConfig, IPAMConfig, IPAMPool, LogConfig, Mount, + ServiceMode, Ulimit, ) try: @@ -260,7 +261,35 @@ class IPAMConfigTest(unittest.TestCase): }) -class TestMounts(unittest.TestCase): +class ServiceModeTest(unittest.TestCase): + def test_replicated_simple(self): + mode = ServiceMode('replicated') + assert mode == {'replicated': {}} + assert mode.mode == 'replicated' + assert mode.replicas is None + + def test_global_simple(self): + mode = ServiceMode('global') + assert mode == {'global': {}} + assert mode.mode == 'global' + assert mode.replicas is None + + def test_global_replicas_error(self): + with pytest.raises(InvalidArgument): + ServiceMode('global', 21) + + def test_replicated_replicas(self): + mode = ServiceMode('replicated', 21) + assert mode == {'replicated': {'Replicas': 21}} + assert mode.mode == 'replicated' + assert mode.replicas == 21 + + def test_invalid_mode(self): + with pytest.raises(InvalidArgument): + ServiceMode('foobar') + + +class MountTest(unittest.TestCase): def test_parse_mount_string_ro(self): mount = Mount.parse_mount_string("/foo/bar:/baz:ro") assert mount['Source'] == "/foo/bar"
Unable to create Service in `global` mode Attempting to create a service with `mode="global"` returns an error from the Docker API: ``` cannot unmarshal string into Go value of type swarm.ServiceMode ```
0.0
5f0b469a09421b0d6140661de9466af74ac3e9ec
[ "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_invalid_mem_swappiness", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_pid_mode", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_blkio_constraints", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_dns_opt", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_isolation", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_kernel_memory", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_mem_reservation", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_pids_limit", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/dockertypes_test.py::HostConfigTest::test_create_host_config_with_userns_mode", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/dockertypes_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/dockertypes_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/dockertypes_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/dockertypes_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/dockertypes_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/dockertypes_test.py::EndpointConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/dockertypes_test.py::IPAMConfigTest::test_create_ipam_config", "tests/unit/dockertypes_test.py::ServiceModeTest::test_global_replicas_error", "tests/unit/dockertypes_test.py::ServiceModeTest::test_global_simple", "tests/unit/dockertypes_test.py::ServiceModeTest::test_invalid_mode", "tests/unit/dockertypes_test.py::ServiceModeTest::test_replicated_replicas", "tests/unit/dockertypes_test.py::ServiceModeTest::test_replicated_simple", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_bind", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_named_volume", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_string_invalid", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_string_no_source", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_string_ro", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_string_rw", "tests/unit/dockertypes_test.py::MountTest::test_parse_mount_string_short_form" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-01-12 02:32:06+00:00
apache-2.0
1,966
docker__docker-py-1393
diff --git a/docker/api/client.py b/docker/api/client.py index a9fe7d08..22c32b44 100644 --- a/docker/api/client.py +++ b/docker/api/client.py @@ -18,16 +18,20 @@ from .service import ServiceApiMixin from .swarm import SwarmApiMixin from .volume import VolumeApiMixin from .. import auth -from ..constants import (DEFAULT_TIMEOUT_SECONDS, DEFAULT_USER_AGENT, - IS_WINDOWS_PLATFORM, DEFAULT_DOCKER_API_VERSION, - STREAM_HEADER_SIZE_BYTES, DEFAULT_NUM_POOLS, - MINIMUM_DOCKER_API_VERSION) -from ..errors import (DockerException, TLSParameterError, - create_api_error_from_http_exception) +from ..constants import ( + DEFAULT_TIMEOUT_SECONDS, DEFAULT_USER_AGENT, IS_WINDOWS_PLATFORM, + DEFAULT_DOCKER_API_VERSION, STREAM_HEADER_SIZE_BYTES, DEFAULT_NUM_POOLS, + MINIMUM_DOCKER_API_VERSION +) +from ..errors import ( + DockerException, TLSParameterError, + create_api_error_from_http_exception +) from ..tls import TLSConfig from ..transport import SSLAdapter, UnixAdapter from ..utils import utils, check_resource, update_headers from ..utils.socket import frames_iter +from ..utils.json_stream import json_stream try: from ..transport import NpipeAdapter except ImportError: @@ -274,27 +278,20 @@ class APIClient( def _stream_helper(self, response, decode=False): """Generator for data coming from a chunked-encoded HTTP response.""" + if response.raw._fp.chunked: - reader = response.raw - while not reader.closed: - # this read call will block until we get a chunk - data = reader.read(1) - if not data: - break - if reader._fp.chunk_left: - data += reader.read(reader._fp.chunk_left) - if decode: - if six.PY3: - data = data.decode('utf-8') - # remove the trailing newline - data = data.strip() - # split the data at any newlines - data_list = data.split("\r\n") - # load and yield each line seperately - for data in data_list: - data = json.loads(data) - yield data - else: + if decode: + for chunk in json_stream(self._stream_helper(response, False)): + yield chunk + else: + reader = response.raw + while not reader.closed: + # this read call will block until we get a chunk + data = reader.read(1) + if not data: + break + if reader._fp.chunk_left: + data += reader.read(reader._fp.chunk_left) yield data else: # Response isn't chunked, meaning we probably diff --git a/docker/models/images.py b/docker/models/images.py index 32068e69..6f8f4fe2 100644 --- a/docker/models/images.py +++ b/docker/models/images.py @@ -30,10 +30,10 @@ class Image(Model): """ The image's tags. """ - return [ - tag for tag in self.attrs.get('RepoTags', []) - if tag != '<none>:<none>' - ] + tags = self.attrs.get('RepoTags') + if tags is None: + tags = [] + return [tag for tag in tags if tag != '<none>:<none>'] def history(self): """ diff --git a/docker/models/resource.py b/docker/models/resource.py index 95712aef..ed3900af 100644 --- a/docker/models/resource.py +++ b/docker/models/resource.py @@ -23,6 +23,9 @@ class Model(object): def __eq__(self, other): return isinstance(other, self.__class__) and self.id == other.id + def __hash__(self): + return hash("%s:%s" % (self.__class__.__name__, self.id)) + @property def id(self): """
docker/docker-py
aed1af6f6f8c97658ad8d11619ba0e7fce7af240
diff --git a/tests/unit/models_images_test.py b/tests/unit/models_images_test.py index 392c58d7..efb21166 100644 --- a/tests/unit/models_images_test.py +++ b/tests/unit/models_images_test.py @@ -83,6 +83,11 @@ class ImageTest(unittest.TestCase): }) assert image.tags == [] + image = Image(attrs={ + 'RepoTags': None + }) + assert image.tags == [] + def test_history(self): client = make_fake_client() image = client.images.get(FAKE_IMAGE_ID) diff --git a/tests/unit/models_resources_test.py b/tests/unit/models_resources_test.py index 25c6a3ed..5af24ee6 100644 --- a/tests/unit/models_resources_test.py +++ b/tests/unit/models_resources_test.py @@ -12,3 +12,17 @@ class ModelTest(unittest.TestCase): container.reload() assert client.api.inspect_container.call_count == 2 assert container.attrs['Name'] == "foobar" + + def test_hash(self): + client = make_fake_client() + container1 = client.containers.get(FAKE_CONTAINER_ID) + my_set = set([container1]) + assert len(my_set) == 1 + + container2 = client.containers.get(FAKE_CONTAINER_ID) + my_set.add(container2) + assert len(my_set) == 1 + + image1 = client.images.get(FAKE_CONTAINER_ID) + my_set.add(image1) + assert len(my_set) == 2
Exception retrieving untagged images on api >= 1.24 Docker API >= 1.24 will return a null object if image tags DNE instead of not including it in the response. This makes the dict.get fail to catch the null case and the list comprehension to iterate over a non-iterable. ``` File "<stdin>", line 1, in <module> File "docker/models/images.py", line 16, in __repr__ return "<%s: '%s'>" % (self.__class__.__name__, "', '".join(self.tags)) File "docker/models/images.py", line 34, in tags tag for tag in self.attrs.get('RepoTags', []) TypeError: 'NoneType' object is not iterable ``` This is similar to an issue seen in [salt](https://github.com/saltstack/salt/pull/35447/commits/b833b5f9587534d3b843a026ef91abc4ec929d0f) Was able to get things working with a pretty quick change: ``` diff --git a/docker/models/images.py b/docker/models/images.py index 32068e6..39a640d 100644 --- a/docker/models/images.py +++ b/docker/models/images.py @@ -30,9 +30,11 @@ class Image(Model): """ The image's tags. """ + tags = self.attrs.get('RepoTags', []) + if tags is None: + return [] return [ - tag for tag in self.attrs.get('RepoTags', []) - if tag != '<none>:<none>' + tag for tag in tags if tag != '<none>:<none>' ] def history(self): ```
0.0
aed1af6f6f8c97658ad8d11619ba0e7fce7af240
[ "tests/unit/models_images_test.py::ImageTest::test_tags", "tests/unit/models_resources_test.py::ModelTest::test_hash" ]
[ "tests/unit/models_images_test.py::ImageCollectionTest::test_build", "tests/unit/models_images_test.py::ImageCollectionTest::test_get", "tests/unit/models_images_test.py::ImageCollectionTest::test_list", "tests/unit/models_images_test.py::ImageCollectionTest::test_load", "tests/unit/models_images_test.py::ImageCollectionTest::test_pull", "tests/unit/models_images_test.py::ImageCollectionTest::test_push", "tests/unit/models_images_test.py::ImageCollectionTest::test_remove", "tests/unit/models_images_test.py::ImageCollectionTest::test_search", "tests/unit/models_images_test.py::ImageTest::test_history", "tests/unit/models_images_test.py::ImageTest::test_save", "tests/unit/models_images_test.py::ImageTest::test_short_id", "tests/unit/models_images_test.py::ImageTest::test_tag", "tests/unit/models_resources_test.py::ModelTest::test_reload" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-01-16 07:57:41+00:00
apache-2.0
1,967
docker__docker-py-1399
diff --git a/docker/models/images.py b/docker/models/images.py index 32068e69..6f8f4fe2 100644 --- a/docker/models/images.py +++ b/docker/models/images.py @@ -30,10 +30,10 @@ class Image(Model): """ The image's tags. """ - return [ - tag for tag in self.attrs.get('RepoTags', []) - if tag != '<none>:<none>' - ] + tags = self.attrs.get('RepoTags') + if tags is None: + tags = [] + return [tag for tag in tags if tag != '<none>:<none>'] def history(self): """ diff --git a/setup.py b/setup.py index b82a74f7..9fc4ad66 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,20 @@ #!/usr/bin/env python +from __future__ import print_function + import codecs import os import sys +import pip + from setuptools import setup, find_packages +if 'docker-py' in [x.project_name for x in pip.get_installed_distributions()]: + print( + 'ERROR: "docker-py" needs to be uninstalled before installing this' + ' package:\npip uninstall docker-py', file=sys.stderr + ) + sys.exit(1) ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR)
docker/docker-py
7db5f7ebcc615db903e3007c05495a82bb319810
diff --git a/tests/unit/models_images_test.py b/tests/unit/models_images_test.py index 392c58d7..efb21166 100644 --- a/tests/unit/models_images_test.py +++ b/tests/unit/models_images_test.py @@ -83,6 +83,11 @@ class ImageTest(unittest.TestCase): }) assert image.tags == [] + image = Image(attrs={ + 'RepoTags': None + }) + assert image.tags == [] + def test_history(self): client = make_fake_client() image = client.images.get(FAKE_IMAGE_ID)
docker-py installation breaks docker-compose im not quite sure if this is correct, but trying to install `docker-py` through pip after i've installed `docker-compose` breaks `docker-compose` with ``` Traceback (most recent call last): File "/usr/local/bin/docker-compose", line 7, in <module> from compose.cli.main import main File "/usr/local/lib/python2.7/site-packages/compose/cli/main.py", line 20, in <module> from ..bundle import get_image_digests File "/usr/local/lib/python2.7/site-packages/compose/bundle.py", line 13, in <module> from .network import get_network_defs_for_service File "/usr/local/lib/python2.7/site-packages/compose/network.py", line 7, in <module> from docker.types import IPAMConfig ImportError: cannot import name IPAMConfig ``` To fix that error, i just need to do the installations in this order: ``` pip install docker-py pip install docker-compose ``` gist: https://gist.github.com/serialdoom/3a443c420aa29f9422f8c5fc73f46602 python/pip versions tried: ``` docker run -it python:2.7.13 bash -c 'pip --version' pip 9.0.1 from /usr/local/lib/python2.7/site-packages (python 2.7) docker run -it python:2.7.12 bash -c 'pip --version' pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7) ```
0.0
7db5f7ebcc615db903e3007c05495a82bb319810
[ "tests/unit/models_images_test.py::ImageTest::test_tags" ]
[ "tests/unit/models_images_test.py::ImageCollectionTest::test_build", "tests/unit/models_images_test.py::ImageCollectionTest::test_get", "tests/unit/models_images_test.py::ImageCollectionTest::test_list", "tests/unit/models_images_test.py::ImageCollectionTest::test_load", "tests/unit/models_images_test.py::ImageCollectionTest::test_pull", "tests/unit/models_images_test.py::ImageCollectionTest::test_push", "tests/unit/models_images_test.py::ImageCollectionTest::test_remove", "tests/unit/models_images_test.py::ImageCollectionTest::test_search", "tests/unit/models_images_test.py::ImageTest::test_history", "tests/unit/models_images_test.py::ImageTest::test_save", "tests/unit/models_images_test.py::ImageTest::test_short_id", "tests/unit/models_images_test.py::ImageTest::test_tag" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-01-19 00:38:50+00:00
apache-2.0
1,968
docker__docker-py-1710
diff --git a/README.md b/README.md index 747b98b2..3ff124d7 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ The latest stable version [is available on PyPI](https://pypi.python.org/pypi/do pip install docker +If you are intending to connect to a docker host via TLS, add `docker[tls]` to your requirements instead, or install with pip: + + pip install docker[tls] + ## Usage Connect to Docker using the default socket or the configuration in your environment: diff --git a/appveyor.yml b/appveyor.yml index 1fc67cc0..41cde625 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,7 +3,7 @@ version: '{branch}-{build}' install: - "SET PATH=C:\\Python27-x64;C:\\Python27-x64\\Scripts;%PATH%" - "python --version" - - "pip install tox==2.1.1 virtualenv==13.1.2" + - "pip install tox==2.7.0 virtualenv==15.1.0" # Build the binary after tests build: false diff --git a/docker/api/build.py b/docker/api/build.py index cbef4a8b..5d4e7720 100644 --- a/docker/api/build.py +++ b/docker/api/build.py @@ -274,7 +274,10 @@ class BuildApiMixin(object): self._auth_configs, registry ) else: - auth_data = self._auth_configs + auth_data = self._auth_configs.copy() + # See https://github.com/docker/docker-py/issues/1683 + if auth.INDEX_NAME in auth_data: + auth_data[auth.INDEX_URL] = auth_data[auth.INDEX_NAME] log.debug( 'Sending auth config ({0})'.format( diff --git a/docker/auth.py b/docker/auth.py index ec9c45b9..c3fb062e 100644 --- a/docker/auth.py +++ b/docker/auth.py @@ -10,7 +10,7 @@ from . import errors from .constants import IS_WINDOWS_PLATFORM INDEX_NAME = 'docker.io' -INDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME) +INDEX_URL = 'https://index.{0}/v1/'.format(INDEX_NAME) DOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json') LEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg' TOKEN_USERNAME = '<token>' @@ -118,7 +118,7 @@ def _resolve_authconfig_credstore(authconfig, registry, credstore_name): if not registry or registry == INDEX_NAME: # The ecosystem is a little schizophrenic with index.docker.io VS # docker.io - in that case, it seems the full URL is necessary. - registry = 'https://index.docker.io/v1/' + registry = INDEX_URL log.debug("Looking for auth entry for {0}".format(repr(registry))) store = dockerpycreds.Store(credstore_name) try: diff --git a/docker/utils/build.py b/docker/utils/build.py index 79b72495..d4223e74 100644 --- a/docker/utils/build.py +++ b/docker/utils/build.py @@ -26,6 +26,7 @@ def exclude_paths(root, patterns, dockerfile=None): if dockerfile is None: dockerfile = 'Dockerfile' + patterns = [p.lstrip('/') for p in patterns] exceptions = [p for p in patterns if p.startswith('!')] include_patterns = [p[1:] for p in exceptions] diff --git a/requirements.txt b/requirements.txt index 37541312..f3c61e79 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,16 @@ -requests==2.11.1 -six>=1.4.0 -websocket-client==0.32.0 -backports.ssl_match_hostname>=3.5 ; python_version < '3.5' -ipaddress==1.0.16 ; python_version < '3.3' +appdirs==1.4.3 +asn1crypto==0.22.0 +backports.ssl-match-hostname==3.5.0.1 +cffi==1.10.0 +cryptography==1.9 docker-pycreds==0.2.1 +enum34==1.1.6 +idna==2.5 +ipaddress==1.0.18 +packaging==16.8 +pycparser==2.17 +pyOpenSSL==17.0.0 +pyparsing==2.2.0 +requests==2.14.2 +six==1.10.0 +websocket-client==0.40.0 diff --git a/setup.py b/setup.py index 31180d23..4a33c8df 100644 --- a/setup.py +++ b/setup.py @@ -35,6 +35,16 @@ extras_require = { # ssl_match_hostname to verify hosts match with certificates via # ServerAltname: https://pypi.python.org/pypi/backports.ssl_match_hostname ':python_version < "3.3"': 'ipaddress >= 1.0.16', + + # If using docker-py over TLS, highly recommend this option is + # pip-installed or pinned. + + # TODO: if pip installing both "requests" and "requests[security]", the + # extra package from the "security" option are not installed (see + # https://github.com/pypa/pip/issues/4391). Once that's fixed, instead of + # installing the extra dependencies, install the following instead: + # 'requests[security] >= 2.5.2, != 2.11.0, != 2.12.2' + 'tls': ['pyOpenSSL>=0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'], } version = None
docker/docker-py
5e4a69bbdafef6f1036b733ce356c6692c65e775
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 7045d23c..4a391fac 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -768,6 +768,11 @@ class ExcludePathsTest(unittest.TestCase): self.all_paths - set(['foo/a.py']) ) + def test_single_subdir_single_filename_leading_slash(self): + assert self.exclude(['/foo/a.py']) == convert_paths( + self.all_paths - set(['foo/a.py']) + ) + def test_single_subdir_with_path_traversal(self): assert self.exclude(['foo/whoops/../a.py']) == convert_paths( self.all_paths - set(['foo/a.py'])
using private image in FROM during build is broken Example: ``` import docker from io import BytesIO dockerfile=""" FROM <some-private-image-on-docker-hub> CMD ["ls"] """ f = BytesIO(dockerfile.encode('utf-8')) client = docker.APIClient(version='auto') client.login(username='<user>', password='<pass>') for l in client.build(fileobj=f, rm=True, tag='test', stream=True, pull=True): print(l) ``` This example will error saying that it failed to find the image in FROM. If you add the full registry: ``` client = docker.APIClient(version='auto') client.login(username='<user>', password='<pass>', registry='https://index.docker.io/v1/') ``` It will succeed. If you leave off the trailing slash on the registry url, it will fail. python 3.5.2 docker-py 2.4.2
0.0
5e4a69bbdafef6f1036b733ce356c6692c65e775
[ "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename_leading_slash" ]
[ "tests/unit/utils_test.py::DecoratorsTest::test_update_headers", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_newline", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_trailing_slash", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_empty_string", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_non_string", "tests/unit/utils_test.py::PortsTest::test_split_port_random_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_ipv6_address", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::PortsTest::test_with_no_container_port", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_double_wildcard", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_and_double_wildcard", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_socket_file", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_shoud_check_parent_directories_of_excluded", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_should_check_directory_not_excluded", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_should_check_excluded_directory_with_exceptions", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_should_check_subdirectories_of_exceptions", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_should_not_check_excluded_directories_with_no_exceptions", "tests/unit/utils_test.py::ShouldCheckDirectoryTest::test_should_not_check_siblings_of_exceptions", "tests/unit/utils_test.py::FormatEnvironmentTest::test_format_env_binary_unicode_value", "tests/unit/utils_test.py::FormatEnvironmentTest::test_format_env_no_value" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-08-15 22:39:49+00:00
apache-2.0
1,969
docker__docker-py-2008
diff --git a/docker/api/config.py b/docker/api/config.py index b46b09c7..767bef26 100644 --- a/docker/api/config.py +++ b/docker/api/config.py @@ -6,7 +6,7 @@ from .. import utils class ConfigApiMixin(object): - @utils.minimum_version('1.25') + @utils.minimum_version('1.30') def create_config(self, name, data, labels=None): """ Create a config @@ -35,7 +35,7 @@ class ConfigApiMixin(object): self._post_json(url, data=body), True ) - @utils.minimum_version('1.25') + @utils.minimum_version('1.30') @utils.check_resource('id') def inspect_config(self, id): """ @@ -53,7 +53,7 @@ class ConfigApiMixin(object): url = self._url('/configs/{0}', id) return self._result(self._get(url), True) - @utils.minimum_version('1.25') + @utils.minimum_version('1.30') @utils.check_resource('id') def remove_config(self, id): """ @@ -73,7 +73,7 @@ class ConfigApiMixin(object): self._raise_for_status(res) return True - @utils.minimum_version('1.25') + @utils.minimum_version('1.30') def configs(self, filters=None): """ List configs diff --git a/docker/api/container.py b/docker/api/container.py index cb97b794..05676f11 100644 --- a/docker/api/container.py +++ b/docker/api/container.py @@ -1018,7 +1018,10 @@ class ContainerApiMixin(object): """ params = {'t': timeout} url = self._url("/containers/{0}/restart", container) - res = self._post(url, params=params) + conn_timeout = self.timeout + if conn_timeout is not None: + conn_timeout += timeout + res = self._post(url, params=params, timeout=conn_timeout) self._raise_for_status(res) @utils.check_resource('container') @@ -1107,9 +1110,10 @@ class ContainerApiMixin(object): else: params = {'t': timeout} url = self._url("/containers/{0}/stop", container) - - res = self._post(url, params=params, - timeout=(timeout + (self.timeout or 0))) + conn_timeout = self.timeout + if conn_timeout is not None: + conn_timeout += timeout + res = self._post(url, params=params, timeout=conn_timeout) self._raise_for_status(res) @utils.check_resource('container')
docker/docker-py
accb9de52f6e383ad0335807f73c8c35bd6e7426
diff --git a/tests/integration/api_container_test.py b/tests/integration/api_container_test.py index e2125186..afd439f9 100644 --- a/tests/integration/api_container_test.py +++ b/tests/integration/api_container_test.py @@ -1165,6 +1165,15 @@ class RestartContainerTest(BaseAPIIntegrationTest): assert info2['State']['Running'] is True self.client.kill(id) + def test_restart_with_low_timeout(self): + container = self.client.create_container(BUSYBOX, ['sleep', '9999']) + self.client.start(container) + self.client.timeout = 1 + self.client.restart(container, timeout=3) + self.client.timeout = None + self.client.restart(container, timeout=3) + self.client.kill(container) + def test_restart_with_dict_instead_of_id(self): container = self.client.create_container(BUSYBOX, ['sleep', '9999']) assert 'Id' in container diff --git a/tests/unit/api_container_test.py b/tests/unit/api_container_test.py index c33f129e..a7e183c8 100644 --- a/tests/unit/api_container_test.py +++ b/tests/unit/api_container_test.py @@ -1335,7 +1335,7 @@ class ContainerTest(BaseAPIClientTest): 'POST', url_prefix + 'containers/3cc2351ab11b/restart', params={'t': 2}, - timeout=DEFAULT_TIMEOUT_SECONDS + timeout=(DEFAULT_TIMEOUT_SECONDS + 2) ) def test_restart_container_with_dict_instead_of_id(self): @@ -1345,7 +1345,7 @@ class ContainerTest(BaseAPIClientTest): 'POST', url_prefix + 'containers/3cc2351ab11b/restart', params={'t': 2}, - timeout=DEFAULT_TIMEOUT_SECONDS + timeout=(DEFAULT_TIMEOUT_SECONDS + 2) ) def test_remove_container(self):
ContainerApiMixin::restart(timeout=...) uses default read timeout which results in ReadTimeout exception ReadTimeout is thrown when you restart or stop a container with a high timeout (e.g. 120sec) in case when the container needs over 60 seconds to stop. This requires users to write code like this: ``` try: my_container.client.api.timeout = 130 my_container.restart(timeout=110) finally: my_container.client.api.timeout = docker.constants.DEFAULT_TIMEOUT_SECONDS ``` or write their own `restart` method. IMO better solution would be to use read timeout that is `max(docker.constants.DEFAULT_TIMEOUT_SECONDS, user_timeout + SOME_CONSTANT)`, because when someone stops a container with specified timeout (`user_timeout`) it's expected that there might be no data to read from the socket for at least `user_timeout`
0.0
accb9de52f6e383ad0335807f73c8c35bd6e7426
[ "tests/unit/api_container_test.py::ContainerTest::test_restart_container", "tests/unit/api_container_test.py::ContainerTest::test_restart_container_with_dict_instead_of_id" ]
[ "tests/unit/api_container_test.py::StartContainerTest::test_start_container", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_none", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_privileged", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_regression_573", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_ro", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_rw", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_multiple_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_port_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_privileged", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_added_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_aliases", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode_and_ro_error", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_ro", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_rw", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cgroup_parent", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_devices", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_dropped_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_entrypoint", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpu_shares", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpus", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset_mems", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mac_address", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_int", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_g_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_k_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_m_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_wrong_value", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_multiple_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_named_volume", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_port_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_ports", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_restart_policy", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stdin_open", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stop_signal", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_sysctl", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_unicode_envvars", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volume_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_working_dir", "tests/unit/api_container_test.py::CreateContainerTest::test_create_named_container", "tests/unit/api_container_test.py::ContainerTest::test_container_stats", "tests/unit/api_container_test.py::ContainerTest::test_container_top", "tests/unit/api_container_test.py::ContainerTest::test_container_top_with_psargs", "tests/unit/api_container_test.py::ContainerTest::test_container_update", "tests/unit/api_container_test.py::ContainerTest::test_diff", "tests/unit/api_container_test.py::ContainerTest::test_diff_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_export", "tests/unit/api_container_test.py::ContainerTest::test_export_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container_undefined_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_signal", "tests/unit/api_container_test.py::ContainerTest::test_list_containers", "tests/unit/api_container_test.py::ContainerTest::test_log_following", "tests/unit/api_container_test.py::ContainerTest::test_log_following_backwards", "tests/unit/api_container_test.py::ContainerTest::test_log_since", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_datetime", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_invalid_value_raises_error", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming_and_following", "tests/unit/api_container_test.py::ContainerTest::test_log_tail", "tests/unit/api_container_test.py::ContainerTest::test_log_tty", "tests/unit/api_container_test.py::ContainerTest::test_logs", "tests/unit/api_container_test.py::ContainerTest::test_logs_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_pause_container", "tests/unit/api_container_test.py::ContainerTest::test_port", "tests/unit/api_container_test.py::ContainerTest::test_remove_container", "tests/unit/api_container_test.py::ContainerTest::test_remove_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_rename_container", "tests/unit/api_container_test.py::ContainerTest::test_resize_container", "tests/unit/api_container_test.py::ContainerTest::test_stop_container", "tests/unit/api_container_test.py::ContainerTest::test_stop_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_unpause_container", "tests/unit/api_container_test.py::ContainerTest::test_wait", "tests/unit/api_container_test.py::ContainerTest::test_wait_with_dict_instead_of_id" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-04-25 22:20:48+00:00
apache-2.0
1,970
docker__docker-py-2186
diff --git a/docker/api/image.py b/docker/api/image.py index a9f801e9..d3fed5c0 100644 --- a/docker/api/image.py +++ b/docker/api/image.py @@ -334,7 +334,8 @@ class ImageApiMixin(object): Args: repository (str): The repository to pull tag (str): The tag to pull - stream (bool): Stream the output as a generator + stream (bool): Stream the output as a generator. Make sure to + consume the generator, otherwise pull might get cancelled. auth_config (dict): Override the credentials that :py:meth:`~docker.api.daemon.DaemonApiMixin.login` has set for this request. ``auth_config`` should contain the ``username`` diff --git a/docker/models/images.py b/docker/models/images.py index 4578c0bd..30e86f10 100644 --- a/docker/models/images.py +++ b/docker/models/images.py @@ -1,5 +1,6 @@ import itertools import re +import warnings import six @@ -425,7 +426,21 @@ class ImageCollection(Collection): if not tag: repository, tag = parse_repository_tag(repository) - self.client.api.pull(repository, tag=tag, **kwargs) + if 'stream' in kwargs: + warnings.warn( + '`stream` is not a valid parameter for this method' + ' and will be overridden' + ) + del kwargs['stream'] + + pull_log = self.client.api.pull( + repository, tag=tag, stream=True, **kwargs + ) + for _ in pull_log: + # We don't do anything with the logs, but we need + # to keep the connection alive and wait for the image + # to be pulled. + pass if tag: return self.get('{0}{2}{1}'.format( repository, tag, '@' if tag.startswith('sha256:') else ':'
docker/docker-py
e1e4048753aafc96571752cf54d96df7b24156d3
diff --git a/tests/unit/models_containers_test.py b/tests/unit/models_containers_test.py index 22dd2410..39e409e4 100644 --- a/tests/unit/models_containers_test.py +++ b/tests/unit/models_containers_test.py @@ -232,7 +232,9 @@ class ContainerCollectionTest(unittest.TestCase): container = client.containers.run('alpine', 'sleep 300', detach=True) assert container.id == FAKE_CONTAINER_ID - client.api.pull.assert_called_with('alpine', platform=None, tag=None) + client.api.pull.assert_called_with( + 'alpine', platform=None, tag=None, stream=True + ) def test_run_with_error(self): client = make_fake_client() diff --git a/tests/unit/models_images_test.py b/tests/unit/models_images_test.py index 67832795..fd894ab7 100644 --- a/tests/unit/models_images_test.py +++ b/tests/unit/models_images_test.py @@ -1,6 +1,8 @@ +import unittest +import warnings + from docker.constants import DEFAULT_DATA_CHUNK_SIZE from docker.models.images import Image -import unittest from .fake_api import FAKE_IMAGE_ID from .fake_api_client import make_fake_client @@ -43,7 +45,9 @@ class ImageCollectionTest(unittest.TestCase): def test_pull(self): client = make_fake_client() image = client.images.pull('test_image:latest') - client.api.pull.assert_called_with('test_image', tag='latest') + client.api.pull.assert_called_with( + 'test_image', tag='latest', stream=True + ) client.api.inspect_image.assert_called_with('test_image:latest') assert isinstance(image, Image) assert image.id == FAKE_IMAGE_ID @@ -51,7 +55,9 @@ class ImageCollectionTest(unittest.TestCase): def test_pull_multiple(self): client = make_fake_client() images = client.images.pull('test_image') - client.api.pull.assert_called_with('test_image', tag=None) + client.api.pull.assert_called_with( + 'test_image', tag=None, stream=True + ) client.api.images.assert_called_with( all=False, name='test_image', filters=None ) @@ -61,6 +67,16 @@ class ImageCollectionTest(unittest.TestCase): assert isinstance(image, Image) assert image.id == FAKE_IMAGE_ID + def test_pull_with_stream_param(self): + client = make_fake_client() + with warnings.catch_warnings(record=True) as w: + client.images.pull('test_image', stream=True) + + assert len(w) == 1 + assert str(w[0].message).startswith( + '`stream` is not a valid parameter' + ) + def test_push(self): client = make_fake_client() client.images.push('foobar', insecure_registry=True)
Can't pull image with stream=True Hi, The scenario is as follows: Mac 10.13.6 docker version v18.06.0-ce Python 3.6 (python package) docker==3.5.0 private docker registry (docker hub, private repo) docker login works ✔️ docker pull $image works ✔️ however, pulling via the docker python api fails when using the parameter `stream=True`: In terminal window I run : ``` python >>> client = docker.DockerClient(base_url='unix://var/run/docker.sock') >>> client.login(username='XXXX', password='XXXX', registry='https://index.docker.io/v1/') >>> client.images.pull('docker.io/vdmtl/portail-datamigration-worker-gcs-lib:latest', stream=True) Traceback (most recent call last): File "/Users/XXXX/apps/open-data-etl/venv/lib/python3.6/site-packages/docker/api/client.py", line 229, in _raise_for_status response.raise_for_status() File "/Users/XXX/apps/open-data-etl/venv/lib/python3.6/site-packages/requests/models.py", line 937, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http+docker://localhost/v1.35/images/docker.io/vdmtl/portail-datamigration-worker-gcs-lib:latest/json >>> client.images.pull('docker.io/vdmtl/portail-datamigration-worker-gcs-lib:latest') <Image: 'vdmtl/portail-datamigration-worker-gcs-lib:latest'> ``` As you can see removing `stream=True` is necessary in order to download my image.
0.0
e1e4048753aafc96571752cf54d96df7b24156d3
[ "tests/unit/models_images_test.py::ImageCollectionTest::test_pull", "tests/unit/models_images_test.py::ImageCollectionTest::test_pull_multiple", "tests/unit/models_images_test.py::ImageCollectionTest::test_pull_with_stream_param", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run_pull" ]
[ "tests/unit/models_images_test.py::ImageCollectionTest::test_load", "tests/unit/models_images_test.py::ImageCollectionTest::test_get", "tests/unit/models_images_test.py::ImageCollectionTest::test_search", "tests/unit/models_images_test.py::ImageCollectionTest::test_push", "tests/unit/models_images_test.py::ImageCollectionTest::test_build", "tests/unit/models_images_test.py::ImageCollectionTest::test_remove", "tests/unit/models_images_test.py::ImageCollectionTest::test_list", "tests/unit/models_images_test.py::ImageCollectionTest::test_labels", "tests/unit/models_images_test.py::ImageTest::test_history", "tests/unit/models_images_test.py::ImageTest::test_tag", "tests/unit/models_images_test.py::ImageTest::test_short_id", "tests/unit/models_images_test.py::ImageTest::test_save", "tests/unit/models_images_test.py::ImageTest::test_tags", "tests/unit/models_containers_test.py::ContainerTest::test_put_archive", "tests/unit/models_containers_test.py::ContainerTest::test_restart", "tests/unit/models_containers_test.py::ContainerTest::test_diff", "tests/unit/models_containers_test.py::ContainerTest::test_update", "tests/unit/models_containers_test.py::ContainerTest::test_exec_run", "tests/unit/models_containers_test.py::ContainerTest::test_image", "tests/unit/models_containers_test.py::ContainerTest::test_labels", "tests/unit/models_containers_test.py::ContainerTest::test_attach", "tests/unit/models_containers_test.py::ContainerTest::test_logs", "tests/unit/models_containers_test.py::ContainerTest::test_start", "tests/unit/models_containers_test.py::ContainerTest::test_pause", "tests/unit/models_containers_test.py::ContainerTest::test_top", "tests/unit/models_containers_test.py::ContainerTest::test_wait", "tests/unit/models_containers_test.py::ContainerTest::test_status", "tests/unit/models_containers_test.py::ContainerTest::test_resize", "tests/unit/models_containers_test.py::ContainerTest::test_name", "tests/unit/models_containers_test.py::ContainerTest::test_get_archive", "tests/unit/models_containers_test.py::ContainerTest::test_rename", "tests/unit/models_containers_test.py::ContainerTest::test_stop", "tests/unit/models_containers_test.py::ContainerTest::test_unpause", "tests/unit/models_containers_test.py::ContainerTest::test_remove", "tests/unit/models_containers_test.py::ContainerTest::test_export", "tests/unit/models_containers_test.py::ContainerTest::test_exec_run_failure", "tests/unit/models_containers_test.py::ContainerTest::test_commit", "tests/unit/models_containers_test.py::ContainerTest::test_kill", "tests/unit/models_containers_test.py::ContainerTest::test_stats", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run_remove", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_get", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_create", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run_with_image_object", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_list", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_list_ignore_removed", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run_detach", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_create_with_image_object", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_run_with_error", "tests/unit/models_containers_test.py::ContainerCollectionTest::test_create_container_args" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-11-28 19:26:48+00:00
apache-2.0
1,971
docker__docker-py-2917
diff --git a/docker/api/plugin.py b/docker/api/plugin.py index 57110f11..10210c1a 100644 --- a/docker/api/plugin.py +++ b/docker/api/plugin.py @@ -51,19 +51,20 @@ class PluginApiMixin: return True @utils.minimum_version('1.25') - def disable_plugin(self, name): + def disable_plugin(self, name, force=False): """ Disable an installed plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. + force (bool): To enable the force query parameter. Returns: ``True`` if successful """ url = self._url('/plugins/{0}/disable', name) - res = self._post(url) + res = self._post(url, params={'force': force}) self._raise_for_status(res) return True diff --git a/docker/models/plugins.py b/docker/models/plugins.py index 69b94f35..16f5245e 100644 --- a/docker/models/plugins.py +++ b/docker/models/plugins.py @@ -44,16 +44,19 @@ class Plugin(Model): self.client.api.configure_plugin(self.name, options) self.reload() - def disable(self): + def disable(self, force=False): """ Disable the plugin. + Args: + force (bool): Force disable. Default: False + Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ - self.client.api.disable_plugin(self.name) + self.client.api.disable_plugin(self.name, force) self.reload() def enable(self, timeout=0): diff --git a/docker/models/services.py b/docker/models/services.py index 200dd333..92550681 100644 --- a/docker/models/services.py +++ b/docker/models/services.py @@ -320,6 +320,7 @@ CREATE_SERVICE_KWARGS = [ 'labels', 'mode', 'update_config', + 'rollback_config', 'endpoint_spec', ]
docker/docker-py
b2a18d7209f827d83cc33acb80aa31bf404ffd4b
diff --git a/tests/integration/api_plugin_test.py b/tests/integration/api_plugin_test.py index 38f9d12d..3ecb0283 100644 --- a/tests/integration/api_plugin_test.py +++ b/tests/integration/api_plugin_test.py @@ -22,13 +22,13 @@ class PluginTest(BaseAPIIntegrationTest): def teardown_method(self, method): client = self.get_client_instance() try: - client.disable_plugin(SSHFS) + client.disable_plugin(SSHFS, True) except docker.errors.APIError: pass for p in self.tmp_plugins: try: - client.remove_plugin(p, force=True) + client.remove_plugin(p) except docker.errors.APIError: pass diff --git a/tests/integration/models_services_test.py b/tests/integration/models_services_test.py index 982842b3..f1439a41 100644 --- a/tests/integration/models_services_test.py +++ b/tests/integration/models_services_test.py @@ -30,13 +30,18 @@ class ServiceTest(unittest.TestCase): # ContainerSpec arguments image="alpine", command="sleep 300", - container_labels={'container': 'label'} + container_labels={'container': 'label'}, + rollback_config={'order': 'start-first'} ) assert service.name == name assert service.attrs['Spec']['Labels']['foo'] == 'bar' container_spec = service.attrs['Spec']['TaskTemplate']['ContainerSpec'] assert "alpine" in container_spec['Image'] assert container_spec['Labels'] == {'container': 'label'} + spec_rollback = service.attrs['Spec'].get('RollbackConfig', None) + assert spec_rollback is not None + assert ('Order' in spec_rollback and + spec_rollback['Order'] == 'start-first') def test_create_with_network(self): client = docker.from_env(version=TEST_API_VERSION) diff --git a/tests/unit/models_services_test.py b/tests/unit/models_services_test.py index b9192e42..94a27f0e 100644 --- a/tests/unit/models_services_test.py +++ b/tests/unit/models_services_test.py @@ -11,6 +11,7 @@ class CreateServiceKwargsTest(unittest.TestCase): 'labels': {'key': 'value'}, 'hostname': 'test_host', 'mode': 'global', + 'rollback_config': {'rollback': 'config'}, 'update_config': {'update': 'config'}, 'networks': ['somenet'], 'endpoint_spec': {'blah': 'blah'}, @@ -37,6 +38,7 @@ class CreateServiceKwargsTest(unittest.TestCase): 'name': 'somename', 'labels': {'key': 'value'}, 'mode': 'global', + 'rollback_config': {'rollback': 'config'}, 'update_config': {'update': 'config'}, 'endpoint_spec': {'blah': 'blah'}, }
Missed rollback_config in service's create/update methods. Hi, in [documentation](https://docker-py.readthedocs.io/en/stable/services.html) for service written that it support `rollback_config` parameter, but in `models/services.py`'s `CREATE_SERVICE_KWARGS` list doesn't contain it. So, I got this error: `TypeError: create() got an unexpected keyword argument 'rollback_config'` Can someone tell me, is this done intentionally, or is it a bug? **Version:** `4.4.4, 5.0.0 and older` **My diff:** ``` diff --git a/docker/models/services.py b/docker/models/services.py index a29ff13..0f26626 100644 --- a/docker/models/services.py +++ b/docker/models/services.py @@ -314,6 +314,7 @@ CREATE_SERVICE_KWARGS = [ 'labels', 'mode', 'update_config', + 'rollback_config', 'endpoint_spec', ] ``` PS. Full stacktrace: ``` In [54]: service_our = client.services.create( ...: name=service_name, ...: image=image_full_name, ...: restart_policy=restart_policy, ...: update_config=update_config, ...: rollback_config=rollback_config ...: ) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-54-8cc6a8a6519b> in <module> ----> 1 service_our = client.services.create( 2 name=service_name, 3 image=image_full_name, 4 restart_policy=restart_policy, 5 update_config=update_config, /usr/local/lib/python3.9/site-packages/docker/models/services.py in create(self, image, command, **kwargs) 224 kwargs['image'] = image 225 kwargs['command'] = command --> 226 create_kwargs = _get_create_service_kwargs('create', kwargs) 227 service_id = self.client.api.create_service(**create_kwargs) 228 return self.get(service_id) /usr/local/lib/python3.9/site-packages/docker/models/services.py in _get_create_service_kwargs(func_name, kwargs) 369 # All kwargs should have been consumed by this point, so raise 370 # error if any are left --> 371 if kwargs: 372 raise create_unexpected_kwargs_error(func_name, kwargs) 373 TypeError: create() got an unexpected keyword argument 'rollback_config' ```
0.0
b2a18d7209f827d83cc33acb80aa31bf404ffd4b
[ "tests/unit/models_services_test.py::CreateServiceKwargsTest::test_get_create_service_kwargs" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-11-23 07:33:12+00:00
apache-2.0
1,972
docker__docker-py-3120
diff --git a/docker/api/container.py b/docker/api/container.py index fef76030..40607e79 100644 --- a/docker/api/container.py +++ b/docker/api/container.py @@ -1164,8 +1164,9 @@ class ContainerApiMixin: 'one_shot is only available in conjunction with ' 'stream=False' ) - return self._stream_helper(self._get(url, params=params), - decode=decode) + return self._stream_helper( + self._get(url, stream=True, params=params), decode=decode + ) else: if decode: raise errors.InvalidArgument(
docker/docker-py
576e47aaacf690a3fdd6cf98c345d48ecf834b7d
diff --git a/tests/unit/api_container_test.py b/tests/unit/api_container_test.py index c605da37..c4e2250b 100644 --- a/tests/unit/api_container_test.py +++ b/tests/unit/api_container_test.py @@ -1528,10 +1528,21 @@ class ContainerTest(BaseAPIClientTest): fake_request.assert_called_with( 'GET', url_prefix + 'containers/' + fake_api.FAKE_CONTAINER_ID + '/stats', + stream=True, timeout=60, params={'stream': True} ) + def test_container_stats_without_streaming(self): + self.client.stats(fake_api.FAKE_CONTAINER_ID, stream=False) + + fake_request.assert_called_with( + 'GET', + url_prefix + 'containers/' + fake_api.FAKE_CONTAINER_ID + '/stats', + timeout=60, + params={'stream': False} + ) + def test_container_stats_with_one_shot(self): self.client.stats( fake_api.FAKE_CONTAINER_ID, stream=False, one_shot=True)
Containers stats is broken in Docker-py 6.1.0 Look like Docker-Py breaks the API to retrieve stats from containers. With Docker 6.0.1 (on Ubuntu 22.04): ``` >>> import docker >>> c = docker..from_env() >>> for i in c.containers.list(): ... i.stats(decode=True) ... <generator object APIClient._stream_helper at 0x7f236f354eb0> ``` With Docker 6.1.0: ``` >>> import docker >>> c = docker..from_env() >>> for i in c.containers.list(): ... i.stats(decode=True) ... Never return anything... ``` Additional information: ``` $ cat /etc/os-release PRETTY_NAME="Ubuntu 22.04.2 LTS" NAME="Ubuntu" VERSION_ID="22.04" VERSION="22.04.2 LTS (Jammy Jellyfish)" VERSION_CODENAME=jammy ID=ubuntu ID_LIKE=debian HOME_URL="https://www.ubuntu.com/" SUPPORT_URL="https://help.ubuntu.com/" BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" UBUNTU_CODENAME=jammy $ docker version Client: Docker Engine - Community Version: 23.0.1 API version: 1.42 Go version: go1.19.5 Git commit: a5ee5b1 Built: Thu Feb 9 19:46:56 2023 OS/Arch: linux/amd64 Context: default Server: Docker Engine - Community Engine: Version: 23.0.1 API version: 1.42 (minimum version 1.12) Go version: go1.19.5 Git commit: bc3805a Built: Thu Feb 9 19:46:56 2023 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.6.19 GitCommit: 1e1ea6e986c6c86565bc33d52e34b81b3e2bc71f runc: Version: 1.1.4 GitCommit: v1.1.4-0-g5fd4c4d docker-init: Version: 0.19.0 ``` Source: https://github.com/nicolargo/glances/issues/2366
0.0
576e47aaacf690a3fdd6cf98c345d48ecf834b7d
[ "tests/unit/api_container_test.py::ContainerTest::test_container_stats" ]
[ "tests/unit/api_container_test.py::StartContainerTest::test_start_container", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_none", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_privileged", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_regression_573", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_ro", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_rw", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_multiple_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_port_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_privileged", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_added_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_aliases", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode_and_ro_error", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_ro", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_rw", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cgroup_parent", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cgroupns", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_device_requests", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_devices", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_dropped_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_entrypoint", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpu_shares", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpus", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset_mems", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mac_address", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_int", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_g_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_k_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_m_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_wrong_value", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_multiple_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_named_volume", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_platform", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_port_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_ports", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_restart_policy", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stdin_open", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stop_signal", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_sysctl", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_unicode_envvars", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volume_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_working_dir", "tests/unit/api_container_test.py::CreateContainerTest::test_create_named_container", "tests/unit/api_container_test.py::ContainerTest::test_container_stats_with_one_shot", "tests/unit/api_container_test.py::ContainerTest::test_container_stats_without_streaming", "tests/unit/api_container_test.py::ContainerTest::test_container_top", "tests/unit/api_container_test.py::ContainerTest::test_container_top_with_psargs", "tests/unit/api_container_test.py::ContainerTest::test_container_update", "tests/unit/api_container_test.py::ContainerTest::test_diff", "tests/unit/api_container_test.py::ContainerTest::test_diff_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_export", "tests/unit/api_container_test.py::ContainerTest::test_export_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container_undefined_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_signal", "tests/unit/api_container_test.py::ContainerTest::test_list_containers", "tests/unit/api_container_test.py::ContainerTest::test_log_following", "tests/unit/api_container_test.py::ContainerTest::test_log_following_backwards", "tests/unit/api_container_test.py::ContainerTest::test_log_since", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_datetime", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_float", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_invalid_value_raises_error", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming_and_following", "tests/unit/api_container_test.py::ContainerTest::test_log_tail", "tests/unit/api_container_test.py::ContainerTest::test_log_tty", "tests/unit/api_container_test.py::ContainerTest::test_logs", "tests/unit/api_container_test.py::ContainerTest::test_logs_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_pause_container", "tests/unit/api_container_test.py::ContainerTest::test_port", "tests/unit/api_container_test.py::ContainerTest::test_remove_container", "tests/unit/api_container_test.py::ContainerTest::test_remove_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_rename_container", "tests/unit/api_container_test.py::ContainerTest::test_resize_container", "tests/unit/api_container_test.py::ContainerTest::test_restart_container", "tests/unit/api_container_test.py::ContainerTest::test_restart_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_stop_container", "tests/unit/api_container_test.py::ContainerTest::test_stop_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_unpause_container", "tests/unit/api_container_test.py::ContainerTest::test_wait", "tests/unit/api_container_test.py::ContainerTest::test_wait_with_dict_instead_of_id" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2023-05-06 19:23:04+00:00
apache-2.0
1,973
docker__docker-py-3200
diff --git a/docker/models/configs.py b/docker/models/configs.py index 3588c8b5..5ef13778 100644 --- a/docker/models/configs.py +++ b/docker/models/configs.py @@ -30,6 +30,7 @@ class ConfigCollection(Collection): def create(self, **kwargs): obj = self.client.api.create_config(**kwargs) + obj.setdefault("Spec", {})["Name"] = kwargs.get("name") return self.prepare_model(obj) create.__doc__ = APIClient.create_config.__doc__ diff --git a/docker/utils/build.py b/docker/utils/build.py index a5c4b0c2..86a4423f 100644 --- a/docker/utils/build.py +++ b/docker/utils/build.py @@ -10,8 +10,9 @@ from ..constants import IS_WINDOWS_PLATFORM _SEP = re.compile('/|\\\\') if IS_WINDOWS_PLATFORM else re.compile('/') _TAG = re.compile( - r"^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(\/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*" \ - + "(:[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127})?$" + r"^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*" + r"(?::[0-9]+)?(/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*" + r"(:[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127})?$" ) diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 759ddd2f..dbd51303 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -5,7 +5,7 @@ import os import os.path import shlex import string -from datetime import datetime +from datetime import datetime, timezone from packaging.version import Version from .. import errors @@ -394,8 +394,8 @@ def convert_filters(filters): def datetime_to_timestamp(dt): - """Convert a UTC datetime to a Unix timestamp""" - delta = dt - datetime.utcfromtimestamp(0) + """Convert a datetime to a Unix timestamp""" + delta = dt.astimezone(timezone.utc) - datetime(1970, 1, 1, tzinfo=timezone.utc) return delta.seconds + delta.days * 24 * 3600
docker/docker-py
6ceb08273c157cbab7b5c77bd71e7389f1a6acc5
diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index 0524becd..03e53cc6 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -19,6 +19,8 @@ FAKE_VOLUME_NAME = 'perfectcherryblossom' FAKE_NODE_ID = '24ifsmvkjbyhk' FAKE_SECRET_ID = 'epdyrw4tsi03xy3deu8g8ly6o' FAKE_SECRET_NAME = 'super_secret' +FAKE_CONFIG_ID = 'sekvs771242jfdjnvfuds8232' +FAKE_CONFIG_NAME = 'super_config' # Each method is prefixed with HTTP method (get, post...) # for clarity and readability @@ -512,6 +514,11 @@ def post_fake_secret(): response = {'ID': FAKE_SECRET_ID} return status_code, response +def post_fake_config(): + status_code = 200 + response = {'ID': FAKE_CONFIG_ID} + return status_code, response + # Maps real api url to fake response callback prefix = 'http+docker://localhost' @@ -630,4 +637,6 @@ fake_responses = { post_fake_network_disconnect, f'{prefix}/{CURRENT_VERSION}/secrets/create': post_fake_secret, + f'{prefix}/{CURRENT_VERSION}/configs/create': + post_fake_config, } diff --git a/tests/unit/fake_api_client.py b/tests/unit/fake_api_client.py index 95cf63b4..79799421 100644 --- a/tests/unit/fake_api_client.py +++ b/tests/unit/fake_api_client.py @@ -37,6 +37,7 @@ def make_fake_api_client(overrides=None): 'create_host_config.side_effect': api_client.create_host_config, 'create_network.return_value': fake_api.post_fake_network()[1], 'create_secret.return_value': fake_api.post_fake_secret()[1], + 'create_config.return_value': fake_api.post_fake_config()[1], 'exec_create.return_value': fake_api.post_fake_exec_create()[1], 'exec_start.return_value': fake_api.post_fake_exec_start()[1], 'images.return_value': fake_api.get_fake_images()[1], diff --git a/tests/unit/models_configs_test.py b/tests/unit/models_configs_test.py new file mode 100644 index 00000000..6960397f --- /dev/null +++ b/tests/unit/models_configs_test.py @@ -0,0 +1,10 @@ +import unittest + +from .fake_api_client import make_fake_client +from .fake_api import FAKE_CONFIG_NAME + +class CreateConfigsTest(unittest.TestCase): + def test_create_config(self): + client = make_fake_client() + config = client.configs.create(name="super_config", data="config") + assert config.__repr__() == "<Config: '{}'>".format(FAKE_CONFIG_NAME) diff --git a/tests/unit/utils_build_test.py b/tests/unit/utils_build_test.py index fa7d833d..5f1bb1ec 100644 --- a/tests/unit/utils_build_test.py +++ b/tests/unit/utils_build_test.py @@ -6,11 +6,10 @@ import tarfile import tempfile import unittest +import pytest from docker.constants import IS_WINDOWS_PLATFORM -from docker.utils import exclude_paths, tar - -import pytest +from docker.utils import exclude_paths, tar, match_tag from ..helpers import make_tree @@ -489,3 +488,51 @@ class TarTest(unittest.TestCase): assert member in names assert 'a/c/b' in names assert 'a/c/b/utils.py' not in names + + +# selected test cases from https://github.com/distribution/reference/blob/8507c7fcf0da9f570540c958ea7b972c30eeaeca/reference_test.go#L13-L328 [email protected]("tag,expected", [ + ("test_com", True), + ("test.com:tag", True), + # N.B. this implicitly means "docker.io/library/test.com:5000" + # i.e. the `5000` is a tag, not a port here! + ("test.com:5000", True), + ("test.com/repo:tag", True), + ("test:5000/repo", True), + ("test:5000/repo:tag", True), + ("test:5000/repo", True), + ("", False), + (":justtag", False), + ("Uppercase:tag", False), + ("test:5000/Uppercase/lowercase:tag", False), + ("lowercase:Uppercase", True), + # length limits not enforced + pytest.param("a/"*128 + "a:tag", False, marks=pytest.mark.xfail), + ("a/"*127 + "a:tag-puts-this-over-max", True), + ("aa/asdf$$^/aa", False), + ("sub-dom1.foo.com/bar/baz/quux", True), + ("sub-dom1.foo.com/bar/baz/quux:some-long-tag", True), + ("b.gcr.io/test.example.com/my-app:test.example.com", True), + ("xn--n3h.com/myimage:xn--n3h.com", True), + ("foo_bar.com:8080", True), + ("foo/foo_bar.com:8080", True), + ("192.168.1.1", True), + ("192.168.1.1:tag", True), + ("192.168.1.1:5000", True), + ("192.168.1.1/repo", True), + ("192.168.1.1:5000/repo", True), + ("192.168.1.1:5000/repo:5050", True), + # regex does not properly handle ipv6 + pytest.param("[2001:db8::1]", False, marks=pytest.mark.xfail), + ("[2001:db8::1]:5000", False), + pytest.param("[2001:db8::1]/repo", True, marks=pytest.mark.xfail), + pytest.param("[2001:db8:1:2:3:4:5:6]/repo:tag", True, marks=pytest.mark.xfail), + pytest.param("[2001:db8::1]:5000/repo", True, marks=pytest.mark.xfail), + pytest.param("[2001:db8::1]:5000/repo:tag", True, marks=pytest.mark.xfail), + pytest.param("[2001:db8::]:5000/repo", True, marks=pytest.mark.xfail), + pytest.param("[::1]:5000/repo", True, marks=pytest.mark.xfail), + ("[fe80::1%eth0]:5000/repo", False), + ("[fe80::1%@invalidzone]:5000/repo", False), +]) +def test_match_tag(tag: str, expected: bool): + assert match_tag(tag) == expected
Can't create config object Much like https://github.com/docker/docker-py/issues/2025 the config model is failing to create a new object due to 'name' KeyError ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "docker\models\configs.py", line 10, in __repr__ return f"<{self.__class__.__name__}: '{self.name}'>" File "docker\models\configs.py", line 14, in name return self.attrs['Spec']['Name'] ``` This https://github.com/docker/docker-py/pull/2793 appears to be the fix that was implemented and should likely be implements for configs as well (if not other models that might have this issue)
0.0
6ceb08273c157cbab7b5c77bd71e7389f1a6acc5
[ "tests/unit/models_configs_test.py::CreateConfigsTest::test_create_config", "tests/unit/utils_build_test.py::test_match_tag[test:5000/repo-True0]", "tests/unit/utils_build_test.py::test_match_tag[test:5000/repo:tag-True]", "tests/unit/utils_build_test.py::test_match_tag[test:5000/repo-True1]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1:5000/repo-True]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1:5000/repo:5050-True]" ]
[ "tests/unit/utils_build_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_build_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_build_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_build_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_build_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_build_test.py::ExcludePathsTest::test_double_wildcard", "tests/unit/utils_build_test.py::ExcludePathsTest::test_double_wildcard_with_exception", "tests/unit/utils_build_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_build_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_build_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_build_test.py::ExcludePathsTest::test_exclude_include_absolute_path", "tests/unit/utils_build_test.py::ExcludePathsTest::test_include_wildcard", "tests/unit/utils_build_test.py::ExcludePathsTest::test_last_line_precedence", "tests/unit/utils_build_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_build_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_build_test.py::ExcludePathsTest::test_parent_directory", "tests/unit/utils_build_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_and_double_wildcard", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_subdir_single_filename_leading_slash", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_build_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_build_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_build_test.py::ExcludePathsTest::test_trailing_double_wildcard", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_build_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_build_test.py::TarTest::test_tar_directory_link", "tests/unit/utils_build_test.py::TarTest::test_tar_socket_file", "tests/unit/utils_build_test.py::TarTest::test_tar_with_broken_symlinks", "tests/unit/utils_build_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_build_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_build_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_build_test.py::TarTest::test_tar_with_file_symlinks", "tests/unit/utils_build_test.py::test_match_tag[test_com-True]", "tests/unit/utils_build_test.py::test_match_tag[test.com:tag-True]", "tests/unit/utils_build_test.py::test_match_tag[test.com:5000-True]", "tests/unit/utils_build_test.py::test_match_tag[test.com/repo:tag-True]", "tests/unit/utils_build_test.py::test_match_tag[-False]", "tests/unit/utils_build_test.py::test_match_tag[:justtag-False]", "tests/unit/utils_build_test.py::test_match_tag[Uppercase:tag-False]", "tests/unit/utils_build_test.py::test_match_tag[test:5000/Uppercase/lowercase:tag-False]", "tests/unit/utils_build_test.py::test_match_tag[lowercase:Uppercase-True]", "tests/unit/utils_build_test.py::test_match_tag[a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a:tag-puts-this-over-max-True]", "tests/unit/utils_build_test.py::test_match_tag[aa/asdf$$^/aa-False]", "tests/unit/utils_build_test.py::test_match_tag[sub-dom1.foo.com/bar/baz/quux-True]", "tests/unit/utils_build_test.py::test_match_tag[sub-dom1.foo.com/bar/baz/quux:some-long-tag-True]", "tests/unit/utils_build_test.py::test_match_tag[b.gcr.io/test.example.com/my-app:test.example.com-True]", "tests/unit/utils_build_test.py::test_match_tag[xn--n3h.com/myimage:xn--n3h.com-True]", "tests/unit/utils_build_test.py::test_match_tag[foo_bar.com:8080-True]", "tests/unit/utils_build_test.py::test_match_tag[foo/foo_bar.com:8080-True]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1-True]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1:tag-True]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1:5000-True]", "tests/unit/utils_build_test.py::test_match_tag[192.168.1.1/repo-True]", "tests/unit/utils_build_test.py::test_match_tag[[2001:db8::1]:5000-False]", "tests/unit/utils_build_test.py::test_match_tag[[fe80::1%eth0]:5000/repo-False]", "tests/unit/utils_build_test.py::test_match_tag[[fe80::1%@invalidzone]:5000/repo-False]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-17 15:00:52+00:00
apache-2.0
1,974
docker__docker-py-822
diff --git a/docker/api/container.py b/docker/api/container.py index 72c5852d..953a5f52 100644 --- a/docker/api/container.py +++ b/docker/api/container.py @@ -997,19 +997,16 @@ class ContainerApiMixin(object): self._raise_for_status(res) @utils.check_resource - def start(self, container, binds=None, port_bindings=None, lxc_conf=None, - publish_all_ports=None, links=None, privileged=None, - dns=None, dns_search=None, volumes_from=None, network_mode=None, - restart_policy=None, cap_add=None, cap_drop=None, devices=None, - extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None, - security_opt=None, ulimits=None): + def start(self, container, *args, **kwargs): """ Start a container. Similar to the ``docker start`` command, but doesn't support attach options. - **Deprecation warning:** For API version > 1.15, it is highly - recommended to provide host config options in the ``host_config`` - parameter of :py:meth:`~ContainerApiMixin.create_container`. + **Deprecation warning:** Passing configuration options in ``start`` is + no longer supported. Users are expected to provide host config options + in the ``host_config`` parameter of + :py:meth:`~ContainerApiMixin.create_container`. + Args: container (str): The container to start @@ -1017,6 +1014,8 @@ class ContainerApiMixin(object): Raises: :py:class:`docker.errors.APIError` If the server returns an error. + :py:class:`docker.errors.DeprecatedMethod` + If any argument besides ``container`` are provided. Example: @@ -1025,64 +1024,14 @@ class ContainerApiMixin(object): ... command='/bin/sleep 30') >>> cli.start(container=container.get('Id')) """ - if utils.compare_version('1.10', self._version) < 0: - if dns is not None: - raise errors.InvalidVersion( - 'dns is only supported for API version >= 1.10' - ) - if volumes_from is not None: - raise errors.InvalidVersion( - 'volumes_from is only supported for API version >= 1.10' - ) - - if utils.compare_version('1.15', self._version) < 0: - if security_opt is not None: - raise errors.InvalidVersion( - 'security_opt is only supported for API version >= 1.15' - ) - if ipc_mode: - raise errors.InvalidVersion( - 'ipc_mode is only supported for API version >= 1.15' - ) - - if utils.compare_version('1.17', self._version) < 0: - if read_only is not None: - raise errors.InvalidVersion( - 'read_only is only supported for API version >= 1.17' - ) - if pid_mode is not None: - raise errors.InvalidVersion( - 'pid_mode is only supported for API version >= 1.17' - ) - - if utils.compare_version('1.18', self._version) < 0: - if ulimits is not None: - raise errors.InvalidVersion( - 'ulimits is only supported for API version >= 1.18' - ) - - start_config_kwargs = dict( - binds=binds, port_bindings=port_bindings, lxc_conf=lxc_conf, - publish_all_ports=publish_all_ports, links=links, dns=dns, - privileged=privileged, dns_search=dns_search, cap_add=cap_add, - cap_drop=cap_drop, volumes_from=volumes_from, devices=devices, - network_mode=network_mode, restart_policy=restart_policy, - extra_hosts=extra_hosts, read_only=read_only, pid_mode=pid_mode, - ipc_mode=ipc_mode, security_opt=security_opt, ulimits=ulimits, - ) - start_config = None - - if any(v is not None for v in start_config_kwargs.values()): - if utils.compare_version('1.15', self._version) > 0: - warnings.warn( - 'Passing host config parameters in start() is deprecated. ' - 'Please use host_config in create_container instead!', - DeprecationWarning - ) - start_config = self.create_host_config(**start_config_kwargs) - + if args or kwargs: + raise errors.DeprecatedMethod( + 'Providing configuration in the start() method is no longer ' + 'supported. Use the host_config param in create_container ' + 'instead.' + ) url = self._url("/containers/{0}/start", container) - res = self._post_json(url, data=start_config) + res = self._post(url) self._raise_for_status(res) @utils.minimum_version('1.17')
docker/docker-py
4c8c761bc15160be5eaa76d81edda17b067aa641
diff --git a/tests/unit/api_container_test.py b/tests/unit/api_container_test.py index 6c080641..abf36138 100644 --- a/tests/unit/api_container_test.py +++ b/tests/unit/api_container_test.py @@ -34,10 +34,7 @@ class StartContainerTest(BaseAPIClientTest): args[0][1], url_prefix + 'containers/3cc2351ab11b/start' ) - self.assertEqual(json.loads(args[1]['data']), {}) - self.assertEqual( - args[1]['headers'], {'Content-Type': 'application/json'} - ) + assert 'data' not in args[1] self.assertEqual( args[1]['timeout'], DEFAULT_TIMEOUT_SECONDS ) @@ -63,25 +60,21 @@ class StartContainerTest(BaseAPIClientTest): self.client.start(**{'container': fake_api.FAKE_CONTAINER_ID}) def test_start_container_with_lxc_conf(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, lxc_conf={'lxc.conf.k': 'lxc.conf.value'} ) - pytest.deprecated_call(call_start) - def test_start_container_with_lxc_conf_compat(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, lxc_conf=[{'Key': 'lxc.conf.k', 'Value': 'lxc.conf.value'}] ) - pytest.deprecated_call(call_start) - def test_start_container_with_binds_ro(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, binds={ '/tmp': { @@ -91,22 +84,18 @@ class StartContainerTest(BaseAPIClientTest): } ) - pytest.deprecated_call(call_start) - def test_start_container_with_binds_rw(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, binds={ '/tmp': {"bind": '/mnt', "ro": False} } ) - pytest.deprecated_call(call_start) - def test_start_container_with_port_binds(self): self.maxDiff = None - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start(fake_api.FAKE_CONTAINER_ID, port_bindings={ 1111: None, 2222: 2222, @@ -116,18 +105,14 @@ class StartContainerTest(BaseAPIClientTest): 6666: [('127.0.0.1',), ('192.168.0.1',)] }) - pytest.deprecated_call(call_start) - def test_start_container_with_links(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, links={'path': 'alias'} ) - pytest.deprecated_call(call_start) - def test_start_container_with_multiple_links(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start( fake_api.FAKE_CONTAINER_ID, links={ @@ -136,21 +121,15 @@ class StartContainerTest(BaseAPIClientTest): } ) - pytest.deprecated_call(call_start) - def test_start_container_with_links_as_list_of_tuples(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start(fake_api.FAKE_CONTAINER_ID, links=[('path', 'alias')]) - pytest.deprecated_call(call_start) - def test_start_container_privileged(self): - def call_start(): + with pytest.raises(docker.errors.DeprecatedMethod): self.client.start(fake_api.FAKE_CONTAINER_ID, privileged=True) - pytest.deprecated_call(call_start) - def test_start_container_with_dict_instead_of_id(self): self.client.start({'Id': fake_api.FAKE_CONTAINER_ID}) @@ -159,10 +138,7 @@ class StartContainerTest(BaseAPIClientTest): args[0][1], url_prefix + 'containers/3cc2351ab11b/start' ) - self.assertEqual(json.loads(args[1]['data']), {}) - self.assertEqual( - args[1]['headers'], {'Content-Type': 'application/json'} - ) + assert 'data' not in args[1] self.assertEqual( args[1]['timeout'], DEFAULT_TIMEOUT_SECONDS )
Passing host_config parameters in start() overrides the host_config that was passed in create()? I had a `host_config` with `extra_hosts` defined. I used this `host_config` to create a container. When starting container, I passed extra volumes_from parameter. However, this lead to `extra_hosts` seemingly not doing their job. After I moved `volumes_from` from `start()` to `create_host_config` everything started working OK. I figured, I should report this, since I spent a couple of hours figuring this out. IMO, start() should override the necessary parts of host_config(and not the whole thing). Or raise an exception.
0.0
4c8c761bc15160be5eaa76d81edda17b067aa641
[ "tests/unit/api_container_test.py::StartContainerTest::test_start_container", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_privileged", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_ro", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_binds_rw", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_multiple_links", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_with_port_binds" ]
[ "tests/unit/api_container_test.py::StartContainerTest::test_start_container_none", "tests/unit/api_container_test.py::StartContainerTest::test_start_container_regression_573", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_empty_volumes_from", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_privileged", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_added_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_aliases", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_mode_and_ro_error", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_ro", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_binds_rw", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cgroup_parent", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cpu_shares", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_cpuset", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_devices", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_dropped_capabilities", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_entrypoint", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpu_shares", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_host_config_cpuset", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_labels_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_links_as_list_of_tuples", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_lxc_conf_compat", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mac_address", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_int", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_g_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_k_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_m_unit", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_mem_limit_as_string_with_wrong_value", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_multiple_links", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_named_volume", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_port_binds", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_ports", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_restart_policy", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stdin_open", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_stop_signal", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_sysctl", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_dict", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_tmpfs_list", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_unicode_envvars", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volume_string", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_volumes_from", "tests/unit/api_container_test.py::CreateContainerTest::test_create_container_with_working_dir", "tests/unit/api_container_test.py::CreateContainerTest::test_create_named_container", "tests/unit/api_container_test.py::ContainerTest::test_container_stats", "tests/unit/api_container_test.py::ContainerTest::test_container_top", "tests/unit/api_container_test.py::ContainerTest::test_container_top_with_psargs", "tests/unit/api_container_test.py::ContainerTest::test_container_update", "tests/unit/api_container_test.py::ContainerTest::test_diff", "tests/unit/api_container_test.py::ContainerTest::test_diff_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_export", "tests/unit/api_container_test.py::ContainerTest::test_export_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container", "tests/unit/api_container_test.py::ContainerTest::test_inspect_container_undefined_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_kill_container_with_signal", "tests/unit/api_container_test.py::ContainerTest::test_list_containers", "tests/unit/api_container_test.py::ContainerTest::test_log_following", "tests/unit/api_container_test.py::ContainerTest::test_log_following_backwards", "tests/unit/api_container_test.py::ContainerTest::test_log_since", "tests/unit/api_container_test.py::ContainerTest::test_log_since_with_datetime", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming", "tests/unit/api_container_test.py::ContainerTest::test_log_streaming_and_following", "tests/unit/api_container_test.py::ContainerTest::test_log_tail", "tests/unit/api_container_test.py::ContainerTest::test_log_tty", "tests/unit/api_container_test.py::ContainerTest::test_logs", "tests/unit/api_container_test.py::ContainerTest::test_logs_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_pause_container", "tests/unit/api_container_test.py::ContainerTest::test_port", "tests/unit/api_container_test.py::ContainerTest::test_remove_container", "tests/unit/api_container_test.py::ContainerTest::test_remove_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_rename_container", "tests/unit/api_container_test.py::ContainerTest::test_resize_container", "tests/unit/api_container_test.py::ContainerTest::test_restart_container", "tests/unit/api_container_test.py::ContainerTest::test_restart_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_stop_container", "tests/unit/api_container_test.py::ContainerTest::test_stop_container_with_dict_instead_of_id", "tests/unit/api_container_test.py::ContainerTest::test_unpause_container", "tests/unit/api_container_test.py::ContainerTest::test_wait", "tests/unit/api_container_test.py::ContainerTest::test_wait_with_dict_instead_of_id" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2015-10-21 22:58:11+00:00
apache-2.0
1,975
dogsheep__twitter-to-sqlite-24
diff --git a/twitter_to_sqlite/cli.py b/twitter_to_sqlite/cli.py index 56ba167..ad44655 100644 --- a/twitter_to_sqlite/cli.py +++ b/twitter_to_sqlite/cli.py @@ -5,7 +5,7 @@ import pathlib import time import click -import sqlite_utils + from twitter_to_sqlite import archive from twitter_to_sqlite import utils @@ -102,7 +102,7 @@ def followers(db_path, auth, user_id, screen_name, silent): "Save followers for specified user (defaults to authenticated user)" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) fetched = [] # Get the follower count, so we can have a progress bar count = 0 @@ -152,7 +152,7 @@ def favorites(db_path, auth, user_id, screen_name, stop_after): "Save tweets favorited by specified user" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) profile = utils.get_profile(db, session, user_id, screen_name) with click.progressbar( utils.fetch_favorites(session, user_id, screen_name, stop_after), @@ -193,7 +193,7 @@ def user_timeline(db_path, auth, stop_after, user_id, screen_name, since, since_ raise click.ClickException("Use either --since or --since_id, not both") auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) profile = utils.get_profile(db, session, user_id, screen_name) expected_length = profile["statuses_count"] @@ -209,7 +209,9 @@ def user_timeline(db_path, auth, stop_after, user_id, screen_name, since, since_ pass with click.progressbar( - utils.fetch_user_timeline(session, user_id, screen_name, stop_after, since_id=since_id), + utils.fetch_user_timeline( + session, user_id, screen_name, stop_after, since_id=since_id + ), length=expected_length, label="Importing tweets", show_pos=True, @@ -253,7 +255,7 @@ def home_timeline(db_path, auth, since, since_id): raise click.ClickException("Use either --since or --since_id, not both") auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) profile = utils.get_profile(db, session) expected_length = 800 if since and db["timeline_tweets"].exists: @@ -310,7 +312,7 @@ def users_lookup(db_path, identifiers, attach, sql, auth, ids): "Fetch user accounts" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) for batch in utils.fetch_user_batches(session, identifiers, ids): utils.save_users(db, batch) @@ -338,7 +340,7 @@ def statuses_lookup(db_path, identifiers, attach, sql, auth, skip_existing, sile "Fetch tweets by their IDs" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) if skip_existing: existing_ids = set( @@ -381,7 +383,7 @@ def list_members(db_path, identifiers, auth, ids): "Fetch lists - accepts one or more screen_name/list_slug identifiers" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) for identifier in identifiers: utils.fetch_and_save_list(db, session, identifier, ids) @@ -477,7 +479,7 @@ def track(db_path, track, auth, verbose): "Experimental: Save tweets matching these keywords in real-time" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) for tweet in utils.stream_filter(session, track=track): if verbose: print(json.dumps(tweet, indent=2)) @@ -505,7 +507,7 @@ def follow(db_path, identifiers, attach, sql, ids, auth, verbose): "Experimental: Follow these Twitter users and save tweets in real-time" auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) # Make sure we have saved these users to the database for batch in utils.fetch_user_batches(session, identifiers, ids): @@ -528,7 +530,7 @@ def _shared_friends_ids_followers_ids( ): auth = json.load(open(auth)) session = utils.session_for_auth(auth) - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) identifiers = utils.resolve_identifiers(db, identifiers, attach, sql) for identifier in identifiers: # Make sure this user is saved @@ -568,7 +570,7 @@ def import_(db_path, paths): Import data from a Twitter exported archive. Input can be the path to a zip file, a directory full of .js files or one or more direct .js files. """ - db = sqlite_utils.Database(db_path) + db = utils.open_database(db_path) for filepath in paths: path = pathlib.Path(filepath) if path.suffix == ".zip": diff --git a/twitter_to_sqlite/migrations.py b/twitter_to_sqlite/migrations.py new file mode 100644 index 0000000..13d7c65 --- /dev/null +++ b/twitter_to_sqlite/migrations.py @@ -0,0 +1,22 @@ +from .utils import extract_and_save_source + +MIGRATIONS = [] + + +def migration(fn): + MIGRATIONS.append(fn) + return fn + + +@migration +def convert_source_column(db): + tables = set(db.table_names()) + if "tweets" not in tables: + return + # Now we extract any '<a href=...' records from the source + for id, source in db.conn.execute( + "select id, source from tweets where source like '<%'" + ).fetchall(): + db["tweets"].update(id, {"source": extract_and_save_source(db, source)}) + db["tweets"].create_index(["source"]) + db["tweets"].add_foreign_key("source") diff --git a/twitter_to_sqlite/utils.py b/twitter_to_sqlite/utils.py index 6f2a44e..1755c51 100644 --- a/twitter_to_sqlite/utils.py +++ b/twitter_to_sqlite/utils.py @@ -2,16 +2,46 @@ import datetime import html import json import pathlib +import re import time import urllib.parse import zipfile from dateutil import parser from requests_oauthlib import OAuth1Session +import sqlite_utils # Twitter API error codes RATE_LIMIT_ERROR_CODE = 88 +source_re = re.compile('<a href="(?P<url>.*?)".*?>(?P<name>.*?)</a>') + + +def open_database(db_path): + db = sqlite_utils.Database(db_path) + # Only run migrations if this is an existing DB (has tables) + if db.tables: + migrate(db) + return db + + +def migrate(db): + from twitter_to_sqlite.migrations import MIGRATIONS + + if "migrations" not in db.table_names(): + db["migrations"].create({"name": str, "applied": str}, pk="name") + applied_migrations = { + m[0] for m in db.conn.execute("select name from migrations").fetchall() + } + for migration in MIGRATIONS: + name = migration.__name__ + if name in applied_migrations: + continue + migration(db) + db["migrations"].insert( + {"name": name, "applied": datetime.datetime.utcnow().isoformat()} + ) + def session_for_auth(auth): return OAuth1Session( @@ -186,6 +216,8 @@ def ensure_tables(db): table_names = set(db.table_names()) if "places" not in table_names: db["places"].create({"id": str}, pk="id") + if "sources" not in table_names: + db["sources"].create({"id": str, "name": str, "url": str}, pk="id") if "users" not in table_names: db["users"].create( { @@ -210,9 +242,14 @@ def ensure_tables(db): "retweeted_status": int, "quoted_status": int, "place": str, + "source": str, }, pk="id", - foreign_keys=(("user", "users", "id"), ("place", "places", "id")), + foreign_keys=( + ("user", "users", "id"), + ("place", "places", "id"), + ("source", "sources", "id"), + ), ) db["tweets"].enable_fts(["full_text"], create_triggers=True) db["tweets"].add_foreign_key("retweeted_status", "tweets") @@ -235,6 +272,7 @@ def save_tweets(db, tweets, favorited_by=None): user = tweet.pop("user") transform_user(user) tweet["user"] = user["id"] + tweet["source"] = extract_and_save_source(db, tweet["source"]) if tweet.get("place"): db["places"].upsert(tweet["place"], pk="id", alter=True) tweet["place"] = tweet["place"]["id"] @@ -472,3 +510,9 @@ def read_archive_js(filepath): for zi in zf.filelist: if zi.filename.endswith(".js"): yield zi.filename, zf.open(zi.filename).read() + + +def extract_and_save_source(db, source): + m = source_re.match(source) + details = m.groupdict() + return db["sources"].upsert(details, hash_id="id").last_pk
dogsheep/twitter-to-sqlite
619f724a722b3f23f4364f67d3164b93e8ba2a70
diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..5877d34 --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,49 @@ +import sqlite_utils +from click.testing import CliRunner +import sqlite_utils +from twitter_to_sqlite import cli, migrations + +from .test_import import zip_contents_path + + +def test_no_migrations_on_first_run(tmpdir, zip_contents_path): + output = str(tmpdir / "output.db") + args = ["import", output, str(zip_contents_path / "follower.js")] + result = CliRunner().invoke(cli.cli, args) + assert 0 == result.exit_code, result.stdout + db = sqlite_utils.Database(output) + assert ["archive_follower"] == db.table_names() + # Re-running the command again should also run the migrations + result = CliRunner().invoke(cli.cli, args) + db = sqlite_utils.Database(output) + assert {"archive_follower", "migrations"} == set(db.table_names()) + + +def test_convert_source_column(): + db = sqlite_utils.Database(memory=True) + db["tweets"].insert_all( + [ + {"id": 1, "source": '<a href="URL">NAME</a>'}, + {"id": 2, "source": '<a href="URL2">NAME2</a>'}, + {"id": 3, "source": "d3c1d39c57fecfc09202f20ea5e2db30262029fd"}, + ], + pk="id", + ) + migrations.convert_source_column(db) + assert [ + { + "id": "d3c1d39c57fecfc09202f20ea5e2db30262029fd", + "url": "URL", + "name": "NAME", + }, + { + "id": "000e4c4db71278018fb8c322f070d051e76885b1", + "url": "URL2", + "name": "NAME2", + }, + ] == list(db["sources"].rows) + assert [ + {"id": 1, "source": "d3c1d39c57fecfc09202f20ea5e2db30262029fd"}, + {"id": 2, "source": "000e4c4db71278018fb8c322f070d051e76885b1"}, + {"id": 3, "source": "d3c1d39c57fecfc09202f20ea5e2db30262029fd"}, + ] == list(db["tweets"].rows) diff --git a/tests/test_save_tweets.py b/tests/test_save_tweets.py index 4bbe7ae..dc87a71 100644 --- a/tests/test_save_tweets.py +++ b/tests/test_save_tweets.py @@ -20,6 +20,7 @@ def db(tweets): def test_tables(db): assert { + "sources", "users_fts_idx", "users_fts_data", "tweets_fts", @@ -182,9 +183,9 @@ def test_tweets(db): "retweeted_status": None, "quoted_status": None, "place": None, + "source": "e6528b505bcfd811fdd40ff2d46665dbccba2024", "truncated": 0, "display_text_range": "[0, 139]", - "source": '<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>', "in_reply_to_status_id": None, "in_reply_to_user_id": None, "in_reply_to_screen_name": None, @@ -207,9 +208,9 @@ def test_tweets(db): "retweeted_status": None, "quoted_status": 861696799362478100, "place": None, + "source": "1f89d6a41b1505a3071169f8d0d028ba9ad6f952", "truncated": 0, "display_text_range": "[0, 239]", - "source": '<a href="https://mobile.twitter.com" rel="nofollow">Twitter Web App</a>', "in_reply_to_status_id": None, "in_reply_to_user_id": None, "in_reply_to_screen_name": None, @@ -232,9 +233,9 @@ def test_tweets(db): "retweeted_status": None, "quoted_status": None, "place": "01a9a39529b27f36", + "source": "95f3aaaddaa45937ac94765e0ddb68ba2be92d20", "truncated": 0, "display_text_range": "[45, 262]", - "source": '<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', "in_reply_to_status_id": "1169079390577320000", "in_reply_to_user_id": "82016165", "in_reply_to_screen_name": "scientiffic", @@ -257,9 +258,9 @@ def test_tweets(db): "retweeted_status": None, "quoted_status": None, "place": None, + "source": "942cfc2bf9f290ddbe3d78f1907dc084a00ed23f", "truncated": 0, "display_text_range": "[0, 235]", - "source": '<a href="http://www.voxmedia.com" rel="nofollow">Vox Media</a>', "in_reply_to_status_id": None, "in_reply_to_user_id": None, "in_reply_to_screen_name": None, @@ -282,9 +283,9 @@ def test_tweets(db): "retweeted_status": 1169242008432644000, "quoted_status": None, "place": None, + "source": "95f3aaaddaa45937ac94765e0ddb68ba2be92d20", "truncated": 0, "display_text_range": "[0, 143]", - "source": '<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', "in_reply_to_status_id": None, "in_reply_to_user_id": None, "in_reply_to_screen_name": None, @@ -302,6 +303,32 @@ def test_tweets(db): ] == tweet_rows +def test_sources(db): + source_rows = list(db["sources"].rows) + assert [ + { + "id": "942cfc2bf9f290ddbe3d78f1907dc084a00ed23f", + "name": "Vox Media", + "url": "http://www.voxmedia.com", + }, + { + "id": "95f3aaaddaa45937ac94765e0ddb68ba2be92d20", + "name": "Twitter for iPhone", + "url": "http://twitter.com/download/iphone", + }, + { + "id": "1f89d6a41b1505a3071169f8d0d028ba9ad6f952", + "name": "Twitter Web App", + "url": "https://mobile.twitter.com", + }, + { + "id": "e6528b505bcfd811fdd40ff2d46665dbccba2024", + "name": "Twitter for Mac", + "url": "http://itunes.apple.com/us/app/twitter/id409789998?mt=12", + }, + ] == source_rows + + def test_places(db): place_rows = list(db["places"].rows) assert [
Extract "source" into a separate lookup table It's pretty bulky and ugly at the moment: <img width="334" alt="trump__tweets__1_820_rows" src="https://user-images.githubusercontent.com/9599/66264630-df23a080-e7bd-11e9-9154-403c2e69f841.png">
0.0
619f724a722b3f23f4364f67d3164b93e8ba2a70
[ "tests/test_migrations.py::test_no_migrations_on_first_run", "tests/test_migrations.py::test_convert_source_column", "tests/test_save_tweets.py::test_tables", "tests/test_save_tweets.py::test_users", "tests/test_save_tweets.py::test_tweets", "tests/test_save_tweets.py::test_sources", "tests/test_save_tweets.py::test_places", "tests/test_save_tweets.py::test_media" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_media", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-17 15:24:56+00:00
apache-2.0
1,976
dopefishh__pympi-39
diff --git a/MANIFEST b/MANIFEST index 5965331..0b43bb0 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,4 +1,5 @@ # file GENERATED by distutils, do NOT edit +setup.cfg setup.py pympi/Elan.py pympi/Praat.py diff --git a/pympi/Elan.py b/pympi/Elan.py index 4b4553e..0a3975c 100644 --- a/pympi/Elan.py +++ b/pympi/Elan.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- - from xml.etree import cElementTree as etree -import os import re import sys import time +import pathlib import warnings VERSION = '1.7' @@ -663,7 +661,8 @@ class Eaf: :returns: Tuple of the form: ``(min_time, max_time)``. """ return (0, 0) if not self.timeslots else\ - (min(self.timeslots.values()), max(self.timeslots.values())) + (min(v for v in self.timeslots.values() if v is not None), + max(v for v in self.timeslots.values() if v is not None)) def get_gaps_and_overlaps(self, tier1, tier2, maxlen=-1): """Give gaps and overlaps. The return types are shown in the table @@ -1460,7 +1459,8 @@ def parse_eaf(file_path, eaf_obj, suppress_version_warning=False): file_path = sys.stdin # Annotation document try: - tree_root = etree.parse(file_path).getroot() + # py3.5 compat: etree.parse does not support pathlib.Path objects in py3.5. + tree_root = etree.parse(str(file_path)).getroot() except etree.ParseError: raise Exception('Unable to parse eaf, can you open it in ELAN?') @@ -1623,15 +1623,7 @@ def to_eaf(file_path, eaf_obj, pretty=True): :param bool pretty: Flag to set pretty printing. """ def rm_none(x): - try: # Ugly hack to test if s is a string in py3 and py2 - basestring - - def isstr(s): - return isinstance(s, basestring) - except NameError: - def isstr(s): - return isinstance(s, str) - return {k: v if isstr(v) else str(v) for k, v in x.items() + return {k: v if isinstance(v, str) else str(v) for k, v in x.items() if v is not None} # Annotation Document ADOCUMENT = etree.Element('ANNOTATION_DOCUMENT', eaf_obj.adocument) @@ -1717,7 +1709,8 @@ def to_eaf(file_path, eaf_obj, pretty=True): except LookupError: sys.stdout.write(etree.tostring(ADOCUMENT, encoding='UTF-8')) else: - if os.access(file_path, os.F_OK): - os.rename(file_path, '{}.bak'.format(file_path)) + file_path = pathlib.Path(file_path) + if file_path.exists(): + file_path.rename(file_path.with_suffix('.bak')) etree.ElementTree(ADOCUMENT).write( - file_path, xml_declaration=True, encoding='UTF-8') + str(file_path), xml_declaration=True, encoding='UTF-8') diff --git a/pympi/Praat.py b/pympi/Praat.py index eba3c5d..9f1ecb6 100644 --- a/pympi/Praat.py +++ b/pympi/Praat.py @@ -1,6 +1,3 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - import codecs import re import struct @@ -63,11 +60,9 @@ class TextGrid: elif textlen == -1: textlen = struct.unpack('>h', ifile.read(2))[0] data = ifile.read(textlen*2) - # Hack to go from number to unicode in python3 and python2 - fun = unichr if 'unichr' in __builtins__ else chr charlist = (data[i:i+2] for i in range(0, len(data), 2)) - return u''.join( - fun(struct.unpack('>h', i)[0]) for i in charlist) + return ''.join( + chr(struct.unpack('>h', i)[0]) for i in charlist) ifile.read(ord(ifile.read(1))) # skip oo type self.xmin = struct.unpack('>d', ifile.read(8))[0] @@ -98,9 +93,9 @@ class TextGrid: line = next(ifile).decode(codec) return pat.search(line).group(1) - regfloat = re.compile('([\d.]+)\s*$', flags=re.UNICODE) - regint = re.compile('([\d]+)\s*$', flags=re.UNICODE) - regstr = re.compile('"(.*)"\s*$', flags=re.UNICODE) + regfloat = re.compile(r'([\d.]+)\s*$', flags=re.UNICODE) + regint = re.compile(r'([\d]+)\s*$', flags=re.UNICODE) + regstr = re.compile(r'"(.*)"\s*$', flags=re.UNICODE) # Skip the Headers and empty line next(ifile), next(ifile), next(ifile) self.xmin = float(nn(ifile, regfloat)) @@ -159,7 +154,7 @@ class TextGrid: elif number < 1 or number > len(self.tiers): raise ValueError('Number not in [1..{}]'.format(len(self.tiers))) elif tier_type not in Tier.P_TIERS: - raise ValueError('tier_type has to be in {}'.format(self.P_TIERS)) + raise ValueError('tier_type has to be in {}'.format(Tier.P_TIERS)) self.tiers.insert(number-1, Tier(self.xmin, self.xmax, name, tier_type)) return self.tiers[number-1] @@ -254,7 +249,8 @@ class TextGrid: itier and f.write(struct.pack('>d', c[1])) writebstr(c[2 if itier else 1]) elif mode in ['normal', 'n', 'short', 's']: - with codecs.open(filepath, 'w', codec) as f: + # py3.5 compat: codecs.open does not support pathlib.Path objects in py3.5. + with codecs.open(str(filepath), 'w', codec) as f: short = mode[0] == 's' def wrt(indent, prefix, value, ff=''): diff --git a/pympi/__init__.py b/pympi/__init__.py index 53f76cc..791f39a 100644 --- a/pympi/__init__.py +++ b/pympi/__init__.py @@ -1,5 +1,5 @@ # Import the packages from pympi.Praat import TextGrid -from pympi.Elan import Eaf +from pympi.Elan import Eaf, eaf_from_chat __all__ = ['Praat', 'Elan', 'eaf_from_chat'] diff --git a/tox.ini b/tox.ini index 142ca55..1ff9207 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py{36,37,38} +envlist = py{35,36,37,38} skip_missing_interpreters = true [testenv]
dopefishh/pympi
fd924ffca6ea8ca2ef81384f97ce4396334ef850
diff --git a/test/test_elan.py b/test/test_elan.py index 0249154..34ee7da 100644 --- a/test/test_elan.py +++ b/test/test_elan.py @@ -1153,10 +1153,14 @@ class Elan(unittest.TestCase): ] ) def test_to_file_to_eaf(eaf, schema, test_dir, tmp_path): - filepath = tmp_path / 'test.eaf' - eaf = Eaf(test_dir / eaf) + filepath = str(tmp_path / 'test.eaf') + eaf = Eaf(str(test_dir / eaf)) eaf.to_file(filepath) schema = etree.XMLSchema(etree.XML(test_dir.joinpath(schema).read_text(encoding='utf8'))) xmlparser = etree.XMLParser(schema=schema) etree.parse(str(filepath), xmlparser) + + +def test_to_textgrid(test_dir): + _ = Eaf(str(test_dir / 'sample_2.7.eaf')).to_textgrid() diff --git a/test/test_praat.py b/test/test_praat.py index f71afc8..1c94c41 100644 --- a/test/test_praat.py +++ b/test/test_praat.py @@ -1,9 +1,7 @@ -#!/bin/env python -# -*- coding: utf-8 -*- - +import pathlib import unittest -import tempfile -import os +import pytest + from pympi.Praat import TextGrid @@ -126,38 +124,6 @@ class PraatTest(unittest.TestCase): self.assertEqual([(1, 'tier1'), (2, 'tier3'), (3, 'tier2')], list(self.tg.get_tier_name_num())) - def test_to_file(self): - for codec in ['utf-8', 'latin_1', 'mac_roman']: - self.tg = TextGrid(xmax=20) - tier1 = self.tg.add_tier('tier') - tier1.add_interval(1, 2, 'i1') - tier1.add_interval(2, 3, 'i2') - tier1.add_interval(4, 5, 'i3') - - tier4 = self.tg.add_tier('tier') - tier4.add_interval(1, 2, u'i1ü') - tier4.add_interval(2.0, 3, 'i2') - tier4.add_interval(4, 5.0, 'i3') - - tier2 = self.tg.add_tier('tier2', tier_type='TextTier') - tier2.add_point(1, u'p1ü') - tier2.add_point(2, 'p1') - tier2.add_point(3, 'p1') - - tempf = tempfile.mkstemp()[1] - -# Normal mode - self.tg.to_file(tempf, codec=codec) - TextGrid(tempf, codec=codec) -# Short mode - self.tg.to_file(tempf, codec=codec, mode='s') - TextGrid(tempf, codec=codec) -# Binary mode - self.tg.to_file(tempf, mode='b') - TextGrid(tempf) - - os.remove(tempf) - def test_to_eaf(self): tier1 = self.tg.add_tier('tier1') tier2 = self.tg.add_tier('tier2', tier_type='TextTier') @@ -267,5 +233,33 @@ class PraatTest(unittest.TestCase): self.tier2.clear_intervals() self.assertEqual([], self.tier2.intervals) -if __name__ == '__main__': - unittest.main() + [email protected]('codec', ['utf-8', 'latin_1', 'mac_roman']) +def test_to_file(codec, tmp_path): + tg = TextGrid(xmax=20) + tier1 = tg.add_tier('tier') + tier1.add_interval(1, 2, 'i1') + tier1.add_interval(2, 3, 'i2') + tier1.add_interval(4, 5, 'i3') + + tier4 = tg.add_tier('tier') + tier4.add_interval(1, 2, u'i1ü') + tier4.add_interval(2.0, 3, 'i2') + tier4.add_interval(4, 5.0, 'i3') + + tier2 = tg.add_tier('tier2', tier_type='TextTier') + tier2.add_point(1, u'p1ü') + tier2.add_point(2, 'p1') + tier2.add_point(3, 'p1') + + tempf = str(tmp_path / 'test') + + # Normal mode + tg.to_file(pathlib.Path(tempf), codec=codec) + TextGrid(tempf, codec=codec) + # Short mode + tg.to_file(tempf, codec=codec, mode='s') + TextGrid(tempf, codec=codec) + # Binary mode + tg.to_file(tempf, mode='b') + TextGrid(tempf)
Support pathlib.Path objects in addition to str file paths I propose to additionally accept `pathlib.Path` objects wherever file paths as `str` are accepted now. This makes tests simpler (when using pytest's `tmp_path`) and is also becoming the standard behaviour of most python stdlib modules.
0.0
fd924ffca6ea8ca2ef81384f97ce4396334ef850
[ "test/test_elan.py::test_to_textgrid" ]
[ "test/test_elan.py::Elan::test_add_annotation", "test/test_elan.py::Elan::test_add_controlled_vocabulary", "test/test_elan.py::Elan::test_add_cv_description", "test/test_elan.py::Elan::test_add_cv_entry", "test/test_elan.py::Elan::test_add_external_ref", "test/test_elan.py::Elan::test_add_language", "test/test_elan.py::Elan::test_add_lexicon_ref", "test/test_elan.py::Elan::test_add_license", "test/test_elan.py::Elan::test_add_linguistic_type", "test/test_elan.py::Elan::test_add_linked_file", "test/test_elan.py::Elan::test_add_locale", "test/test_elan.py::Elan::test_add_nested_reference_annotations", "test/test_elan.py::Elan::test_add_property", "test/test_elan.py::Elan::test_add_ref_annotation", "test/test_elan.py::Elan::test_add_secondary_linked_file", "test/test_elan.py::Elan::test_add_tier", "test/test_elan.py::Elan::test_clean_time_slots", "test/test_elan.py::Elan::test_copy_tier", "test/test_elan.py::Elan::test_create_gaps_and_overlaps_tier", "test/test_elan.py::Elan::test_eaf_from_chat", "test/test_elan.py::Elan::test_filter_annotations", "test/test_elan.py::Elan::test_get_annotation_data_after_time", "test/test_elan.py::Elan::test_get_annotation_data_at_time", "test/test_elan.py::Elan::test_get_annotation_data_before_time", "test/test_elan.py::Elan::test_get_annotation_data_between_times", "test/test_elan.py::Elan::test_get_annotation_data_for_tier", "test/test_elan.py::Elan::test_get_child_tiers_for", "test/test_elan.py::Elan::test_get_controlled_vocabulary_names", "test/test_elan.py::Elan::test_get_cv_descriptions", "test/test_elan.py::Elan::test_get_cv_entry", "test/test_elan.py::Elan::test_get_external_ref", "test/test_elan.py::Elan::test_get_external_ref_names", "test/test_elan.py::Elan::test_get_full_time_interval", "test/test_elan.py::Elan::test_get_gaps_and_overlaps2", "test/test_elan.py::Elan::test_get_languages", "test/test_elan.py::Elan::test_get_lexicon_ref", "test/test_elan.py::Elan::test_get_lexicon_ref_names", "test/test_elan.py::Elan::test_get_licenses", "test/test_elan.py::Elan::test_get_linguistic_types_names", "test/test_elan.py::Elan::test_get_linked_files", "test/test_elan.py::Elan::test_get_locales", "test/test_elan.py::Elan::test_get_parameters_for_linguistic_type", "test/test_elan.py::Elan::test_get_parameters_for_tier", "test/test_elan.py::Elan::test_get_properties", "test/test_elan.py::Elan::test_get_ref_annotation_at_time", "test/test_elan.py::Elan::test_get_ref_annotation_data_between_times", "test/test_elan.py::Elan::test_get_ref_annotation_data_for_tier", "test/test_elan.py::Elan::test_get_secondary_linked_files", "test/test_elan.py::Elan::test_get_tier_ids_for_linguistic_type", "test/test_elan.py::Elan::test_get_tier_names", "test/test_elan.py::Elan::test_merge_tiers", "test/test_elan.py::Elan::test_parse_eaf", "test/test_elan.py::Elan::test_ref_get_annotation_data_after_time", "test/test_elan.py::Elan::test_ref_get_annotation_data_before_time", "test/test_elan.py::Elan::test_remove_all_annotations_from_tier", "test/test_elan.py::Elan::test_remove_annotation", "test/test_elan.py::Elan::test_remove_controlled_vocabulary", "test/test_elan.py::Elan::test_remove_cv_description", "test/test_elan.py::Elan::test_remove_cv_entry", "test/test_elan.py::Elan::test_remove_external_ref", "test/test_elan.py::Elan::test_remove_language", "test/test_elan.py::Elan::test_remove_lexicon_ref", "test/test_elan.py::Elan::test_remove_license", "test/test_elan.py::Elan::test_remove_linguistic_type", "test/test_elan.py::Elan::test_remove_linked_files", "test/test_elan.py::Elan::test_remove_locale", "test/test_elan.py::Elan::test_remove_property", "test/test_elan.py::Elan::test_remove_ref_annotation", "test/test_elan.py::Elan::test_remove_secondary_linked_files", "test/test_elan.py::Elan::test_remove_tier", "test/test_elan.py::Elan::test_remove_tiers", "test/test_elan.py::Elan::test_rename_tier", "test/test_elan.py::Elan::test_shift_annotations", "test/test_elan.py::Elan::test_to_textgrid", "test/test_elan.py::test_to_file_to_eaf[sample_2.8.eaf-EAFv2.8.xsd]", "test/test_elan.py::test_to_file_to_eaf[sample_2.7.eaf-EAFv2.8.xsd]", "test/test_elan.py::test_to_file_to_eaf[sample_3.0.eaf-EAFv3.0.xsd]", "test/test_praat.py::PraatTest::test_add_interval", "test/test_praat.py::PraatTest::test_add_point", "test/test_praat.py::PraatTest::test_add_tier", "test/test_praat.py::PraatTest::test_change_tier_name", "test/test_praat.py::PraatTest::test_clear_intervals", "test/test_praat.py::PraatTest::test_get_intervals", "test/test_praat.py::PraatTest::test_get_tier", "test/test_praat.py::PraatTest::test_get_tier_name_num", "test/test_praat.py::PraatTest::test_get_tiers", "test/test_praat.py::PraatTest::test_remove_interval", "test/test_praat.py::PraatTest::test_remove_point", "test/test_praat.py::PraatTest::test_remove_tier", "test/test_praat.py::PraatTest::test_sort_tiers", "test/test_praat.py::PraatTest::test_to_eaf", "test/test_praat.py::test_to_file[utf-8]", "test/test_praat.py::test_to_file[latin_1]", "test/test_praat.py::test_to_file[mac_roman]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-04 11:28:45+00:00
mit
1,977
dotmesh-io__dotscience-python-37
diff --git a/dotscience/__init__.py b/dotscience/__init__.py index e12da54..c2c3ac3 100644 --- a/dotscience/__init__.py +++ b/dotscience/__init__.py @@ -253,6 +253,9 @@ class Dotscience: currentRun = None def __init__(self): + self._reset() + + def _reset(self): self._mode = None self._workload_file = None self._root = os.getenv('DOTSCIENCE_PROJECT_DOT_ROOT', default=os.getcwd()) @@ -269,6 +272,7 @@ class Dotscience: # TODO: make publish etc fail if we're not connected in remote mode. if not project: raise Exception("Please specify a project name as the third argument to ds.connect()") + self._reset() self._dotmesh_client = DotmeshClient( cluster_url=hostname + "/v2/dotmesh/rpc", username=username,
dotmesh-io/dotscience-python
7e2ec1fceacd0bd8ec2517a2dd6cc9fd74a0f82a
diff --git a/dotscience/test_dotscience.py b/dotscience/test_dotscience.py index 92790c7..89ab7e9 100644 --- a/dotscience/test_dotscience.py +++ b/dotscience/test_dotscience.py @@ -857,3 +857,39 @@ def test_multi_publish_2(): assert m1["__ID"] != m2["__ID"] assert m1["start"] != m2["start"] assert m1["end"] != m2["end"] + + +def test_reconnect_resets_internal_state(monkeypatch): + class FakeDotmeshClient: + def __init__(self, cluster_url, username, api_key): + self.cluster_url = cluster_url + self.username = username + self.api_key = api_key + + def ping(self): + pass + + monkeypatch.setattr(dotscience, "DotmeshClient", FakeDotmeshClient) + + ds = dotscience.Dotscience() + ds.connect("me", "pass", "myproj", "https://example.com") + assert ds._dotmesh_client.__dict__ == { + "cluster_url": "https://example.com/v2/dotmesh/rpc", + "username": "me", + "api_key": "pass", + } + assert ds._project_name == "myproj" + + # Pretend we have a cached project: + ds._cached_project = "not empty" + assert ds._get_project_or_create("myproj") == "not empty" + + # Now, reconnect: + ds.connect("me2", "pass2", "myproj2", "https://2.example.com") + assert ds._dotmesh_client.__dict__ == { + "cluster_url": "https://2.example.com/v2/dotmesh/rpc", + "username": "me2", + "api_key": "pass2", + } + assert ds._project_name == "myproj2" + assert ds._cached_project == None
ds.connect() only connects to single project and runs overwritten [fusemachines] Fuse machines run ds.connect() from a local machine but it only connects to a single project. Also runs are getting overwritten when running on the same machine. This text is just a placeholder: it was decided on the Fuse machines call Oct 21st 4-5pm BST that they may need to do a call with the support engineer to fully explain. And/or send a video/screenshots. Link to description from Fuse Machines: https://docs.google.com/document/d/1ZLhKlW6AG3khlPVyrINXD3LaS1fSTilyEorrj66w9ow
0.0
7e2ec1fceacd0bd8ec2517a2dd6cc9fd74a0f82a
[ "dotscience/test_dotscience.py::test_reconnect_resets_internal_state" ]
[ "dotscience/test_dotscience.py::test_input_1b", "dotscience/test_dotscience.py::test_run_parameter_1", "dotscience/test_dotscience.py::test_run_output_2", "dotscience/test_dotscience.py::test_multi_publish_2", "dotscience/test_dotscience.py::test_notice_jupyter_mode", "dotscience/test_dotscience.py::test_explicit_script_name", "dotscience/test_dotscience.py::test_notice_command_mode", "dotscience/test_dotscience.py::test_label_1a", "dotscience/test_dotscience.py::test_summary_1a", "dotscience/test_dotscience.py::test_parameter_n", "dotscience/test_dotscience.py::test_run_input_n", "dotscience/test_dotscience.py::test_parameter_1a", "dotscience/test_dotscience.py::test_run_summary_1", "dotscience/test_dotscience.py::test_conflicting_mode_2", "dotscience/test_dotscience.py::test_run_input_relative", "dotscience/test_dotscience.py::test_run_input_2", "dotscience/test_dotscience.py::test_run_summary_multi", "dotscience/test_dotscience.py::test_run_basics", "dotscience/test_dotscience.py::test_output_n", "dotscience/test_dotscience.py::test_output_1a", "dotscience/test_dotscience.py::test_run_start_1", "dotscience/test_dotscience.py::test_start_end", "dotscience/test_dotscience.py::test_run_start_2", "dotscience/test_dotscience.py::test_summary_1b", "dotscience/test_dotscience.py::test_description_a", "dotscience/test_dotscience.py::test_non_conflicting_mode_2", "dotscience/test_dotscience.py::test_description_c", "dotscience/test_dotscience.py::test_conflicting_mode_1", "dotscience/test_dotscience.py::test_parameter_1b", "dotscience/test_dotscience.py::test_run_end_1", "dotscience/test_dotscience.py::test_run_input_recursive", "dotscience/test_dotscience.py::test_run_output_1", "dotscience/test_dotscience.py::test_run_labels_1", "dotscience/test_dotscience.py::test_run_labels_multi", "dotscience/test_dotscience.py::test_run_input_1", "dotscience/test_dotscience.py::test_run_output_n", "dotscience/test_dotscience.py::test_error_b", "dotscience/test_dotscience.py::test_label_1b", "dotscience/test_dotscience.py::test_input_1a", "dotscience/test_dotscience.py::test_run_null", "dotscience/test_dotscience.py::test_multi_publish_1", "dotscience/test_dotscience.py::test_output_1b", "dotscience/test_dotscience.py::test_error_a", "dotscience/test_dotscience.py::test_no_script_name_when_interactive", "dotscience/test_dotscience.py::test_label_n", "dotscience/test_dotscience.py::test_summary_n", "dotscience/test_dotscience.py::test_run_output_relative", "dotscience/test_dotscience.py::test_no_mode", "dotscience/test_dotscience.py::test_input_n", "dotscience/test_dotscience.py::test_run_tensorflow_model", "dotscience/test_dotscience.py::test_null", "dotscience/test_dotscience.py::test_run_end_2", "dotscience/test_dotscience.py::test_non_conflicting_mode_1", "dotscience/test_dotscience.py::test_run_output_recursive", "dotscience/test_dotscience.py::test_run_tensorflow_model_with_classes", "dotscience/test_dotscience.py::test_run_parameter_multi", "dotscience/test_dotscience.py::test_description_b" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-10-29 17:39:37+00:00
apache-2.0
1,978
dotpot__InAppPy-54
diff --git a/README.rst b/README.rst index 9ea1223..771796a 100644 --- a/README.rst +++ b/README.rst @@ -17,10 +17,11 @@ Table of contents 2. Installation 3. Google Play (`receipt` + `signature`) 4. Google Play (verification) -5. App Store (`receipt` + using optional `shared-secret`) -6. App Store Response (`validation_result` / `raw_response`) example -7. App Store, **asyncio** version (available in the inapppy.asyncio package) -8. Development +5. Google Play (verification with result) +6. App Store (`receipt` + using optional `shared-secret`) +7. App Store Response (`validation_result` / `raw_response`) example +8. App Store, **asyncio** version (available in the inapppy.asyncio package) +9. Development 1. Introduction @@ -88,7 +89,42 @@ In-app purchase validation library for `Apple AppStore` and `GooglePlay` (`App S return response -5. App Store (validates `receipt` using optional `shared-secret` against iTunes service) +5. Google Play verification (with result) +========================================= +Alternative to `.verify` method, instead of raising an error result class will be returned. + +.. code:: python + + from inapppy import GooglePlayVerifier, errors + + + def google_validator(receipt): + """ + Accepts receipt, validates in Google. + """ + purchase_token = receipt['purchaseToken'] + product_sku = receipt['productId'] + verifier = GooglePlayVerifier( + GOOGLE_BUNDLE_ID, + GOOGLE_SERVICE_ACCOUNT_KEY_FILE, + ) + response = {'valid': False, 'transactions': []} + + result = verifier.verify_with_result( + purchase_token, + product_sku, + is_subscription=True + ) + + # result contains data + raw_response = result.raw_response + is_canceled = result.is_canceled + is_expired = result.is_expired + + return result + + +6. App Store (validates `receipt` using optional `shared-secret` against iTunes service) ======================================================================================== .. code:: python @@ -110,7 +146,7 @@ In-app purchase validation library for `Apple AppStore` and `GooglePlay` (`App S -6. App Store Response (`validation_result` / `raw_response`) example +7. App Store Response (`validation_result` / `raw_response`) example ==================================================================== .. code:: json @@ -190,7 +226,7 @@ In-app purchase validation library for `Apple AppStore` and `GooglePlay` (`App S } -7. App Store, asyncio version (available in the inapppy.asyncio package) +8. App Store, asyncio version (available in the inapppy.asyncio package) ======================================================================== .. code:: python @@ -213,7 +249,7 @@ In-app purchase validation library for `Apple AppStore` and `GooglePlay` (`App S -8. Development +9. Development ============== .. code:: bash diff --git a/inapppy/errors.py b/inapppy/errors.py index 6436945..bad7e22 100644 --- a/inapppy/errors.py +++ b/inapppy/errors.py @@ -18,5 +18,4 @@ class InAppPyValidationError(Exception): class GoogleError(InAppPyValidationError): - def __init__(self, message: str = None, raw_response: dict = None, *args, **kwargs): - super().__init__(message, raw_response, *args, **kwargs) + pass diff --git a/inapppy/googleplay.py b/inapppy/googleplay.py index 25a849c..eee64a8 100644 --- a/inapppy/googleplay.py +++ b/inapppy/googleplay.py @@ -72,6 +72,27 @@ class GooglePlayValidator: return False +class GoogleVerificationResult: + """Google verification result class.""" + + raw_response: dict = {} + is_expired: bool = False + is_canceled: bool = False + + def __init__(self, raw_response: dict, is_expired: bool, is_canceled: bool): + self.raw_response = raw_response + self.is_expired = is_expired + self.is_canceled = is_canceled + + def __repr__(self): + return ( + f"GoogleVerificationResult(" + f"raw_response={self.raw_response}, " + f"is_expired={self.is_expired}, " + f"is_canceled={self.is_canceled})" + ) + + class GooglePlayVerifier: def __init__(self, bundle_id: str, private_key_path: str, http_timeout: int = 15) -> None: """ @@ -159,3 +180,32 @@ class GooglePlayVerifier: raise GoogleError("Purchase cancelled", result) return result + + def verify_with_result( + self, purchase_token: str, product_sku: str, is_subscription: bool = False + ) -> GoogleVerificationResult: + """Verifies by returning verification result instead of raising an error, + basically it's and better alternative to verify method.""" + service = build("androidpublisher", "v3", http=self.http) + verification_result = GoogleVerificationResult({}, False, False) + + if is_subscription: + result = self.check_purchase_subscription(purchase_token, product_sku, service) + verification_result.raw_response = result + + cancel_reason = int(result.get("cancelReason", 0)) + if cancel_reason != 0: + verification_result.is_canceled = True + + ms_timestamp = result.get("expiryTimeMillis", 0) + if self._ms_timestamp_expired(ms_timestamp): + verification_result.is_expired = True + else: + result = self.check_purchase_product(purchase_token, product_sku, service) + verification_result.raw_response = result + + purchase_state = int(result.get("purchaseState", 1)) + if purchase_state != 0: + verification_result.is_canceled = True + + return verification_result
dotpot/InAppPy
662179362b679dbd3250cc759299bd454842b6dc
diff --git a/tests/test_google_verifier.py b/tests/test_google_verifier.py index 0e213a7..ed517e2 100644 --- a/tests/test_google_verifier.py +++ b/tests/test_google_verifier.py @@ -32,6 +32,48 @@ def test_google_verify_subscription(): verifier.verify("test-token", "test-product", is_subscription=True) +def test_google_verify_with_result_subscription(): + with patch.object(googleplay, "build", return_value=None): + with patch.object(googleplay.GooglePlayVerifier, "_authorize", return_value=None): + verifier = googleplay.GooglePlayVerifier("test-bundle-id", "private_key_path", 30) + + # expired + with patch.object(verifier, "check_purchase_subscription", return_value={"expiryTimeMillis": 666}): + result = verifier.verify_with_result("test-token", "test-product", is_subscription=True) + assert result.is_canceled is False + assert result.is_expired + assert result.raw_response == {"expiryTimeMillis": 666} + assert ( + str(result) == "GoogleVerificationResult(raw_response=" + "{'expiryTimeMillis': 666}, " + "is_expired=True, " + "is_canceled=False)" + ) + + # canceled + with patch.object(verifier, "check_purchase_subscription", return_value={"cancelReason": 666}): + result = verifier.verify_with_result("test-token", "test-product", is_subscription=True) + assert result.is_canceled + assert result.is_expired + assert result.raw_response == {"cancelReason": 666} + assert ( + str(result) == "GoogleVerificationResult(" + "raw_response={'cancelReason': 666}, " + "is_expired=True, " + "is_canceled=True)" + ) + + # norm + now = datetime.datetime.utcnow().timestamp() + exp_value = now * 1000 + 10 ** 10 + with patch.object(verifier, "check_purchase_subscription", return_value={"expiryTimeMillis": exp_value}): + result = verifier.verify_with_result("test-token", "test-product", is_subscription=True) + assert result.is_canceled is False + assert result.is_expired is False + assert result.raw_response == {"expiryTimeMillis": exp_value} + assert str(result) is not None + + def test_google_verify_product(): with patch.object(googleplay, "build", return_value=None): with patch.object(googleplay.GooglePlayVerifier, "_authorize", return_value=None): @@ -47,6 +89,33 @@ def test_google_verify_product(): verifier.verify("test-token", "test-product") +def test_google_verify_with_result_product(): + with patch.object(googleplay, "build", return_value=None): + with patch.object(googleplay.GooglePlayVerifier, "_authorize", return_value=None): + verifier = googleplay.GooglePlayVerifier("test-bundle-id", "private_key_path", 30) + + # purchase + with patch.object(verifier, "check_purchase_product", return_value={"purchaseState": 0}): + result = verifier.verify_with_result("test-token", "test-product") + assert result.is_canceled is False + assert result.is_expired is False + assert result.raw_response == {"purchaseState": 0} + assert str(result) is not None + + # cancelled + with patch.object(verifier, "check_purchase_product", return_value={"purchaseState": 1}): + result = verifier.verify_with_result("test-token", "test-product") + assert result.is_canceled + assert result.is_expired is False + assert result.raw_response == {"purchaseState": 1} + assert ( + str(result) == "GoogleVerificationResult(" + "raw_response={'purchaseState': 1}, " + "is_expired=False, " + "is_canceled=True)" + ) + + DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
cancelled android purchases do not get caught correctly in lines 109-110 of googleplay.py: ``` cancel_reason = int(result.get('cancelReason', 0)) if cancel_reason != 0: raise GoogleError('Subscription is canceled', result) ``` If we look at [the docs](https://developers.google.com/android-publisher/api-ref/purchases/subscriptions) we see that a value of `cancelReason = 0` also indicates cancellation by user. Therefore I do not understand what was the original intention of this snippet of code. If we look at the lines following this snippet: ``` ms_timestamp = result.get('expiryTimeMillis', 0) if self._ms_timestamp_expired(ms_timestamp): raise GoogleError('Subscription expired', result) else: result = self.check_purchase_product(purchase_token, product_sku, service) purchase_state = int(result.get('purchaseState', 1)) if purchase_state != 0: raise GoogleError('Purchase cancelled', result) ``` I think the general issue here is, that a subscription can be a) not cancelled and not expired b) cancelled and not expired c) cancelled and expired So even if we fixed the issue with the code above, we would have to rethink how we throw errors / catch google certificate expiry (see also #25). I suggest we remove the current mechanism of throwing errors an instead return some sort of datastructure containing: `raw_response`, `is_expired`, `is_cancelled`. That way we describe all 3 scenarios above. What do you think?
0.0
662179362b679dbd3250cc759299bd454842b6dc
[ "tests/test_google_verifier.py::test_google_verify_with_result_subscription", "tests/test_google_verifier.py::test_google_verify_with_result_product" ]
[ "tests/test_google_verifier.py::test_google_verify_subscription", "tests/test_google_verifier.py::test_google_verify_product", "tests/test_google_verifier.py::test_bad_request_subscription", "tests/test_google_verifier.py::test_bad_request_product" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-07-25 13:24:02+00:00
mit
1,979
dougthor42__pynuget-41
diff --git a/CHANGELOG.md b/CHANGELOG.md index 464e237..4caff42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ + Optionally run coverage when running in localhost development. + Fixed an issue where files with dependencies would break the "List" nuget command (#39) ++ Fixed an issue where deleting the last remaining version of a package + would not delete the row in the Package table, thus causing subsequet pushes + of the same version to fail. (#38) ## 0.2.1 (2018-07-25) diff --git a/src/pynuget/db.py b/src/pynuget/db.py index cb7caf7..668c652 100644 --- a/src/pynuget/db.py +++ b/src/pynuget/db.py @@ -73,7 +73,7 @@ class Version(Base): package = relationship("Package", backref="versions") def __repr__(self): - return "<Version({}, {})>".format(self.package.name, self.version) + return "<Version({}, {}, {})>".format(self.version_id, self.package.name, self.version) @hybrid_property def thing(self): @@ -330,18 +330,19 @@ def delete_version(session, package_name, version): .filter(Package.name == package_name) .filter(Version.version == version) ) - package = sql.one().package - logger.debug(package) + version = sql.one() + pkg = version.package - session.delete(sql.one()) - session.commit() + session.delete(version) # update the Package.latest_version value, or delete the Package versions = (session.query(Version) + .join(Package) .filter(Package.name == package_name) ).all() if len(versions) > 0: - package.latest_version = max(v.version for v in versions) + pkg.latest_version = max(v.version for v in versions) else: - session.delete(package) + logger.info("No more versions exist. Deleting package %s" % pkg) + session.delete(pkg) session.commit()
dougthor42/pynuget
4540549e0118c1e044799f2c8df5e48223216703
diff --git a/tests/test_db.py b/tests/test_db.py index 9f31f43..e2f4fb5 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -150,22 +150,46 @@ def test_insert_version(session): def test_delete_version(session): + # Add additional dummy data. + pkg = db.Package(name="Foo", latest_version="0.9.6") + session.add(pkg) + session.commit() + + session.add(db.Version(package_id=pkg.package_id, version="0.9.6")) + session.add(db.Version(package_id=pkg.package_id, version="0.9.7")) + session.commit() + + # The package we're interested in. + pkg_id = 'dummy' + # get our initial counts - version_count = session.query(sa.func.count(db.Version.version_id)) + version_count = (session.query(sa.func.count(db.Version.version_id)) + .join(db.Package) + .filter(db.Package.name == pkg_id)) package_count = session.query(sa.func.count(db.Package.package_id)) initial_version_count = version_count.scalar() initial_package_count = package_count.scalar() - # Delete a version - pkg_id = 'dummy' db.delete_version(session, pkg_id, '0.0.2') + # The number of versions for our package should have decreased by 1. assert initial_version_count - 1 == version_count.scalar() + + # We should still have 2 packages + assert initial_package_count == 2 assert initial_package_count == package_count.scalar() + + # The deleted version should not show up at all. (Note this particular + # test only works because our dummy data only has 1 instance of "0.0.2") assert '0.0.2' not in session.query(db.Version.version).all() - # twice more, the 2nd of which should delete the package + # Deleting the highest version should change the `latest_version` value + qry = session.query(db.Package).filter(db.Package.name == 'dummy') db.delete_version(session, pkg_id, '0.0.3') + assert qry.one().latest_version == '0.0.1' + + # Deleting the last version of a package should remove the row from the + # Packages table. db.delete_version(session, pkg_id, '0.0.1') assert version_count.scalar() == 0 - assert package_count.scalar() == 0 + assert package_count.scalar() == 1
Deleting the last version of a package does not delete the entry in the "package" table. Deleting the last version of a package does not delete the entry in the "package" table. Steps to reproduce: 1. Upload `foo.0.0.1.nupkg` 2. Delete `foo.0.0.2.nupkg` 3. Attempt to upload `foo.0.0.1.nupkg` again 4. See that you get a 'package already exists' error. 5. View the sqlite file. table package contains 'foo' while table version does not.
0.0
4540549e0118c1e044799f2c8df5e48223216703
[ "tests/test_db.py::test_delete_version" ]
[ "tests/test_db.py::test_count_packages", "tests/test_db.py::test_search_packages", "tests/test_db.py::test_package_updates", "tests/test_db.py::test_find_by_pkg_name", "tests/test_db.py::test_validate_id_and_version", "tests/test_db.py::test_increment_download_count", "tests/test_db.py::test_insert_or_update_package", "tests/test_db.py::test_insert_version" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-07-26 22:21:10+00:00
mit
1,980
dpkp__kafka-python-1507
diff --git a/kafka/cluster.py b/kafka/cluster.py index 45f25ad..8078eb7 100644 --- a/kafka/cluster.py +++ b/kafka/cluster.py @@ -214,7 +214,8 @@ class ClusterMetadata(object): return self.failed_update(error) if not metadata.brokers: - log.warning("No broker metadata found in MetadataResponse") + log.warning("No broker metadata found in MetadataResponse -- ignoring.") + return self.failed_update(Errors.MetadataEmptyBrokerList(metadata)) _new_brokers = {} for broker in metadata.brokers: diff --git a/kafka/conn.py b/kafka/conn.py index f67edfb..a2d5ee6 100644 --- a/kafka/conn.py +++ b/kafka/conn.py @@ -292,11 +292,7 @@ class BrokerConnection(object): # First attempt to perform dns lookup # note that the underlying interface, socket.getaddrinfo, # has no explicit timeout so we may exceed the user-specified timeout - while time.time() < timeout: - if self._dns_lookup(): - break - else: - return False + self._dns_lookup() # Loop once over all returned dns entries selector = None @@ -903,6 +899,7 @@ class BrokerConnection(object): Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ... """ + timeout_at = time.time() + timeout log.info('Probing node %s broker version', self.node_id) # Monkeypatch some connection configurations to avoid timeouts override_config = { @@ -932,7 +929,7 @@ class BrokerConnection(object): ] for version, request in test_cases: - if not self.connect_blocking(timeout): + if not self.connect_blocking(timeout_at - time.time()): raise Errors.NodeNotReadyError() f = self.send(request) # HACK: sleeping to wait for socket to send bytes diff --git a/kafka/errors.py b/kafka/errors.py index f4c8740..93a9f40 100644 --- a/kafka/errors.py +++ b/kafka/errors.py @@ -54,6 +54,10 @@ class StaleMetadata(KafkaError): invalid_metadata = True +class MetadataEmptyBrokerList(KafkaError): + retriable = True + + class UnrecognizedBrokerVersion(KafkaError): pass
dpkp/kafka-python
c9d783a8211337205bc90c27d1f67beb65ac5d9e
diff --git a/test/test_cluster.py b/test/test_cluster.py new file mode 100644 index 0000000..f010c4f --- /dev/null +++ b/test/test_cluster.py @@ -0,0 +1,22 @@ +# pylint: skip-file +from __future__ import absolute_import + +import pytest + +from kafka.cluster import ClusterMetadata +from kafka.protocol.metadata import MetadataResponse + + +def test_empty_broker_list(): + cluster = ClusterMetadata() + assert len(cluster.brokers()) == 0 + + cluster.update_metadata(MetadataResponse[0]( + [(0, 'foo', 12), (1, 'bar', 34)], [])) + assert len(cluster.brokers()) == 2 + + # empty broker list response should be ignored + cluster.update_metadata(MetadataResponse[0]( + [], # empty brokers + [(17, 'foo', []), (17, 'bar', [])])) # topics w/ error + assert len(cluster.brokers()) == 2
Invalid bootstrap servers list blocks during startup ```python >>> kafka.KafkaProducer(bootstrap_servers='can-not-resolve:9092') # never returns ```
0.0
c9d783a8211337205bc90c27d1f67beb65ac5d9e
[ "test/test_cluster.py::test_empty_broker_list" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-25 07:16:51+00:00
apache-2.0
1,981
dr-prodigy__python-holidays-1087
diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 5d982e6a..b1b98965 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -100,7 +100,7 @@ jobs: name: dist path: dist - name: Publish Package - uses: pypa/[email protected] + uses: pypa/[email protected] with: user: __token__ password: ${{ secrets.pypi_password }} diff --git a/holidays/__init__.py b/holidays/__init__.py index bc268a05..294c676e 100644 --- a/holidays/__init__.py +++ b/holidays/__init__.py @@ -10,9 +10,12 @@ # License: MIT (see LICENSE file) from holidays.constants import * -from holidays.countries import * -from holidays.financial import * from holidays.holiday_base import * +from holidays.registry import EntityLoader from holidays.utils import * __version__ = "0.25" + + +EntityLoader.load("countries", globals()) +EntityLoader.load("financial", globals()) diff --git a/holidays/registry.py b/holidays/registry.py new file mode 100644 index 00000000..ca8ee397 --- /dev/null +++ b/holidays/registry.py @@ -0,0 +1,257 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +import importlib +from typing import Any, Dict, Iterable, Optional, Tuple, Union + +from holidays.holiday_base import HolidayBase + +RegistryDict = Dict[str, Tuple[str, ...]] + +COUNTRIES: RegistryDict = { + "albania": ("Albania", "AL", "ALB"), + "american_samoa": ("AmericanSamoa", "AS", "ASM", "HolidaysAS"), + "andorra": ("Andorra", "AD", "AND"), + "angola": ("Angola", "AO", "AGO"), + "argentina": ("Argentina", "AR", "ARG"), + "armenia": ("Armenia", "AM", "ARM"), + "aruba": ("Aruba", "AW", "ABW"), + "australia": ("Australia", "AU", "AUS"), + "austria": ("Austria", "AT", "AUT"), + "azerbaijan": ("Azerbaijan", "AZ", "AZE"), + "bahrain": ("Bahrain", "BH", "BAH"), + "bangladesh": ("Bangladesh", "BD", "BGD"), + "belarus": ("Belarus", "BY", "BLR"), + "belgium": ("Belgium", "BE", "BEL"), + "bolivia": ("Bolivia", "BO", "BOL"), + "bosnia_and_herzegovina": ("BosniaAndHerzegovina", "BA", "BIH"), + "botswana": ("Botswana", "BW", "BWA"), + "brazil": ("Brazil", "BR", "BRA"), + "bulgaria": ("Bulgaria", "BG", "BLG"), + "burundi": ("Burundi", "BI", "BDI"), + "canada": ("Canada", "CA", "CAN"), + "chile": ("Chile", "CL", "CHL"), + "china": ("China", "CN", "CHN"), + "colombia": ("Colombia", "CO", "COL"), + "costa_rica": ("CostaRica", "CR", "CRI"), + "croatia": ("Croatia", "HR", "HRV"), + "cuba": ("Cuba", "CU", "CUB"), + "curacao": ("Curacao", "CW", "CUW"), + "cyprus": ("Cyprus", "CY", "CYP"), + "czechia": ("Czechia", "CZ", "CZE"), + "denmark": ("Denmark", "DK", "DNK"), + "djibouti": ("Djibouti", "DJ", "DJI"), + "dominican_republic": ("DominicanRepublic", "DO", "DOM"), + "ecuador": ("Ecuador", "EC", "ECU"), + "egypt": ("Egypt", "EG", "EGY"), + "estonia": ("Estonia", "EE", "EST"), + "eswatini": ("Eswatini", "SZ", "SZW", "Swaziland"), + "ethiopia": ("Ethiopia", "ET", "ETH"), + "finland": ("Finland", "FI", "FIN"), + "france": ("France", "FR", "FRA"), + "georgia": ("Georgia", "GE", "GEO"), + "germany": ("Germany", "DE", "DEU"), + "greece": ("Greece", "GR", "GRC"), + "guam": ("Guam", "GU", "GUM", "HolidaysGU"), + "honduras": ("Honduras", "HN", "HND"), + "hongkong": ("HongKong", "HK", "HKG"), + "hungary": ("Hungary", "HU", "HUN"), + "iceland": ("Iceland", "IS", "ISL"), + "india": ("India", "IN", "IND"), + "indonesia": ("Indonesia", "ID", "IDN"), + "ireland": ("Ireland", "IE", "IRL"), + "isle_of_man": ("IsleOfMan", "IM", "IMN"), + "israel": ("Israel", "IL", "ISR"), + "italy": ("Italy", "IT", "ITA"), + "jamaica": ("Jamaica", "JM", "JAM"), + "japan": ("Japan", "JP", "JPN"), + "kazakhstan": ("Kazakhstan", "KZ", "KAZ"), + "kenya": ("Kenya", "KE", "KEN"), + "kyrgyzstan": ("Kyrgyzstan", "KG", "KGZ"), + "latvia": ("Latvia", "LV", "LVA"), + "lesotho": ("Lesotho", "LS", "LSO"), + "liechtenstein": ("Liechtenstein", "LI", "LIE"), + "lithuania": ("Lithuania", "LT", "LTU"), + "luxembourg": ("Luxembourg", "LU", "LUX"), + "madagascar": ("Madagascar", "MG", "MDG"), + "malawi": ("Malawi", "MW", "MWI"), + "malaysia": ("Malaysia", "MY", "MYS"), + "malta": ("Malta", "MT", "MLT"), + "marshall_islands": ("MarshallIslands", "MH", "MHL", "HolidaysMH"), + "mexico": ("Mexico", "MX", "MEX"), + "moldova": ("Moldova", "MD", "MDA"), + "monaco": ("Monaco", "MC", "MCO"), + "montenegro": ("Montenegro", "ME", "MNE"), + "morocco": ("Morocco", "MA", "MOR"), + "mozambique": ("Mozambique", "MZ", "MOZ"), + "namibia": ("Namibia", "NA", "NAM"), + "netherlands": ("Netherlands", "NL", "NLD"), + "new_zealand": ("NewZealand", "NZ", "NZL"), + "nicaragua": ("Nicaragua", "NI", "NIC"), + "nigeria": ("Nigeria", "NG", "NGA"), + "north_macedonia": ("NorthMacedonia", "MK", "MKD"), + "northern_mariana_islands": ( + "NorthernMarianaIslands", + "MP", + "MNP", + "HolidaysMP", + ), + "norway": ("Norway", "NO", "NOR"), + "pakistan": ("Pakistan", "PK", "PAK"), + "panama": ("Panama", "PA", "PAN"), + "paraguay": ("Paraguay", "PY", "PRY"), + "peru": ("Peru", "PE", "PER"), + "philippines": ("Philippines", "PH", "PHL"), + "poland": ("Poland", "PL", "POL"), + "portugal": ("Portugal", "PT", "PRT"), + "puerto_rico": ("PuertoRico", "PR", "PRI", "HolidaysPR"), + "romania": ("Romania", "RO", "ROU"), + "russia": ("Russia", "RU", "RUS"), + "san_marino": ("SanMarino", "SM", "SMR"), + "saudi_arabia": ("SaudiArabia", "SA", "SAU"), + "serbia": ("Serbia", "RS", "SRB"), + "singapore": ("Singapore", "SG", "SGP"), + "slovakia": ("Slovakia", "SK", "SVK"), + "slovenia": ("Slovenia", "SI", "SVN"), + "south_africa": ("SouthAfrica", "ZA", "ZAF"), + "south_korea": ("SouthKorea", "KR", "KOR", "Korea"), + "spain": ("Spain", "ES", "ESP"), + "sweden": ("Sweden", "SE", "SWE"), + "switzerland": ("Switzerland", "CH", "CHE"), + "taiwan": ("Taiwan", "TW", "TWN"), + "thailand": ("Thailand", "TH", "THA"), + "tunisia": ("Tunisia", "TN", "TUN"), + "turkey": ("Turkey", "TR", "TUR"), + "ukraine": ("Ukraine", "UA", "UKR"), + "united_arab_emirates": ("UnitedArabEmirates", "AE", "ARE"), + "united_kingdom": ("UnitedKingdom", "GB", "GBR", "UK"), + "united_states_minor_outlying_islands": ( + "UnitedStatesMinorOutlyingIslands", + "UM", + "UMI", + "HolidaysUM", + ), + "united_states_virgin_islands": ( + "UnitedStatesVirginIslands", + "VI", + "VIR", + "HolidaysVI", + ), + "united_states": ("UnitedStates", "US", "USA"), + "uruguay": ("Uruguay", "UY", "URY"), + "uzbekistan": ("Uzbekistan", "UZ", "UZB"), + "vatican_city": ("VaticanCity", "VA", "VAT"), + "venezuela": ("Venezuela", "VE", "VEN"), + "vietnam": ("Vietnam", "VN", "VNM"), + "zambia": ("Zambia", "ZM", "ZMB"), + "zimbabwe": ("Zimbabwe", "ZW", "ZWE"), +} + +FINANCIAL: RegistryDict = { + "european_central_bank": ("EuropeanCentralBank", "ECB", "TAR"), + "ny_stock_exchange": ("NewYorkStockExchange", "NYSE", "XNYS"), +} + + +class EntityLoader: + """Country and financial holidays entities lazy loader.""" + + __slots__ = ("entity", "entity_name", "module_name") + + def __init__(self, path: str, *args, **kwargs) -> None: + """Set up a lazy loader.""" + self.entity = None + + entity_path = path.split(".") + self.entity_name = entity_path[-1] + self.module_name = ".".join(entity_path[0:-1]) + + super().__init__(*args, **kwargs) + + def __call__(self, *args, **kwargs) -> HolidayBase: + """Create a new instance of a lazy-loaded entity.""" + cls = self.get_entity() + return cls(*args, **kwargs) # type: ignore[misc, operator] + + def __getattr__(self, name: str) -> Optional[Any]: + """Return attribute of a lazy-loaded entity.""" + cls = self.get_entity() + return getattr(cls, name) + + def __str__(self) -> str: + """Return lazy loader object string representation.""" + return ( + f"A lazy loader for {self.get_entity()}. For inheritance please " + f"use the '{self.module_name}.{self.entity_name}' class directly." + ) + + def get_entity(self) -> Optional[HolidayBase]: + """Return lazy-loaded entity.""" + if self.entity is None: + self.entity = getattr( + importlib.import_module(self.module_name), + self.entity_name, + ) + + return self.entity + + @staticmethod + def _get_entity_codes( + container: RegistryDict, + entity_length: Union[int, Iterable[int]], + include_aliases: bool = True, + ) -> Iterable[str]: + entity_length = ( + {entity_length} + if isinstance(entity_length, int) + else set(entity_length) + ) + for entities in container.values(): + for entity in entities: + if len(entity) in entity_length: + yield entity + # Assuming that the alpha-2 code goes first. + if not include_aliases: + break + + @staticmethod + def get_country_codes(include_aliases: bool = True) -> Iterable[str]: + """Get supported country codes. + + :param include_aliases: + Whether to include entity aliases (e.g. UK for GB). + """ + return EntityLoader._get_entity_codes(COUNTRIES, 2, include_aliases) + + @staticmethod + def get_financial_codes(include_aliases: bool = True) -> Iterable[str]: + """Get supported financial codes. + + :param include_aliases: + Whether to include entity aliases(e.g. TAR for ECB, XNYS for NYSE). + """ + return EntityLoader._get_entity_codes( + FINANCIAL, (3, 4), include_aliases + ) + + @staticmethod + def load(prefix: str, scope: Dict) -> None: + """Load country or financial entities.""" + entity_mapping = COUNTRIES if prefix == "countries" else FINANCIAL + for module, entities in entity_mapping.items(): + scope.update( + { + entity: EntityLoader( + f"holidays.{prefix}.{module}.{entity}" + ) + for entity in entities + } + ) diff --git a/holidays/utils.py b/holidays/utils.py index 0c527f8e..8df9d96a 100755 --- a/holidays/utils.py +++ b/holidays/utils.py @@ -17,13 +17,12 @@ __all__ = ( "list_supported_financial", ) -import inspect import warnings from functools import lru_cache from typing import Dict, Iterable, List, Optional, Union -from holidays import countries, financial from holidays.holiday_base import HolidayBase +from holidays.registry import EntityLoader def country_holidays( @@ -176,8 +175,10 @@ def country_holidays( :class:`HolidayBase` class and define your own :meth:`_populate` method. See documentation for examples. """ + import holidays + try: - return getattr(countries, country)( + return getattr(holidays, country)( years=years, subdiv=subdiv, expand=expand, @@ -238,8 +239,10 @@ def financial_holidays( See :py:func:`country_holidays` documentation for further details and examples. """ + import holidays + try: - return getattr(financial, market)( + return getattr(holidays, market)( years=years, subdiv=subdiv, expand=expand, @@ -286,10 +289,11 @@ def list_supported_countries(include_aliases=True) -> Dict[str, List[str]]: A dictionary where the key is the ISO 3166-1 Alpha-2 country codes and the value is a list of supported subdivision codes. """ + import holidays + return { - name if include_aliases else cls.country: list(cls.subdivisions) - for name, cls in inspect.getmembers(countries, inspect.isclass) - if len(name) == 2 and issubclass(cls, HolidayBase) + country_code: list(getattr(holidays, country_code).subdivisions) + for country_code in EntityLoader.get_country_codes(include_aliases) } @@ -305,8 +309,9 @@ def list_supported_financial(include_aliases=True) -> Dict[str, List[str]]: A dictionary where the key is the market codes and the value is a list of supported subdivision codes. """ + import holidays + return { - name if include_aliases else cls.market: list(cls.subdivisions) - for name, cls in inspect.getmembers(financial, inspect.isclass) - if len(name) in {3, 4} and issubclass(cls, HolidayBase) + financial_code: list(getattr(holidays, financial_code).subdivisions) + for financial_code in EntityLoader.get_financial_codes(include_aliases) }
dr-prodigy/python-holidays
773afed052a3286cfc7a948ce7db2c626c061129
diff --git a/tests/test_holiday_base.py b/tests/test_holiday_base.py index 5d4af3e9..7bfa8ae4 100644 --- a/tests/test_holiday_base.py +++ b/tests/test_holiday_base.py @@ -20,7 +20,7 @@ from dateutil.relativedelta import MO from dateutil.relativedelta import relativedelta as rd import holidays -from holidays.constants import JAN, FEB, MON, TUE, SAT, SUN +from holidays.constants import JAN, FEB, OCT, MON, TUE, SAT, SUN class TestBasics(unittest.TestCase): @@ -449,10 +449,10 @@ class TestBasics(unittest.TestCase): self.assertRaises(TypeError, lambda: 1 + holidays.US()) def test_inheritance(self): - class NoColumbusHolidays(holidays.US): + class NoColumbusHolidays(holidays.countries.US): def _populate(self, year): - holidays.US._populate(self, year) - self.pop(date(year, 10, 1) + rd(weekday=MO(+2))) + super()._populate(year) + self.pop(date(year, OCT, 1) + rd(weekday=MO(+2))) hdays = NoColumbusHolidays() self.assertIn(date(2014, 10, 13), self.holidays) @@ -462,9 +462,9 @@ class TestBasics(unittest.TestCase): self.assertNotIn(date(2020, 10, 12), hdays) self.assertIn(date(2020, 1, 1), hdays) - class NinjaTurtlesHolidays(holidays.US): + class NinjaTurtlesHolidays(holidays.countries.US): def _populate(self, year): - holidays.US._populate(self, year) + super()._populate(year) self[date(year, 7, 13)] = "Ninja Turtle's Day" hdays = NinjaTurtlesHolidays() diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 00000000..66b93f6f --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,112 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +import importlib +import inspect +import warnings +from unittest import TestCase + +from holidays import countries, financial, registry + + +class TestEntityLoader(TestCase): + # TODO(ark): consider running this just once for the latest Python version. + def test_countries_imports(self): + warnings.simplefilter("ignore") + + import holidays + + loader_entities = set() + for module, entities in registry.COUNTRIES.items(): + module = importlib.import_module(f"holidays.countries.{module}") + for entity in entities: + countries_cls = getattr(countries, entity) + loader_cls = getattr(holidays, entity) + module_cls = getattr(module, entity) + + self.assertIsNotNone(countries_cls, entity) + self.assertIsNotNone(loader_cls, entity) + self.assertIsNotNone(module_cls, entity) + self.assertEqual(countries_cls, module_cls) + self.assertTrue(isinstance(loader_cls, registry.EntityLoader)) + self.assertTrue(isinstance(loader_cls(), countries_cls)) + self.assertTrue(isinstance(loader_cls(), module_cls)) + + loader_entities.add(loader_cls.__name__) + + countries_entities = set( + entity[0] + for entity in inspect.getmembers(countries, inspect.isclass) + ) + self.assertEqual( + countries_entities, + loader_entities, + "Registry entities and countries entities don't match: %s" + % countries_entities.difference(loader_entities), + ) + + def test_country_str(self): + self.assertEqual( + str( + registry.EntityLoader( + "holidays.countries.united_states.US", + ) + ), + "A lazy loader for <class 'holidays.countries.united_states.US'>. " + "For inheritance please use the " + "'holidays.countries.united_states.US' class directly.", + ) + + # TODO(ark): consider running this just once for the latest Python version. + def test_financial_imports(self): + import holidays + + loader_entities = set() + for module, entities in registry.FINANCIAL.items(): + module = importlib.import_module(f"holidays.financial.{module}") + for entity in entities: + financial_cls = getattr(financial, entity) + loader_cls = getattr(holidays, entity) + module_cls = getattr(module, entity) + + self.assertIsNotNone(financial_cls, entity) + self.assertIsNotNone(loader_cls, entity) + self.assertIsNotNone(module_cls, entity) + self.assertEqual(financial_cls, module_cls) + self.assertTrue(isinstance(loader_cls, registry.EntityLoader)) + self.assertTrue(isinstance(loader_cls(), financial_cls)) + self.assertTrue(isinstance(loader_cls(), module_cls)) + + loader_entities.add(loader_cls.__name__) + + financial_entities = set( + entity[0] + for entity in inspect.getmembers(financial, inspect.isclass) + ) + self.assertEqual( + financial_entities, + loader_entities, + "Registry entities and financial entities don't match: %s" + % financial_entities.difference(loader_entities), + ) + + def test_financial_str(self): + self.assertEqual( + str( + registry.EntityLoader( + "holidays.financial.ny_stock_exchange.NYSE" + ) + ), + "A lazy loader for " + "<class 'holidays.financial.ny_stock_exchange.NYSE'>. " + "For inheritance please use the " + "'holidays.financial.ny_stock_exchange.NYSE' class directly.", + )
Maximize load performance We advertise this library as "fast, efficient", and is performance or memory footprint affected by loading every single class for every single country (that's 360+ classes) even when the user needs holidays only for a single country, which I assume this to be 90%+ of use cases, or just a few countries? What about on small footprints (e.g. Raspberry Pi)? I would assume so, but am not very familiar with Python innards. If so, are there architectures that we can implement to maximize load performance especially when only one (or a few) countries are needed? _Originally posted by @mborsetti in https://github.com/dr-prodigy/python-holidays/issues/948#issuecomment-1432382359_
0.0
773afed052a3286cfc7a948ce7db2c626c061129
[ "tests/test_holiday_base.py::TestBasics::test_add_countries", "tests/test_holiday_base.py::TestBasics::test_add_financial", "tests/test_holiday_base.py::TestBasics::test_add_holiday", "tests/test_holiday_base.py::TestBasics::test_append", "tests/test_holiday_base.py::TestBasics::test_contains", "tests/test_holiday_base.py::TestBasics::test_copy", "tests/test_holiday_base.py::TestBasics::test_eq_", "tests/test_holiday_base.py::TestBasics::test_get", "tests/test_holiday_base.py::TestBasics::test_get_list", "tests/test_holiday_base.py::TestBasics::test_get_named_contains", "tests/test_holiday_base.py::TestBasics::test_get_named_exact", "tests/test_holiday_base.py::TestBasics::test_get_named_icontains", "tests/test_holiday_base.py::TestBasics::test_get_named_iexact", "tests/test_holiday_base.py::TestBasics::test_get_named_istartswith", "tests/test_holiday_base.py::TestBasics::test_get_named_lookup_invalid", "tests/test_holiday_base.py::TestBasics::test_get_named_startswith", "tests/test_holiday_base.py::TestBasics::test_getitem", "tests/test_holiday_base.py::TestBasics::test_inheritance", "tests/test_holiday_base.py::TestBasics::test_is_leap_year", "tests/test_holiday_base.py::TestBasics::test_is_weekend", "tests/test_holiday_base.py::TestBasics::test_ne", "tests/test_holiday_base.py::TestBasics::test_pop", "tests/test_holiday_base.py::TestBasics::test_pop_named", "tests/test_holiday_base.py::TestBasics::test_radd", "tests/test_holiday_base.py::TestBasics::test_repr_country", "tests/test_holiday_base.py::TestBasics::test_repr_market", "tests/test_holiday_base.py::TestBasics::test_setitem", "tests/test_holiday_base.py::TestBasics::test_str_country", "tests/test_holiday_base.py::TestBasics::test_str_market", "tests/test_holiday_base.py::TestBasics::test_update", "tests/test_holiday_base.py::TestArgs::test_country", "tests/test_holiday_base.py::TestArgs::test_deprecation_warnings", "tests/test_holiday_base.py::TestArgs::test_expand", "tests/test_holiday_base.py::TestArgs::test_observed", "tests/test_holiday_base.py::TestArgs::test_serialization", "tests/test_holiday_base.py::TestArgs::test_years", "tests/test_holiday_base.py::TestKeyTransforms::test_dates", "tests/test_holiday_base.py::TestKeyTransforms::test_datetimes", "tests/test_holiday_base.py::TestKeyTransforms::test_exceptions", "tests/test_holiday_base.py::TestKeyTransforms::test_strings", "tests/test_holiday_base.py::TestKeyTransforms::test_timestamp", "tests/test_holiday_base.py::TestCountryHolidayDeprecation::test_deprecation", "tests/test_holiday_base.py::TestCountrySpecialHolidays::test_populate_special_holidays", "tests/test_holiday_base.py::TestHolidaysTranslation::test_language_unavailable", "tests/test_registry.py::TestEntityLoader::test_countries_imports", "tests/test_registry.py::TestEntityLoader::test_country_str", "tests/test_registry.py::TestEntityLoader::test_financial_imports", "tests/test_registry.py::TestEntityLoader::test_financial_str" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-04-07 17:51:48+00:00
mit
1,982
dr-prodigy__python-holidays-1257
diff --git a/holidays/countries/greece.py b/holidays/countries/greece.py index 28b24919..fae02e99 100644 --- a/holidays/countries/greece.py +++ b/holidays/countries/greece.py @@ -9,13 +9,12 @@ # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) -from datetime import date from datetime import timedelta as td from gettext import gettext as tr from holidays.calendars import _get_nth_weekday_from, JULIAN_CALENDAR from holidays.calendars import GREGORIAN_CALENDAR -from holidays.constants import MAR, MAY, OCT, MON +from holidays.constants import MAR, OCT, MON from holidays.holiday_base import HolidayBase from holidays.holiday_groups import ChristianHolidays, InternationalHolidays @@ -52,6 +51,9 @@ class Greece(HolidayBase, ChristianHolidays, InternationalHolidays): # Independence Day. self._add_holiday(tr("Εικοστή Πέμπτη Μαρτίου"), MAR, 25) + # Good Friday. + self._add_good_friday(tr("Μεγάλη Παρασκευή")) + # Easter Monday. self._add_easter_monday(tr("Δευτέρα του Πάσχα")) @@ -62,8 +64,7 @@ class Greece(HolidayBase, ChristianHolidays, InternationalHolidays): name = self.tr("Εργατική Πρωτομαγιά") name_observed = self.tr("%s (παρατηρήθηκε)") - dt = date(year, MAY, 1) - self._add_holiday(name, dt) + dt = self._add_labor_day(name) if self.observed and self._is_weekend(dt): # https://en.wikipedia.org/wiki/Public_holidays_in_Greece labour_day_observed_date = _get_nth_weekday_from(1, MON, dt) diff --git a/holidays/locale/el/LC_MESSAGES/GR.po b/holidays/locale/el/LC_MESSAGES/GR.po index 78316365..11ba671e 100644 --- a/holidays/locale/el/LC_MESSAGES/GR.po +++ b/holidays/locale/el/LC_MESSAGES/GR.po @@ -3,10 +3,10 @@ # msgid "" msgstr "" -"Project-Id-Version: Python Holidays 0.20\n" -"POT-Creation-Date: 2023-02-15 14:53-0800\n" -"PO-Revision-Date: 2023-02-16 08:50-0800\n" -"Last-Translator: Arkadii Yakovets <[email protected]>\n" +"Project-Id-Version: Python Holidays 0.26\n" +"POT-Creation-Date: 2023-06-01 17:41+0300\n" +"PO-Revision-Date: 2023-06-01 17:43+0300\n" +"Last-Translator: ~Jhellico <[email protected]>\n" "Language-Team: Python Holidays localization team\n" "Language: el\n" "MIME-Version: 1.0\n" @@ -16,60 +16,65 @@ msgstr "" "X-Generator: Poedit 3.2.2\n" #. New Year's Day. -#: ./holidays/countries/greece.py:44 +#: ./holidays/countries/greece.py:43 msgid "Πρωτοχρονιά" msgstr "" #. Epiphany. -#: ./holidays/countries/greece.py:47 +#: ./holidays/countries/greece.py:46 msgid "Θεοφάνεια" msgstr "" #. Clean Monday. -#: ./holidays/countries/greece.py:50 +#: ./holidays/countries/greece.py:49 msgid "Καθαρά Δευτέρα" msgstr "" #. Independence Day. -#: ./holidays/countries/greece.py:53 +#: ./holidays/countries/greece.py:52 msgid "Εικοστή Πέμπτη Μαρτίου" msgstr "" +#. Good Friday. +#: ./holidays/countries/greece.py:55 +msgid "Μεγάλη Παρασκευή" +msgstr "" + #. Easter Monday. -#: ./holidays/countries/greece.py:56 +#: ./holidays/countries/greece.py:58 msgid "Δευτέρα του Πάσχα" msgstr "" #. Monday of the Holy Spirit. -#: ./holidays/countries/greece.py:59 +#: ./holidays/countries/greece.py:61 msgid "Δευτέρα του Αγίου Πνεύματος" msgstr "" #. Labour Day. -#: ./holidays/countries/greece.py:62 +#: ./holidays/countries/greece.py:64 msgid "Εργατική Πρωτομαγιά" msgstr "" -#: ./holidays/countries/greece.py:63 +#: ./holidays/countries/greece.py:65 #, c-format msgid "%s (παρατηρήθηκε)" msgstr "" #. Assumption of Mary. -#: ./holidays/countries/greece.py:77 +#: ./holidays/countries/greece.py:78 msgid "Κοίμηση της Θεοτόκου" msgstr "" #. Ochi Day. -#: ./holidays/countries/greece.py:80 +#: ./holidays/countries/greece.py:81 msgid "Ημέρα του Όχι" msgstr "" #. Christmas Day. -#: ./holidays/countries/greece.py:83 +#: ./holidays/countries/greece.py:84 msgid "Χριστούγεννα" msgstr "" -#: ./holidays/countries/greece.py:87 +#: ./holidays/countries/greece.py:88 msgid "Επόμενη ημέρα των Χριστουγέννων" msgstr "" diff --git a/holidays/locale/en_US/LC_MESSAGES/GR.po b/holidays/locale/en_US/LC_MESSAGES/GR.po index 96288f05..d52e5c34 100644 --- a/holidays/locale/en_US/LC_MESSAGES/GR.po +++ b/holidays/locale/en_US/LC_MESSAGES/GR.po @@ -3,10 +3,10 @@ # msgid "" msgstr "" -"Project-Id-Version: Python Holidays 0.20\n" -"POT-Creation-Date: 2023-02-15 14:53-0800\n" -"PO-Revision-Date: 2023-02-15 14:59-0800\n" -"Last-Translator: Arkadii Yakovets <[email protected]>\n" +"Project-Id-Version: Python Holidays 0.26\n" +"POT-Creation-Date: 2023-06-01 17:41+0300\n" +"PO-Revision-Date: 2023-06-01 17:44+0300\n" +"Last-Translator: ~Jhellico <[email protected]>\n" "Language-Team: Python Holidays localization team\n" "Language: en_US\n" "MIME-Version: 1.0\n" @@ -16,60 +16,65 @@ msgstr "" "X-Generator: Poedit 3.2.2\n" #. New Year's Day. -#: ./holidays/countries/greece.py:44 +#: ./holidays/countries/greece.py:43 msgid "Πρωτοχρονιά" msgstr "New Year’s Day" #. Epiphany. -#: ./holidays/countries/greece.py:47 +#: ./holidays/countries/greece.py:46 msgid "Θεοφάνεια" msgstr "Epiphany" #. Clean Monday. -#: ./holidays/countries/greece.py:50 +#: ./holidays/countries/greece.py:49 msgid "Καθαρά Δευτέρα" msgstr "Clean Monday" #. Independence Day. -#: ./holidays/countries/greece.py:53 +#: ./holidays/countries/greece.py:52 msgid "Εικοστή Πέμπτη Μαρτίου" msgstr "Independence Day" +#. Good Friday. +#: ./holidays/countries/greece.py:55 +msgid "Μεγάλη Παρασκευή" +msgstr "Good Friday" + #. Easter Monday. -#: ./holidays/countries/greece.py:56 +#: ./holidays/countries/greece.py:58 msgid "Δευτέρα του Πάσχα" msgstr "Easter Monday" #. Monday of the Holy Spirit. -#: ./holidays/countries/greece.py:59 +#: ./holidays/countries/greece.py:61 msgid "Δευτέρα του Αγίου Πνεύματος" msgstr "Easter Monday" #. Labour Day. -#: ./holidays/countries/greece.py:62 +#: ./holidays/countries/greece.py:64 msgid "Εργατική Πρωτομαγιά" msgstr "Labor Day" -#: ./holidays/countries/greece.py:63 +#: ./holidays/countries/greece.py:65 #, c-format msgid "%s (παρατηρήθηκε)" msgstr "%s (Observed)" #. Assumption of Mary. -#: ./holidays/countries/greece.py:77 +#: ./holidays/countries/greece.py:78 msgid "Κοίμηση της Θεοτόκου" msgstr "Assumption of Mary Day" #. Ochi Day. -#: ./holidays/countries/greece.py:80 +#: ./holidays/countries/greece.py:81 msgid "Ημέρα του Όχι" msgstr "Ochi Day" #. Christmas Day. -#: ./holidays/countries/greece.py:83 +#: ./holidays/countries/greece.py:84 msgid "Χριστούγεννα" msgstr "Christmas Day" -#: ./holidays/countries/greece.py:87 +#: ./holidays/countries/greece.py:88 msgid "Επόμενη ημέρα των Χριστουγέννων" msgstr "Day After Christmas"
dr-prodigy/python-holidays
4c691d998d1f31285d1a564e5ababcd3b00e973a
diff --git a/tests/countries/test_greece.py b/tests/countries/test_greece.py index 93c1b87a..1d043600 100644 --- a/tests/countries/test_greece.py +++ b/tests/countries/test_greece.py @@ -9,8 +9,6 @@ # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) -from datetime import date - from holidays.countries.greece import Greece, GR, GRC from tests.common import TestCase @@ -18,93 +16,122 @@ from tests.common import TestCase class TestGreece(TestCase): @classmethod def setUpClass(cls): - super().setUpClass(Greece) + super().setUpClass(Greece, years=range(2000, 2025)) def test_country_aliases(self): self.assertCountryAliases(Greece, GR, GRC) def test_fixed_holidays(self): years = range(2000, 2025) - for y in years: - fdays = ( - (date(y, 1, 1), "Πρωτοχρονιά"), - (date(y, 1, 6), "Θεοφάνεια"), - (date(y, 3, 25), "Εικοστή Πέμπτη Μαρτίου"), - (date(y, 5, 1), "Εργατική Πρωτομαγιά"), - (date(y, 8, 15), "Κοίμηση της Θεοτόκου"), - (date(y, 10, 28), "Ημέρα του Όχι"), - (date(y, 12, 25), "Χριστούγεννα"), - (date(y, 12, 26), "Επόμενη ημέρα των Χριστουγέννων"), + for m, d, name in ( + (1, 1, "Πρωτοχρονιά"), + (1, 6, "Θεοφάνεια"), + (3, 25, "Εικοστή Πέμπτη Μαρτίου"), + (5, 1, "Εργατική Πρωτομαγιά"), + (8, 15, "Κοίμηση της Θεοτόκου"), + (10, 28, "Ημέρα του Όχι"), + (12, 25, "Χριστούγεννα"), + (12, 26, "Επόμενη ημέρα των Χριστουγέννων"), + ): + self.assertHolidaysName( + name, (f"{year}-{m}-{d}" for year in years) ) - for d, dstr in fdays: - self.assertIn(d, self.holidays) - self.assertIn(dstr, self.holidays[d]) - - def test_gr_clean_monday(self): - checkdates = ( - date(2018, 2, 19), - date(2019, 3, 11), - date(2020, 3, 2), - date(2021, 3, 15), - date(2022, 3, 7), - date(2023, 2, 27), - date(2024, 3, 18), + def test_clean_monday(self): + self.assertHolidaysName( + "Καθαρά Δευτέρα", + "2018-02-19", + "2019-03-11", + "2020-03-02", + "2021-03-15", + "2022-03-07", + "2023-02-27", + "2024-03-18", ) - for d in checkdates: - self.assertIn(d, self.holidays) - self.assertIn("Καθαρά Δευτέρα", self.holidays[d]) - - def test_gr_easter_monday(self): - checkdates = ( - date(2018, 4, 9), - date(2019, 4, 29), - date(2020, 4, 20), - date(2021, 5, 3), - date(2022, 4, 25), - date(2023, 4, 17), - date(2024, 5, 6), + def test_good_friday(self): + self.assertHolidaysName( + "Μεγάλη Παρασκευή", + "2018-04-06", + "2019-04-26", + "2020-04-17", + "2021-04-30", + "2022-04-22", + "2023-04-14", + "2024-05-03", ) - for d in checkdates: - self.assertIn(d, self.holidays) - self.assertIn("Δευτέρα του Πάσχα", self.holidays[d]) - - def test_gr_monday_of_the_holy_spirit(self): - checkdates = ( - date(2018, 5, 28), - date(2019, 6, 17), - date(2020, 6, 8), - date(2021, 6, 21), - date(2022, 6, 13), - date(2023, 6, 5), - date(2024, 6, 24), + def test_easter_monday(self): + self.assertHolidaysName( + "Δευτέρα του Πάσχα", + "2018-04-09", + "2019-04-29", + "2020-04-20", + "2021-05-03", + "2022-04-25", + "2023-04-17", + "2024-05-06", ) - for d in checkdates: - self.assertIn(d, self.holidays) - self.assertIn("Δευτέρα του Αγίου Πνεύματος", self.holidays[d]) - - def test_gr_labour_day_observed(self): - # Dates when labour day was observed on a different date - checkdates = ( - date(2016, 5, 3), - date(2021, 5, 4), - date(2022, 5, 2), - date(2033, 5, 2), + def test_monday_of_the_holy_spirit(self): + self.assertHolidaysName( + "Δευτέρα του Αγίου Πνεύματος", + "2018-05-28", + "2019-06-17", + "2020-06-08", + "2021-06-21", + "2022-06-13", + "2023-06-05", + "2024-06-24", ) - # Years when labour date was observed on May 1st - checkyears = (2017, 2018, 2019, 2020, 2023) - for d in checkdates: - self.assertIn(d, self.holidays) - self.assertIn("Εργατική Πρωτομαγιά", self.holidays[d]) + def test_labour_day_observed(self): + name_observed = "Εργατική Πρωτομαγιά (παρατηρήθηκε)" + dt = ( + "2011-05-02", + "2016-05-03", + "2021-05-04", + "2022-05-02", + ) + self.assertHolidaysName(name_observed, dt) + self.assertNoNonObservedHoliday(dt) + self.assertNoHolidayName(name_observed, 2017, 2018, 2019, 2020, 2023) + + def test_l10n_default(self): + self.assertLocalizedHolidays( + ( + ("2022-01-01", "Πρωτοχρονιά"), + ("2022-01-06", "Θεοφάνεια"), + ("2022-03-07", "Καθαρά Δευτέρα"), + ("2022-03-25", "Εικοστή Πέμπτη Μαρτίου"), + ("2022-04-22", "Μεγάλη Παρασκευή"), + ("2022-04-25", "Δευτέρα του Πάσχα"), + ("2022-05-01", "Εργατική Πρωτομαγιά"), + ("2022-05-02", "Εργατική Πρωτομαγιά (παρατηρήθηκε)"), + ("2022-06-13", "Δευτέρα του Αγίου Πνεύματος"), + ("2022-08-15", "Κοίμηση της Θεοτόκου"), + ("2022-10-28", "Ημέρα του Όχι"), + ("2022-12-25", "Χριστούγεννα"), + ("2022-12-26", "Επόμενη ημέρα των Χριστουγέννων"), + ) + ) - # Check that there is no observed day created for years - # when Labour Day was on May 1st - for year in checkyears: - for day in (2, 3, 4): - d = date(year, 5, day) - if d in self.holidays: - self.assertNotIn("Εργατική Πρωτομαγιά", self.holidays[d]) + def test_l10n_en_us(self): + self.assertLocalizedHolidays( + ( + ("2022-01-01", "New Year’s Day"), + ("2022-01-06", "Epiphany"), + ("2022-03-07", "Clean Monday"), + ("2022-03-25", "Independence Day"), + ("2022-04-22", "Good Friday"), + ("2022-04-25", "Easter Monday"), + ("2022-05-01", "Labor Day"), + ("2022-05-02", "Labor Day (Observed)"), + ("2022-06-13", "Easter Monday"), + ("2022-08-15", "Assumption of Mary Day"), + ("2022-10-28", "Ochi Day"), + ("2022-12-25", "Christmas Day"), + ("2022-12-26", "Day After Christmas"), + ), + "en_US", + )
Missing Orthodox Good Friday in Greece national holiday Hello team, I was looking at your package's data and noticed one missing day for Greece. Source: https://www.officeholidays.com/countries/greece/2022 Missing day: 2023 Fri, Apr 14 National Holiday (Orthodox Good Friday) Would it be possible to include it in your package, please? Best regards, David Boudart
0.0
4c691d998d1f31285d1a564e5ababcd3b00e973a
[ "tests/countries/test_greece.py::TestGreece::test_good_friday", "tests/countries/test_greece.py::TestGreece::test_l10n_default" ]
[ "tests/countries/test_greece.py::TestGreece::test_clean_monday", "tests/countries/test_greece.py::TestGreece::test_country_aliases", "tests/countries/test_greece.py::TestGreece::test_easter_monday", "tests/countries/test_greece.py::TestGreece::test_fixed_holidays", "tests/countries/test_greece.py::TestGreece::test_labour_day_observed", "tests/countries/test_greece.py::TestGreece::test_monday_of_the_holy_spirit" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-01 15:32:22+00:00
mit
1,983
dr-prodigy__python-holidays-1278
diff --git a/README.rst b/README.rst index 88119e36..211fceee 100644 --- a/README.rst +++ b/README.rst @@ -108,7 +108,7 @@ Available Countries .. _ISO 3166-2 code: https://en.wikipedia.org/wiki/ISO_3166-2 .. _ISO 639-1 code: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes -We currently support 127 country codes. The standard way to refer to a country +We currently support 128 country codes. The standard way to refer to a country is by using its `ISO 3166-1 alpha-2 code`_, the same used for domain names, and for a subdivision its `ISO 3166-2 code`_. Some of the countries support more than one language for holiday names output. @@ -219,6 +219,10 @@ The list of supported countries, their subdivisions and supported languages - BG - - **bg**, en_US + * - Burkina Faso + - BF + - + - * - Burundi - BI - diff --git a/holidays/countries/__init__.py b/holidays/countries/__init__.py index 65ad53c0..e75e4960 100644 --- a/holidays/countries/__init__.py +++ b/holidays/countries/__init__.py @@ -31,6 +31,7 @@ from .botswana import Botswana, BW, BWA from .brazil import Brazil, BR, BRA from .brunei import Brunei, BN, BRN from .bulgaria import Bulgaria, BG, BLG +from .burkina_faso import BurkinaFaso, BF, BFA from .burundi import Burundi, BI, BDI from .cameroon import Cameroon, CM, CMR from .canada import Canada, CA, CAN diff --git a/holidays/countries/burkina_faso.py b/holidays/countries/burkina_faso.py new file mode 100644 index 00000000..34c1fbc4 --- /dev/null +++ b/holidays/countries/burkina_faso.py @@ -0,0 +1,144 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from datetime import date +from datetime import timedelta as td + +from holidays.calendars import _CustomIslamicCalendar +from holidays.constants import JAN, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC +from holidays.holiday_base import HolidayBase +from holidays.holiday_groups import ChristianHolidays, InternationalHolidays +from holidays.holiday_groups import IslamicHolidays + + +class BurkinaFaso( + HolidayBase, ChristianHolidays, InternationalHolidays, IslamicHolidays +): + """ + References: + - https://en.wikipedia.org/wiki/Public_holidays_in_Burkina_Faso + """ + + country = "BF" + + def __init__(self, *args, **kwargs) -> None: + ChristianHolidays.__init__(self) + InternationalHolidays.__init__(self) + IslamicHolidays.__init__(self, calendar=BurkinaFasoIslamicCalendar()) + super().__init__(*args, **kwargs) + + def _add_observed(self, dt: date) -> None: + if self.observed and self._is_sunday(dt): + self._add_holiday("%s (Observed)" % self[dt], dt + td(days=+1)) + + def _populate(self, year): + # On 5 August 1960, Burkina Faso (Republic of Upper Volta at that time) + # gained independence from France. + if year <= 1960: + return None + + super()._populate(year) + + # New Year's Day. + self._add_observed(self._add_new_years_day("New Year's Day")) + + if year >= 1967: + # Revolution Day. + self._add_observed(self._add_holiday("Revolution Day", JAN, 3)) + + # International Women's Day. + self._add_observed(self._add_womens_day("International Women's Day")) + + # Easter Monday. + self._add_easter_monday("Easter Monday") + + # Labour Day. + self._add_observed(self._add_labor_day("Labour Day")) + + # Ascension Day. + self._add_ascension_thursday("Ascension Day") + + # Independence Day. + self._add_observed(self._add_holiday("Independence Day", AUG, 5)) + + # Assumption Day. + self._add_observed(self._add_assumption_of_mary_day("Assumption Day")) + + if year >= 2016: + # Martyrs' Day. + self._add_observed(self._add_holiday("Martyrs' Day", OCT, 31)) + + # All Saints' Day. + self._add_observed(self._add_all_saints_day("All Saints' Day")) + + self._add_observed( + # Proclamation of Independence Day. + self._add_holiday("Proclamation of Independence Day", DEC, 11) + ) + + # Christmas Day. + self._add_observed(self._add_christmas_day("Christmas Day")) + + # Eid al-Fitr. + self._add_eid_al_fitr_day("Eid al-Fitr") + + # Eid al-Adha. + self._add_eid_al_adha_day("Eid al-Adha") + + # Mawlid. + self._add_mawlid_day("Mawlid") + + +class BF(BurkinaFaso): + pass + + +class BFA(BurkinaFaso): + pass + + +class BurkinaFasoIslamicCalendar(_CustomIslamicCalendar): + EID_AL_ADHA_DATES = { + 2014: ((OCT, 5),), + 2015: ((SEP, 24),), + 2016: ((SEP, 13),), + 2017: ((SEP, 2),), + 2018: ((AUG, 21),), + 2019: ((AUG, 11),), + 2020: ((JUL, 31),), + 2021: ((JUL, 20),), + 2022: ((JUL, 9),), + } + + EID_AL_FITR_DATES = { + 2014: ((JUL, 29),), + 2015: ((JUL, 18),), + 2016: ((JUL, 7),), + 2017: ((JUN, 26),), + 2018: ((JUN, 15),), + 2019: ((JUN, 4),), + 2020: ((MAY, 24),), + 2021: ((MAY, 13),), + 2022: ((MAY, 2),), + 2023: ((APR, 21),), + } + + MAWLID_DATES = { + 2014: ((JAN, 14),), + 2015: ((JAN, 3), (DEC, 24)), + 2016: ((DEC, 12),), + 2017: ((DEC, 1),), + 2018: ((NOV, 21),), + 2019: ((NOV, 10),), + 2020: ((OCT, 29),), + 2021: ((OCT, 19),), + 2022: ((OCT, 9),), + } diff --git a/holidays/registry.py b/holidays/registry.py index 241b8fa0..698be8e0 100644 --- a/holidays/registry.py +++ b/holidays/registry.py @@ -39,6 +39,7 @@ COUNTRIES: RegistryDict = { "brazil": ("Brazil", "BR", "BRA"), "brunei": ("Brunei", "BN", "BRN"), "bulgaria": ("Bulgaria", "BG", "BLG"), + "burkina_faso": ("BurkinaFaso", "BF", "BFA"), "burundi": ("Burundi", "BI", "BDI"), "cameroon": ("Cameroon", "CM", "CMR"), "canada": ("Canada", "CA", "CAN"),
dr-prodigy/python-holidays
d44a0535262939d0146d2e107643d77b7f2043ba
diff --git a/tests/countries/test_burkina_faso.py b/tests/countries/test_burkina_faso.py new file mode 100644 index 00000000..4758e192 --- /dev/null +++ b/tests/countries/test_burkina_faso.py @@ -0,0 +1,101 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from holidays.countries.burkina_faso import BurkinaFaso, BF, BFA +from tests.common import TestCase + + +class TestBurkinaFaso(TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass(BurkinaFaso) + + def test_country_aliases(self): + self.assertCountryAliases(BurkinaFaso, BF, BFA) + + def test_no_holidays(self): + self.assertNoHolidays(BurkinaFaso(years=1960)) + + def test_revolution_day(self): + name = "Revolution Day" + self.assertHolidaysName( + name, (f"{year}-01-03" for year in range(1967, 2050)) + ) + self.assertNoHolidayName(name, BurkinaFaso(years=range(1961, 1967))) + self.assertNoHoliday(f"{year}-01-03" for year in range(1961, 1967)) + + def test_martyrs_day(self): + name = "Martyrs' Day" + self.assertHolidaysName( + name, (f"{year}-10-31" for year in range(2016, 2050)) + ) + self.assertNoHolidayName(name, BurkinaFaso(years=range(1961, 2016))) + self.assertNoHoliday( + f"{year}-10-31" + for year in set(range(1961, 2016)).difference({1979}) + ) + + def test_observed(self): + dt = ( + # New Year's Day + "2012-01-02", + "2017-01-02", + "2023-01-02", + # Revolution Day + "2010-01-04", + "2016-01-04", + "2021-01-04", + # International Women's Day + "2015-03-09", + "2020-03-09", + # Labour Day + "2011-05-02", + "2016-05-02", + # Independence Day + "2012-08-06", + "2018-08-06", + # Assumption Day + "2010-08-16", + "2021-08-16", + # All Saints' Day + "2015-11-02", + "2020-11-02", + # Proclamation of Independence Day + "2011-12-12", + "2022-12-12", + # Christmas Day + "2011-12-26", + "2016-12-26", + "2022-12-26", + ) + self.assertHoliday(dt) + self.assertNoNonObservedHoliday(dt) + + def test_2022(self): + self.assertHolidays( + ("2022-01-01", "New Year's Day"), + ("2022-01-03", "Revolution Day"), + ("2022-03-08", "International Women's Day"), + ("2022-04-18", "Easter Monday"), + ("2022-05-01", "Labour Day"), + ("2022-05-02", "Eid al-Fitr; Labour Day (Observed)"), + ("2022-05-26", "Ascension Day"), + ("2022-07-09", "Eid al-Adha"), + ("2022-08-05", "Independence Day"), + ("2022-08-15", "Assumption Day"), + ("2022-10-09", "Mawlid"), + ("2022-10-31", "Martyrs' Day"), + ("2022-11-01", "All Saints' Day"), + ("2022-12-11", "Proclamation of Independence Day"), + ("2022-12-12", "Proclamation of Independence Day (Observed)"), + ("2022-12-25", "Christmas Day"), + ("2022-12-26", "Christmas Day (Observed)"), + )
Add Burkina Faso holidays Useful links: - https://en.wikipedia.org/wiki/Public_holidays_in_Burkina_Faso - https://www.timeanddate.com/holidays/burkina-faso/
0.0
d44a0535262939d0146d2e107643d77b7f2043ba
[ "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_2022", "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_country_aliases", "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_martyrs_day", "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_no_holidays", "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_observed", "tests/countries/test_burkina_faso.py::TestBurkinaFaso::test_revolution_day" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-03 16:07:51+00:00
mit
1,984
dr-prodigy__python-holidays-1279
diff --git a/README.rst b/README.rst index 211fceee..c7cae973 100644 --- a/README.rst +++ b/README.rst @@ -108,7 +108,7 @@ Available Countries .. _ISO 3166-2 code: https://en.wikipedia.org/wiki/ISO_3166-2 .. _ISO 639-1 code: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes -We currently support 128 country codes. The standard way to refer to a country +We currently support 129 country codes. The standard way to refer to a country is by using its `ISO 3166-1 alpha-2 code`_, the same used for domain names, and for a subdivision its `ISO 3166-2 code`_. Some of the countries support more than one language for holiday names output. @@ -235,6 +235,10 @@ The list of supported countries, their subdivisions and supported languages - CA - Provinces and territories: AB, BC, MB, NB, NL, NS, NT, NU, **ON**, PE, QC, SK, YT - ar, **en**, en_US, fr, th + * - Chad + - TD + - + - * - Chile - CL - Regions: AI, AN, AP, AR, AT, BI, CO, LI, LL, LR, MA, ML, NB, RM, TA, VS diff --git a/holidays/countries/__init__.py b/holidays/countries/__init__.py index e75e4960..aa860a45 100644 --- a/holidays/countries/__init__.py +++ b/holidays/countries/__init__.py @@ -35,6 +35,7 @@ from .burkina_faso import BurkinaFaso, BF, BFA from .burundi import Burundi, BI, BDI from .cameroon import Cameroon, CM, CMR from .canada import Canada, CA, CAN +from .chad import Chad, TD, TCD from .chile import Chile, CL, CHL from .china import China, CN, CHN from .colombia import Colombia, CO, COL diff --git a/holidays/countries/chad.py b/holidays/countries/chad.py new file mode 100644 index 00000000..ffb0576d --- /dev/null +++ b/holidays/countries/chad.py @@ -0,0 +1,136 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from datetime import date +from datetime import timedelta as td + +from holidays.calendars import _CustomIslamicCalendar +from holidays.constants import JAN, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC +from holidays.holiday_base import HolidayBase +from holidays.holiday_groups import ChristianHolidays, InternationalHolidays +from holidays.holiday_groups import IslamicHolidays + + +class Chad( + HolidayBase, ChristianHolidays, InternationalHolidays, IslamicHolidays +): + """ + References: + - https://en.wikipedia.org/wiki/Public_holidays_in_Chad + - https://www.ilo.org/dyn/natlex/docs/ELECTRONIC/97323/115433/F-316075167/TCD-97323.pdf # noqa: E501 + """ + + country = "TD" + special_holidays = { + 2021: ((APR, 23, "Funeral of Idriss Déby Itno"),), + } + + def __init__(self, *args, **kwargs) -> None: + ChristianHolidays.__init__(self) + InternationalHolidays.__init__(self) + IslamicHolidays.__init__(self, calendar=ChadIslamicCalendar()) + super().__init__(*args, **kwargs) + + def _add_observed(self, dt: date) -> None: + if self.observed and self._is_sunday(dt): + self._add_holiday("%s (Observed)" % self[dt], dt + td(days=+1)) + + def _populate(self, year): + # On 11 August 1960, Chad gained independence from France. + if year <= 1960: + return None + + super()._populate(year) + + # New Year's Day. + self._add_observed(self._add_new_years_day("New Year's Day")) + + # International Women's Day. + self._add_observed(self._add_womens_day("International Women's Day")) + + # Easter Monday. + self._add_easter_monday("Easter Monday") + + # Labour Day. + self._add_observed(self._add_labor_day("Labour Day")) + + # Independence Day. + self._add_observed(self._add_holiday("Independence Day", AUG, 11)) + + # All Saints' Day. + self._add_all_saints_day("All Saints' Day") + + self._add_observed( + # Republic Day. + self._add_holiday("Republic Day", NOV, 28) + ) + + if year >= 1991: + self._add_observed( + # Freedom and Democracy Day. + self._add_holiday("Freedom and Democracy Day", DEC, 1) + ) + + # Christmas Day. + self._add_christmas_day("Christmas Day") + + # Eid al-Fitr. + self._add_eid_al_fitr_day("Eid al-Fitr") + + # Eid al-Adha. + self._add_eid_al_adha_day("Eid al-Adha") + + # Mawlid. + self._add_mawlid_day("Mawlid") + + +class TD(Chad): + pass + + +class TCD(Chad): + pass + + +class ChadIslamicCalendar(_CustomIslamicCalendar): + EID_AL_ADHA_DATES = { + 2015: ((SEP, 24),), + 2016: ((SEP, 13),), + 2017: ((SEP, 2),), + 2018: ((AUG, 22),), + 2019: ((AUG, 11),), + 2020: ((JUL, 31),), + 2021: ((JUL, 20),), + 2022: ((JUL, 9),), + } + + EID_AL_FITR_DATES = { + 2015: ((JUL, 18),), + 2016: ((JUL, 7),), + 2017: ((JUN, 26),), + 2018: ((JUN, 15),), + 2019: ((JUN, 4),), + 2020: ((MAY, 24),), + 2021: ((MAY, 13),), + 2022: ((MAY, 2),), + 2023: ((APR, 21),), + } + + MAWLID_DATES = { + 2015: ((JAN, 3), (DEC, 24)), + 2016: ((DEC, 12),), + 2017: ((DEC, 1),), + 2018: ((NOV, 21),), + 2019: ((NOV, 9),), + 2020: ((OCT, 29),), + 2021: ((OCT, 18),), + 2022: ((OCT, 8),), + } diff --git a/holidays/registry.py b/holidays/registry.py index 698be8e0..3b6324f1 100644 --- a/holidays/registry.py +++ b/holidays/registry.py @@ -43,6 +43,7 @@ COUNTRIES: RegistryDict = { "burundi": ("Burundi", "BI", "BDI"), "cameroon": ("Cameroon", "CM", "CMR"), "canada": ("Canada", "CA", "CAN"), + "chad": ("Chad", "TD", "TCD"), "chile": ("Chile", "CL", "CHL"), "china": ("China", "CN", "CHN"), "colombia": ("Colombia", "CO", "COL"),
dr-prodigy/python-holidays
e8c53e3c61cd5c1277d17d1dee6fde378ad37680
diff --git a/tests/countries/test_chad.py b/tests/countries/test_chad.py new file mode 100644 index 00000000..3d61d8c2 --- /dev/null +++ b/tests/countries/test_chad.py @@ -0,0 +1,80 @@ +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Authors: dr-prodigy <[email protected]> (c) 2017-2023 +# ryanss <[email protected]> (c) 2014-2017 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from holidays.countries.chad import Chad, TD, TCD +from tests.common import TestCase + + +class TestChad(TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass(Chad) + + def test_country_aliases(self): + self.assertCountryAliases(Chad, TD, TCD) + + def test_no_holidays(self): + self.assertNoHolidays(Chad(years=1960)) + + def test_special_holidays(self): + self.assertHoliday("2021-04-23") + + def test_freedom_and_democracy_day(self): + name = "Freedom and Democracy Day" + self.assertHolidaysName( + name, (f"{year}-12-01" for year in range(1991, 2050)) + ) + self.assertNoHolidayName(name, Chad(years=range(1961, 1991))) + self.assertNoHoliday( + f"{year}-12-01" + for year in set(range(1961, 1991)).difference({1976}) + ) + + def test_observed(self): + dt = ( + # New Year's Day + "2012-01-02", + "2017-01-02", + "2023-01-02", + # International Women's Day + "2015-03-09", + "2020-03-09", + # Labour Day + "2011-05-02", + "2016-05-02", + # Independence Day + "2013-08-12", + "2019-08-12", + # Republic Day + "2010-11-29", + "2021-11-29", + # Freedom and Democracy Day + "2013-12-02", + "2019-12-02", + ) + self.assertHoliday(dt) + self.assertNoNonObservedHoliday(dt) + + def test_2022(self): + self.assertHolidays( + ("2022-01-01", "New Year's Day"), + ("2022-03-08", "International Women's Day"), + ("2022-04-18", "Easter Monday"), + ("2022-05-01", "Labour Day"), + ("2022-05-02", "Eid al-Fitr; Labour Day (Observed)"), + ("2022-07-09", "Eid al-Adha"), + ("2022-08-11", "Independence Day"), + ("2022-10-08", "Mawlid"), + ("2022-11-01", "All Saints' Day"), + ("2022-11-28", "Republic Day"), + ("2022-12-01", "Freedom and Democracy Day"), + ("2022-12-25", "Christmas Day"), + )
Add Chad holidays Useful links: - https://en.wikipedia.org/wiki/Public_holidays_in_Chad - https://www.timeanddate.com/holidays/chad/
0.0
e8c53e3c61cd5c1277d17d1dee6fde378ad37680
[ "tests/countries/test_chad.py::TestChad::test_2022", "tests/countries/test_chad.py::TestChad::test_country_aliases", "tests/countries/test_chad.py::TestChad::test_freedom_and_democracy_day", "tests/countries/test_chad.py::TestChad::test_no_holidays", "tests/countries/test_chad.py::TestChad::test_observed", "tests/countries/test_chad.py::TestChad::test_special_holidays" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-03 18:35:59+00:00
mit
1,985
dr-prodigy__python-holidays-1306
diff --git a/holidays/holiday_base.py b/holidays/holiday_base.py index 0690d59c..ccffa40c 100644 --- a/holidays/holiday_base.py +++ b/holidays/holiday_base.py @@ -724,7 +724,12 @@ class HolidayBase(Dict[date, str]): if name ] - def get_named(self, holiday_name: str, lookup="icontains") -> List[date]: + def get_named( + self, + holiday_name: str, + lookup="icontains", + split_multiple_names=True, + ) -> List[date]: """Return a list of all holiday dates matching the provided holiday name. The match will be made case insensitively and partial matches will be included by default. @@ -739,12 +744,17 @@ class HolidayBase(Dict[date, str]): icontains - case insensitive contains match; iexact - case insensitive exact match; istartswith - case insensitive starts with match; + :param split_multiple_names: + Either use the exact name for each date or split it by holiday + name delimiter. :return: A list of all holiday dates matching the provided holiday name. """ holiday_date_names_mapping: Dict[date, List[str]] = { key: value.split(HOLIDAY_NAME_DELIMITER) + if split_multiple_names + else [value] for key, value in self.items() } @@ -849,14 +859,24 @@ class HolidayBase(Dict[date, str]): :raise: KeyError if date is not a holiday and default is not given. """ - dates = self.get_named(name) - if not dates: + use_exact_name = HOLIDAY_NAME_DELIMITER in name + dts = self.get_named(name, split_multiple_names=not use_exact_name) + if len(dts) == 0: raise KeyError(name) - for dt in dates: + popped = [] + for dt in dts: + holiday_names = self[dt].split(HOLIDAY_NAME_DELIMITER) self.pop(dt) + popped.append(dt) - return dates + # Keep the rest of holidays falling on the same date. + if not use_exact_name: + holiday_names.remove(name) + if len(holiday_names) > 0: + self[dt] = HOLIDAY_NAME_DELIMITER.join(holiday_names) + + return popped def update( # type: ignore[override] self, *args: Union[Dict[DateLike, str], List[DateLike], DateLike]
dr-prodigy/python-holidays
522a9951f4457c68977016ecc8d8d9e08011f8d2
diff --git a/tests/countries/test_isle_of_man.py b/tests/countries/test_isle_of_man.py index 157f6956..28a72bec 100644 --- a/tests/countries/test_isle_of_man.py +++ b/tests/countries/test_isle_of_man.py @@ -21,6 +21,17 @@ class TestIM(TestCase): def test_country_aliases(self): self.assertCountryAliases(IsleOfMan, IM, IMN) + def test_1970(self): + self.assertHolidays( + ("1970-03-27", "Good Friday"), + ("1970-03-30", "Easter Monday"), + ("1970-06-05", "TT Bank Holiday"), + ("1970-07-05", "Tynwald Day"), + ("1970-12-25", "Christmas Day"), + ("1970-12-26", "Boxing Day"), + ("1970-12-28", "Boxing Day (Observed)"), + ) + def test_2022(self): self.assertHolidays( ("2022-01-01", "New Year's Day"), diff --git a/tests/test_holiday_base.py b/tests/test_holiday_base.py index f6d36473..ffd27a9a 100644 --- a/tests/test_holiday_base.py +++ b/tests/test_holiday_base.py @@ -21,6 +21,7 @@ from dateutil.relativedelta import relativedelta as rd import holidays from holidays.constants import JAN, FEB, OCT, MON, TUE, SAT, SUN +from holidays.constants import HOLIDAY_NAME_DELIMITER class TestBasics(unittest.TestCase): @@ -119,15 +120,60 @@ class TestBasics(unittest.TestCase): self.assertNotIn(date(2014, 1, 1), self.holidays) self.assertIn(date(2014, 7, 4), self.holidays) - def test_pop_named(self): + def test_pop_named_single(self): self.assertIn(date(2014, 1, 1), self.holidays) - self.holidays.pop_named("New Year's Day") - self.assertNotIn(date(2014, 1, 1), self.holidays) + dts = self.holidays.pop_named("New Year's Day") + for dt in dts: + self.assertNotIn(dt, self.holidays) + + def test_pop_named_multiple(self): + dt = date(2022, 2, 22) + holiday_name_1 = "Holiday Name 1" + holiday_name_2 = "Holiday Name 2" + holiday_name_3 = "Holiday Name 3" + combined_name = HOLIDAY_NAME_DELIMITER.join( + (holiday_name_1, holiday_name_2, holiday_name_3) + ) + self.holidays[dt] = holiday_name_1 + self.holidays[dt] = holiday_name_2 + self.holidays[dt] = holiday_name_3 + self.assertEqual(self.holidays[dt], combined_name) + + # Pop the entire date by multiple holidays exact name. + self.holidays.pop_named(combined_name) + self.assertNotIn(dt, self.holidays) + + # Pop only one holiday by a single name. + self.holidays[dt] = holiday_name_1 + self.holidays[dt] = holiday_name_2 + self.holidays[dt] = holiday_name_3 + self.assertEqual(self.holidays[dt], combined_name) + + self.holidays.pop_named(holiday_name_1) + self.assertEqual( + self.holidays[dt], + HOLIDAY_NAME_DELIMITER.join((holiday_name_2, holiday_name_3)), + ) + + self.holidays.pop_named(holiday_name_3) + self.assertEqual(self.holidays[dt], holiday_name_2) + + self.holidays.pop_named(holiday_name_2) + self.assertNotIn(dt, self.holidays) + + def test_pop_named_exception(self): self.assertRaises( KeyError, lambda: self.holidays.pop_named("New Year's Dayz"), ) + self.assertIn(date(2022, 1, 1), self.holidays) + self.holidays.pop_named("New Year's Day") + self.assertRaises( + KeyError, + lambda: self.holidays.pop_named("New Year's Day"), + ) + def test_setitem(self): self.holidays = holidays.US(years=[2014]) self.assertEqual(len(self.holidays), 10)
Cannot "Pop" Combined Texas Emancipation/Juneteenth Holiday Creating a holiday using TX as the state, there is the combined holiday 'Emancipation Day In Texas; Juneteenth National Independence Day' Previous versions of python-holidays seemed to treat this concatenation with a comma a such: 'Emancipation Day In Texas, Juneteenth National Independence Day' I am able to 'pop_named' the holiday in the older version, not in the newer with the semicolon seperator: python3.6/holidays 0.11.3.1: ![image](https://github.com/dr-prodigy/python-holidays/assets/38263272/0de82f34-1c46-400b-859a-b7d87f7c8703) python 3.10/holidays .25: ![image](https://github.com/dr-prodigy/python-holidays/assets/38263272/381017f6-0d49-49d3-9b09-f4e5c85b31f0)
0.0
522a9951f4457c68977016ecc8d8d9e08011f8d2
[ "tests/test_holiday_base.py::TestBasics::test_pop_named_multiple" ]
[ "tests/countries/test_isle_of_man.py::TestIM::test_1970", "tests/countries/test_isle_of_man.py::TestIM::test_2022", "tests/countries/test_isle_of_man.py::TestIM::test_country_aliases", "tests/test_holiday_base.py::TestBasics::test_add_countries", "tests/test_holiday_base.py::TestBasics::test_add_financial", "tests/test_holiday_base.py::TestBasics::test_add_holiday", "tests/test_holiday_base.py::TestBasics::test_append", "tests/test_holiday_base.py::TestBasics::test_contains", "tests/test_holiday_base.py::TestBasics::test_copy", "tests/test_holiday_base.py::TestBasics::test_eq_", "tests/test_holiday_base.py::TestBasics::test_get", "tests/test_holiday_base.py::TestBasics::test_get_list", "tests/test_holiday_base.py::TestBasics::test_get_named_contains", "tests/test_holiday_base.py::TestBasics::test_get_named_exact", "tests/test_holiday_base.py::TestBasics::test_get_named_icontains", "tests/test_holiday_base.py::TestBasics::test_get_named_iexact", "tests/test_holiday_base.py::TestBasics::test_get_named_istartswith", "tests/test_holiday_base.py::TestBasics::test_get_named_lookup_invalid", "tests/test_holiday_base.py::TestBasics::test_get_named_startswith", "tests/test_holiday_base.py::TestBasics::test_getitem", "tests/test_holiday_base.py::TestBasics::test_inheritance", "tests/test_holiday_base.py::TestBasics::test_is_leap_year", "tests/test_holiday_base.py::TestBasics::test_is_weekend", "tests/test_holiday_base.py::TestBasics::test_ne", "tests/test_holiday_base.py::TestBasics::test_pop", "tests/test_holiday_base.py::TestBasics::test_pop_named_exception", "tests/test_holiday_base.py::TestBasics::test_pop_named_single", "tests/test_holiday_base.py::TestBasics::test_radd", "tests/test_holiday_base.py::TestBasics::test_repr_country", "tests/test_holiday_base.py::TestBasics::test_repr_market", "tests/test_holiday_base.py::TestBasics::test_setitem", "tests/test_holiday_base.py::TestBasics::test_str_country", "tests/test_holiday_base.py::TestBasics::test_str_market", "tests/test_holiday_base.py::TestBasics::test_update", "tests/test_holiday_base.py::TestArgs::test_country", "tests/test_holiday_base.py::TestArgs::test_deprecation_warnings", "tests/test_holiday_base.py::TestArgs::test_expand", "tests/test_holiday_base.py::TestArgs::test_observed", "tests/test_holiday_base.py::TestArgs::test_serialization", "tests/test_holiday_base.py::TestArgs::test_years", "tests/test_holiday_base.py::TestKeyTransforms::test_date", "tests/test_holiday_base.py::TestKeyTransforms::test_date_derived", "tests/test_holiday_base.py::TestKeyTransforms::test_datetime", "tests/test_holiday_base.py::TestKeyTransforms::test_exception", "tests/test_holiday_base.py::TestKeyTransforms::test_string", "tests/test_holiday_base.py::TestKeyTransforms::test_timestamp", "tests/test_holiday_base.py::TestCountryHolidayDeprecation::test_deprecation", "tests/test_holiday_base.py::TestCountrySpecialHolidays::test_populate_special_holidays", "tests/test_holiday_base.py::TestHolidaysTranslation::test_language_unavailable" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-06-10 01:43:28+00:00
mit
1,986
dr-prodigy__python-holidays-1325
diff --git a/CHANGES b/CHANGES index 38bd8937..04d3b680 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,10 @@ +Version 0.27.1 +============== + +Released June 21, 2023 + +- Fix HolidayBase::pop_named partial holiday names removal (#1325 by @arkid15r) + Version 0.27 ============ diff --git a/holidays/__init__.py b/holidays/__init__.py index 12bda76a..02182bc9 100644 --- a/holidays/__init__.py +++ b/holidays/__init__.py @@ -14,7 +14,7 @@ from holidays.holiday_base import * from holidays.registry import EntityLoader from holidays.utils import * -__version__ = "0.27" +__version__ = "0.27.1" EntityLoader.load("countries", globals()) diff --git a/holidays/holiday_base.py b/holidays/holiday_base.py index 5c568e22..c25cf69c 100644 --- a/holidays/holiday_base.py +++ b/holidays/holiday_base.py @@ -822,7 +822,13 @@ class HolidayBase(Dict[date, str]): # Keep the rest of holidays falling on the same date. if not use_exact_name: - holiday_names.remove(name) + name_lower = name.lower() + holiday_names = [ + holiday_name + for holiday_name in holiday_names + if name_lower not in holiday_name.lower() + ] + if len(holiday_names) > 0: self[dt] = HOLIDAY_NAME_DELIMITER.join(holiday_names) diff --git a/setup.cfg b/setup.cfg index 4c1e185c..f0505dea 100644 --- a/setup.cfg +++ b/setup.cfg @@ -37,7 +37,7 @@ python_requires = >=3.7 include_package_data = True [bumpversion] -current_version = 0.27 +current_version = 0.27.1 [flake8] extend-ignore = F821
dr-prodigy/python-holidays
2b0463684d23adacb331c03fda7b794534c16c6d
diff --git a/tests/test_holiday_base.py b/tests/test_holiday_base.py index c57af796..bfe86e01 100644 --- a/tests/test_holiday_base.py +++ b/tests/test_holiday_base.py @@ -156,6 +156,16 @@ class TestBasics(unittest.TestCase): self.holidays.pop_named(holiday_name_2) self.assertNotIn(dt, self.holidays) + def test_pop_named_partial(self): + self.assertIn(date(2014, 1, 1), self.holidays) + dts = self.holidays.pop_named("N") + for dt in dts: + self.assertNotIn(dt, self.holidays) + self.assertRaises( + KeyError, + lambda: self.holidays.pop_named("New Year"), + ) + def test_pop_named_exception(self): self.assertRaises( KeyError,
HolidayBase::pop_named won't remove holiday by a partial name ``` File ".../home-assistant-core/venv/lib/python3.10/site-packages/holidays/holiday_base.py", line 825, in pop_named holiday_names.remove(name) ValueError: list.remove(x): x not in list ```
0.0
2b0463684d23adacb331c03fda7b794534c16c6d
[ "tests/test_holiday_base.py::TestBasics::test_pop_named_partial" ]
[ "tests/test_holiday_base.py::TestBasics::test_add_countries", "tests/test_holiday_base.py::TestBasics::test_add_financial", "tests/test_holiday_base.py::TestBasics::test_add_holiday", "tests/test_holiday_base.py::TestBasics::test_append", "tests/test_holiday_base.py::TestBasics::test_contains", "tests/test_holiday_base.py::TestBasics::test_copy", "tests/test_holiday_base.py::TestBasics::test_eq_", "tests/test_holiday_base.py::TestBasics::test_get", "tests/test_holiday_base.py::TestBasics::test_get_list", "tests/test_holiday_base.py::TestBasics::test_get_named_contains", "tests/test_holiday_base.py::TestBasics::test_get_named_exact", "tests/test_holiday_base.py::TestBasics::test_get_named_icontains", "tests/test_holiday_base.py::TestBasics::test_get_named_iexact", "tests/test_holiday_base.py::TestBasics::test_get_named_istartswith", "tests/test_holiday_base.py::TestBasics::test_get_named_lookup_invalid", "tests/test_holiday_base.py::TestBasics::test_get_named_startswith", "tests/test_holiday_base.py::TestBasics::test_getitem", "tests/test_holiday_base.py::TestBasics::test_inheritance", "tests/test_holiday_base.py::TestBasics::test_is_leap_year", "tests/test_holiday_base.py::TestBasics::test_is_weekend", "tests/test_holiday_base.py::TestBasics::test_ne", "tests/test_holiday_base.py::TestBasics::test_pop", "tests/test_holiday_base.py::TestBasics::test_pop_named_exception", "tests/test_holiday_base.py::TestBasics::test_pop_named_multiple", "tests/test_holiday_base.py::TestBasics::test_pop_named_single", "tests/test_holiday_base.py::TestBasics::test_radd", "tests/test_holiday_base.py::TestBasics::test_repr_country", "tests/test_holiday_base.py::TestBasics::test_repr_market", "tests/test_holiday_base.py::TestBasics::test_setitem", "tests/test_holiday_base.py::TestBasics::test_str_country", "tests/test_holiday_base.py::TestBasics::test_str_market", "tests/test_holiday_base.py::TestBasics::test_update", "tests/test_holiday_base.py::TestArgs::test_country", "tests/test_holiday_base.py::TestArgs::test_deprecation_warnings", "tests/test_holiday_base.py::TestArgs::test_expand", "tests/test_holiday_base.py::TestArgs::test_observed", "tests/test_holiday_base.py::TestArgs::test_serialization", "tests/test_holiday_base.py::TestArgs::test_years", "tests/test_holiday_base.py::TestKeyTransforms::test_date", "tests/test_holiday_base.py::TestKeyTransforms::test_date_derived", "tests/test_holiday_base.py::TestKeyTransforms::test_datetime", "tests/test_holiday_base.py::TestKeyTransforms::test_exception", "tests/test_holiday_base.py::TestKeyTransforms::test_string", "tests/test_holiday_base.py::TestKeyTransforms::test_timestamp", "tests/test_holiday_base.py::TestCountryHolidayDeprecation::test_deprecation", "tests/test_holiday_base.py::TestCountrySpecialHolidays::test_populate_special_holidays", "tests/test_holiday_base.py::TestHolidaysTranslation::test_language_unavailable" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-06-21 15:53:34+00:00
mit
1,987
dr-prodigy__python-holidays-371
diff --git a/holidays/countries/croatia.py b/holidays/countries/croatia.py index 519fe18b..0136f1e3 100644 --- a/holidays/countries/croatia.py +++ b/holidays/countries/croatia.py @@ -11,18 +11,18 @@ # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) -from datetime import date +from datetime import date, timedelta from dateutil.easter import easter -from dateutil.relativedelta import relativedelta as rd -from holidays.constants import JAN, MAY, JUN, AUG, OCT, \ - NOV, DEC +from holidays.constants import JAN, MAY, JUN, AUG, OCT, NOV, DEC from holidays.holiday_base import HolidayBase class Croatia(HolidayBase): + # Updated with act 022-03 / 19-01 / 219 of 14 November 2019 + # https://narodne-novine.nn.hr/clanci/sluzbeni/2019_11_110_2212.html # https://en.wikipedia.org/wiki/Public_holidays_in_Croatia def __init__(self, **kwargs): @@ -32,6 +32,7 @@ class Croatia(HolidayBase): def _populate(self, year): # New years self[date(year, JAN, 1)] = "Nova Godina" + # Epiphany self[date(year, JAN, 6)] = "Sveta tri kralja" easter_date = easter(year) @@ -39,23 +40,23 @@ class Croatia(HolidayBase): # Easter self[easter_date] = "Uskrs" # Easter Monday - self[easter_date + rd(days=1)] = "Uskršnji ponedjeljak" + self[easter_date + timedelta(days=1)] = "Uskrsni ponedjeljak" # Corpus Christi - self[easter_date + rd(days=60)] = "Tijelovo" + self[easter_date + timedelta(days=60)] = "Tijelovo" # International Workers' Day self[date(year, MAY, 1)] = "Međunarodni praznik rada" + # Statehood day (new) if year >= 2020: - # Statehood day self[date(year, MAY, 30)] = "Dan državnosti" # Anti-fascist struggle day self[date(year, JUN, 22)] = "Dan antifašističke borbe" + # Statehood day (old) if year < 2020: - # Statehood day self[date(year, JUN, 25)] = "Dan državnosti" # Victory and Homeland Thanksgiving Day @@ -64,17 +65,16 @@ class Croatia(HolidayBase): # Assumption of Mary self[date(year, AUG, 15)] = "Velika Gospa" + # Independence Day (old) if year < 2020: - # Independence Day self[date(year, OCT, 8)] = "Dan neovisnosti" # All Saints' Day - self[date(year, NOV, 1)] = "Dan svih svetih" + self[date(year, NOV, 1)] = "Svi sveti" if year >= 2020: # Memorial day - self[date(year, NOV, 18)] =\ - "Dan sjećanja na žrtve Domovinskog rata" + self[date(year, NOV, 18)] = "Dan sjećanja" # Christmas day self[date(year, DEC, 25)] = "Božić" diff --git a/holidays/countries/russia.py b/holidays/countries/russia.py index 8e935295..41d36c92 100644 --- a/holidays/countries/russia.py +++ b/holidays/countries/russia.py @@ -53,8 +53,12 @@ class Russia(HolidayBase): self[date(year, MAY, 9)] = "День Победы" # Russia's Day self[date(year, JUN, 12)] = "День России" - # Unity Day - self[date(year, NOV, 4)] = "День народного единства" + if year >= 2005: + # Unity Day + self[date(year, NOV, 4)] = "День народного единства" + else: + # October Revolution Day + self[date(year, NOV, 7)] = "День Октябрьской революции" class RU(Russia): diff --git a/holidays/countries/united_kingdom.py b/holidays/countries/united_kingdom.py index 4054b559..dfa92fae 100644 --- a/holidays/countries/united_kingdom.py +++ b/holidays/countries/united_kingdom.py @@ -166,6 +166,8 @@ class UnitedKingdom(HolidayBase): # Boxing Day name = "Boxing Day" + if self.country == "Ireland": + name = "St. Stephen's Day" self[date(year, DEC, 26)] = name if self.observed and date(year, DEC, 26).weekday() == SAT: self[date(year, DEC, 28)] = name + " (Observed)" diff --git a/holidays/countries/united_states.py b/holidays/countries/united_states.py index 595005e5..428eac78 100644 --- a/holidays/countries/united_states.py +++ b/holidays/countries/united_states.py @@ -452,12 +452,12 @@ class UnitedStates(HolidayBase): # American Indian Heritage Day # Family Day # New Mexico Presidents' Day - if (self.state in ('DE', 'FL', 'NH', 'NC', 'OK', 'TX', 'WV') and + if (self.state in ('CA', 'DE', 'FL', 'NH', 'NC', 'OK', 'TX', 'WV') and year >= 1975) \ or (self.state == 'IN' and year >= 2010) \ or (self.state == 'MD' and year >= 2008) \ or self.state in ('NV', 'NM'): - if self.state in ('DE', 'NH', 'NC', 'OK', 'WV'): + if self.state in ('CA', 'DE', 'NH', 'NC', 'OK', 'WV'): name = "Day After Thanksgiving" elif self.state in ('FL', 'TX'): name = "Friday After Thanksgiving"
dr-prodigy/python-holidays
5ead4697d65317cf22d17571f2843ea323733a75
diff --git a/tests.py b/tests.py index 6832fdd4..43adb74c 100644 --- a/tests.py +++ b/tests.py @@ -1937,6 +1937,7 @@ class TestUS(unittest.TestCase): self.assertIn(date(2017, 11, 20), pr_holidays) def test_thanksgiving_day(self): + ca_holidays = holidays.US(state='CA') de_holidays = holidays.US(state='DE') fl_holidays = holidays.US(state='FL') in_holidays = holidays.US(state='IN') @@ -1955,6 +1956,8 @@ class TestUS(unittest.TestCase): self.assertNotIn(dt + relativedelta(days=-1), self.holidays) self.assertNotIn(dt + relativedelta(days=+1), self.holidays) self.assertIn(dt + relativedelta(days=+1), de_holidays) + self.assertEqual(ca_holidays.get(dt + relativedelta(days=+1)), + "Day After Thanksgiving") self.assertEqual(de_holidays.get(dt + relativedelta(days=+1)), "Day After Thanksgiving") self.assertEqual(nh_holidays.get(dt + relativedelta(days=+1)), @@ -4949,6 +4952,9 @@ class TestCroatia(unittest.TestCase): self.assertIn(date(2018, 11, 1), self.holidays) self.assertIn(date(2018, 12, 25), self.holidays) self.assertIn(date(2018, 12, 26), self.holidays) + + def test_2020_new(self): + self.assertIn(date(2020, 5, 30), self.holidays) self.assertIn(date(2020, 11, 18), self.holidays) @@ -5282,6 +5288,10 @@ class TestRussia(unittest.TestCase): def setUp(self): self.holidays = holidays.RU() + + def test_before_2005(self): + self.assertIn(date(2004, 11, 7), self.holidays) + self.assertNotIn(date(2004, 11, 4), self.holidays) def test_2018(self): # https://en.wikipedia.org/wiki/Public_holidays_in_Russia @@ -5299,6 +5309,7 @@ class TestRussia(unittest.TestCase): self.assertIn(date(2018, 5, 9), self.holidays) self.assertIn(date(2018, 6, 12), self.holidays) self.assertIn(date(2018, 11, 4), self.holidays) + self.assertNotIn(date(2018, 11, 7), self.holidays) class TestLatvia(unittest.TestCase):
Wrong workday info for country HR Today (Oct. 8, 2020) my alarmclock automation did not go off, because my workday sensor gave the wrong info (no workday). This day used to be a holiday in Croatia, but is not anymore. binary_sensor: - platform: workday country: HR ![image](https://user-images.githubusercontent.com/61622258/95419607-4082d000-093a-11eb-904c-77a2639b1719.png)
0.0
5ead4697d65317cf22d17571f2843ea323733a75
[ "tests.py::TestUS::test_thanksgiving_day", "tests.py::TestRussia::test_before_2005" ]
[ "tests.py::TestBasics::test_add", "tests.py::TestBasics::test_append", "tests.py::TestBasics::test_contains", "tests.py::TestBasics::test_eq_ne", "tests.py::TestBasics::test_get", "tests.py::TestBasics::test_get_list", "tests.py::TestBasics::test_get_named", "tests.py::TestBasics::test_getitem", "tests.py::TestBasics::test_inheritance", "tests.py::TestBasics::test_list_supported_countries", "tests.py::TestBasics::test_pop", "tests.py::TestBasics::test_pop_named", "tests.py::TestBasics::test_radd", "tests.py::TestBasics::test_setitem", "tests.py::TestBasics::test_update", "tests.py::TestArgs::test_country", "tests.py::TestArgs::test_expand", "tests.py::TestArgs::test_observed", "tests.py::TestArgs::test_years", "tests.py::TestKeyTransforms::test_dates", "tests.py::TestKeyTransforms::test_datetimes", "tests.py::TestKeyTransforms::test_exceptions", "tests.py::TestKeyTransforms::test_strings", "tests.py::TestKeyTransforms::test_timestamp", "tests.py::TestCountryHoliday::test_country", "tests.py::TestCountryHoliday::test_country_province", "tests.py::TestCountryHoliday::test_country_state", "tests.py::TestCountryHoliday::test_country_years", "tests.py::TestCountryHoliday::test_exceptions", "tests.py::TestAruba::test_2017", "tests.py::TestAruba::test_anthem_and_flag_day", "tests.py::TestAruba::test_ascension_day", "tests.py::TestAruba::test_betico_day", "tests.py::TestAruba::test_carnaval_monday", "tests.py::TestAruba::test_christmas", "tests.py::TestAruba::test_easter_monday", "tests.py::TestAruba::test_good_friday", "tests.py::TestAruba::test_kings_day_after_2014", "tests.py::TestAruba::test_kings_day_after_2014_substituted_earlier", "tests.py::TestAruba::test_labour_day", "tests.py::TestAruba::test_new_years", "tests.py::TestAruba::test_queens_day_between_1891_and_1948", "tests.py::TestAruba::test_queens_day_between_1891_and_1948_substituted_later", "tests.py::TestAruba::test_queens_day_between_1949_and_1980_substituted_later", "tests.py::TestAruba::test_queens_day_between_1949_and_2013", "tests.py::TestAruba::test_queens_day_between_1980_and_2013_substituted_earlier", "tests.py::TestAruba::test_second_christmas", "tests.py::TestBulgaria::test_before_1990", "tests.py::TestBulgaria::test_christmas", "tests.py::TestBulgaria::test_easter", "tests.py::TestBulgaria::test_independence_day", "tests.py::TestBulgaria::test_labour_day", "tests.py::TestBulgaria::test_liberation_day", "tests.py::TestBulgaria::test_national_awakening_day", "tests.py::TestBulgaria::test_new_years_day", "tests.py::TestBulgaria::test_saint_georges_day", "tests.py::TestBulgaria::test_twenty_fourth_of_may", "tests.py::TestBulgaria::test_unification_day", "tests.py::TestCA::test_boxing_day", "tests.py::TestCA::test_canada_day", "tests.py::TestCA::test_christmas_day", "tests.py::TestCA::test_civic_holiday", "tests.py::TestCA::test_discovery_day", "tests.py::TestCA::test_easter_monday", "tests.py::TestCA::test_family_day", "tests.py::TestCA::test_good_friday", "tests.py::TestCA::test_islander_day", "tests.py::TestCA::test_labour_day", "tests.py::TestCA::test_national_aboriginal_day", "tests.py::TestCA::test_new_years", "tests.py::TestCA::test_nunavut_day", "tests.py::TestCA::test_remembrance_day", "tests.py::TestCA::test_st_georges_day", "tests.py::TestCA::test_st_jean_baptiste_day", "tests.py::TestCA::test_st_patricks_day", "tests.py::TestCA::test_thanksgiving", "tests.py::TestCA::test_victoria_day", "tests.py::TestCO::test_2016", "tests.py::TestCO::test_others", "tests.py::TestMX::test_benito_juarez", "tests.py::TestMX::test_change_of_government", "tests.py::TestMX::test_christmas", "tests.py::TestMX::test_constitution_day", "tests.py::TestMX::test_independence_day", "tests.py::TestMX::test_labor_day", "tests.py::TestMX::test_new_years", "tests.py::TestMX::test_revolution_day", "tests.py::TestNetherlands::test_2017", "tests.py::TestNetherlands::test_ascension_day", "tests.py::TestNetherlands::test_easter", "tests.py::TestNetherlands::test_easter_monday", "tests.py::TestNetherlands::test_first_christmas", "tests.py::TestNetherlands::test_kings_day_after_2014", "tests.py::TestNetherlands::test_kings_day_after_2014_substituted_earlier", "tests.py::TestNetherlands::test_liberation_day", "tests.py::TestNetherlands::test_liberation_day_after_1990_in_lustrum_year", "tests.py::TestNetherlands::test_liberation_day_after_1990_non_lustrum_year", "tests.py::TestNetherlands::test_new_years", "tests.py::TestNetherlands::test_queens_day_between_1891_and_1948", "tests.py::TestNetherlands::test_queens_day_between_1891_and_1948_substituted_later", "tests.py::TestNetherlands::test_queens_day_between_1949_and_1980_substituted_later", "tests.py::TestNetherlands::test_queens_day_between_1949_and_2013", "tests.py::TestNetherlands::test_queens_day_between_1980_and_2013_substituted_earlier", "tests.py::TestNetherlands::test_second_christmas", "tests.py::TestNetherlands::test_whit_monday", "tests.py::TestNetherlands::test_whit_sunday", "tests.py::TestUS::test_alaska_day", "tests.py::TestUS::test_all_souls_day", "tests.py::TestUS::test_arbor_day", "tests.py::TestUS::test_bennington_battle_day", "tests.py::TestUS::test_casimir_pulaski_day", "tests.py::TestUS::test_cesar_chavez_day", "tests.py::TestUS::test_christmas_day", "tests.py::TestUS::test_christmas_eve", "tests.py::TestUS::test_columbus_day", "tests.py::TestUS::test_confederate_memorial_day", "tests.py::TestUS::test_constitution_day", "tests.py::TestUS::test_day_after_christmas", "tests.py::TestUS::test_discovery_day", "tests.py::TestUS::test_easter_monday", "tests.py::TestUS::test_election_day", "tests.py::TestUS::test_emancipation_day", "tests.py::TestUS::test_emancipation_day_in_puerto_rico", "tests.py::TestUS::test_emancipation_day_in_texas", "tests.py::TestUS::test_emancipation_day_in_virgin_islands", "tests.py::TestUS::test_epiphany", "tests.py::TestUS::test_evacuation_day", "tests.py::TestUS::test_good_friday", "tests.py::TestUS::test_guam_discovery_day", "tests.py::TestUS::test_holy_thursday", "tests.py::TestUS::test_inauguration_day", "tests.py::TestUS::test_independence_day", "tests.py::TestUS::test_jefferson_davis_birthday", "tests.py::TestUS::test_kamehameha_day", "tests.py::TestUS::test_labor_day", "tests.py::TestUS::test_lady_of_camarin_day", "tests.py::TestUS::test_lee_jackson_day", "tests.py::TestUS::test_liberation_day_guam", "tests.py::TestUS::test_liberty_day", "tests.py::TestUS::test_lincolns_birthday", "tests.py::TestUS::test_lyndon_baines_johnson_day", "tests.py::TestUS::test_mardi_gras", "tests.py::TestUS::test_martin_luther", "tests.py::TestUS::test_memorial_day", "tests.py::TestUS::test_nevada_day", "tests.py::TestUS::test_new_years", "tests.py::TestUS::test_new_years_eve", "tests.py::TestUS::test_patriots_day", "tests.py::TestUS::test_pioneer_day", "tests.py::TestUS::test_primary_election_day", "tests.py::TestUS::test_prince_jonah_kuhio_kalanianaole_day", "tests.py::TestUS::test_robert_lee_birthday", "tests.py::TestUS::test_san_jacinto_day", "tests.py::TestUS::test_statehood_day", "tests.py::TestUS::test_stewards_day", "tests.py::TestUS::test_susan_b_anthony_day", "tests.py::TestUS::test_texas_independence_day", "tests.py::TestUS::test_three_kings_day", "tests.py::TestUS::test_town_meeting_day", "tests.py::TestUS::test_transfer_day", "tests.py::TestUS::test_truman_day", "tests.py::TestUS::test_veterans_day", "tests.py::TestUS::test_victory_day", "tests.py::TestUS::test_washingtons_birthday", "tests.py::TestUS::test_west_virginia_day", "tests.py::TestNZ::test_all_holidays_present", "tests.py::TestNZ::test_anzac_day", "tests.py::TestNZ::test_auckland_anniversary_day", "tests.py::TestNZ::test_boxing_day", "tests.py::TestNZ::test_canterbury_anniversary_day", "tests.py::TestNZ::test_chatham_islands_anniversary_day", "tests.py::TestNZ::test_christmas_day", "tests.py::TestNZ::test_day_after_new_years", "tests.py::TestNZ::test_easter_monday", "tests.py::TestNZ::test_good_friday", "tests.py::TestNZ::test_hawkes_bay_anniversary_day", "tests.py::TestNZ::test_labour_day", "tests.py::TestNZ::test_marlborough_anniversary_day", "tests.py::TestNZ::test_nelson_anniversary_day", "tests.py::TestNZ::test_new_years", "tests.py::TestNZ::test_otago_anniversary_day", "tests.py::TestNZ::test_south_canterbury_anniversary_day", "tests.py::TestNZ::test_southland_anniversary_day", "tests.py::TestNZ::test_sovereigns_birthday", "tests.py::TestNZ::test_taranaki_anniversary_day", "tests.py::TestNZ::test_waitangi_day", "tests.py::TestNZ::test_wellington_anniversary_day", "tests.py::TestNZ::test_westland_anniversary_day", "tests.py::TestAU::test_adelaide_cup", "tests.py::TestAU::test_all_holidays", "tests.py::TestAU::test_anzac_day", "tests.py::TestAU::test_australia_day", "tests.py::TestAU::test_bank_holiday", "tests.py::TestAU::test_boxing_day", "tests.py::TestAU::test_christmas_day", "tests.py::TestAU::test_easter_monday", "tests.py::TestAU::test_easter_saturday", "tests.py::TestAU::test_easter_sunday", "tests.py::TestAU::test_family_and_community_day", "tests.py::TestAU::test_good_friday", "tests.py::TestAU::test_grand_final_day", "tests.py::TestAU::test_labour_day", "tests.py::TestAU::test_melbourne_cup", "tests.py::TestAU::test_new_years", "tests.py::TestAU::test_picnic_day", "tests.py::TestAU::test_queens_birthday", "tests.py::TestAU::test_reconciliation_day", "tests.py::TestAU::test_royal_queensland_show", "tests.py::TestAU::test_western_australia_day", "tests.py::TestDE::test_75_jahrestag_beendigung_zweiter_weltkrieg", "tests.py::TestDE::test_all_holidays_present", "tests.py::TestDE::test_allerheiligen", "tests.py::TestDE::test_buss_und_bettag", "tests.py::TestDE::test_christi_himmelfahrt", "tests.py::TestDE::test_fixed_holidays", "tests.py::TestDE::test_frauentag", "tests.py::TestDE::test_fronleichnam", "tests.py::TestDE::test_heilige_drei_koenige", "tests.py::TestDE::test_internationaler_frauentag", "tests.py::TestDE::test_karfreitag", "tests.py::TestDE::test_mariae_himmelfahrt", "tests.py::TestDE::test_no_data_before_1990", "tests.py::TestDE::test_ostermontag", "tests.py::TestDE::test_ostersonntag", "tests.py::TestDE::test_pfingstmontag", "tests.py::TestDE::test_pfingstsonntag", "tests.py::TestDE::test_reformationstag", "tests.py::TestDE::test_tag_der_deutschen_einheit_in_1990", "tests.py::TestDE::test_weltkindertag", "tests.py::TestAT::test_all_holidays_present", "tests.py::TestAT::test_christmas", "tests.py::TestAT::test_easter_monday", "tests.py::TestAT::test_national_day", "tests.py::TestAT::test_new_years", "tests.py::TestDK::test_2016", "tests.py::TestUK::test_all_holidays_present", "tests.py::TestUK::test_boxing_day", "tests.py::TestUK::test_christmas_day", "tests.py::TestUK::test_easter_monday", "tests.py::TestUK::test_good_friday", "tests.py::TestUK::test_may_day", "tests.py::TestUK::test_new_years", "tests.py::TestUK::test_royal_wedding", "tests.py::TestUK::test_spring_bank_holiday", "tests.py::TestScotland::test_2017", "tests.py::TestIsleOfMan::test_2018", "tests.py::TestIreland::test_2020", "tests.py::TestES::test_fixed_holidays", "tests.py::TestES::test_province_specific_days", "tests.py::TestES::test_variable_days_in_2016", "tests.py::TestTAR::test_26_december_day", "tests.py::TestTAR::test_all_holidays_present", "tests.py::TestTAR::test_christmas_day", "tests.py::TestTAR::test_easter_monday", "tests.py::TestTAR::test_good_friday", "tests.py::TestTAR::test_labour_day", "tests.py::TestTAR::test_new_years", "tests.py::TestECB::test_new_years", "tests.py::TestCZ::test_2017", "tests.py::TestCZ::test_czech_deprecated", "tests.py::TestCZ::test_others", "tests.py::TestSK::test_2018", "tests.py::TestSK::test_slovak_deprecated", "tests.py::TestPL::test_2017", "tests.py::TestPL::test_polish_deprecated", "tests.py::TestPT::test_2017", "tests.py::TestPortugalExt::test_2017", "tests.py::TestNorway::test_christmas", "tests.py::TestNorway::test_constitution_day", "tests.py::TestNorway::test_easter", "tests.py::TestNorway::test_new_years", "tests.py::TestNorway::test_not_holiday", "tests.py::TestNorway::test_pentecost", "tests.py::TestNorway::test_sundays", "tests.py::TestNorway::test_workers_day", "tests.py::TestItaly::test_2017", "tests.py::TestItaly::test_christmas", "tests.py::TestItaly::test_easter", "tests.py::TestItaly::test_easter_monday", "tests.py::TestItaly::test_liberation_day_after_1946", "tests.py::TestItaly::test_liberation_day_before_1946", "tests.py::TestItaly::test_new_years", "tests.py::TestItaly::test_province_specific_days", "tests.py::TestItaly::test_republic_day_after_1948", "tests.py::TestItaly::test_republic_day_before_1948", "tests.py::TestItaly::test_saint_stephan", "tests.py::TestSweden::test_christmas", "tests.py::TestSweden::test_constitution_day", "tests.py::TestSweden::test_easter", "tests.py::TestSweden::test_new_years", "tests.py::TestSweden::test_not_holiday", "tests.py::TestSweden::test_pentecost", "tests.py::TestSweden::test_sundays", "tests.py::TestSweden::test_workers_day", "tests.py::TestJapan::test_autumnal_equinox_day", "tests.py::TestJapan::test_childrens_day", "tests.py::TestJapan::test_coming_of_age", "tests.py::TestJapan::test_constitution_memorial_day", "tests.py::TestJapan::test_culture_day", "tests.py::TestJapan::test_emperors_birthday", "tests.py::TestJapan::test_foundation_day", "tests.py::TestJapan::test_greenery_day", "tests.py::TestJapan::test_health_and_sports_day", "tests.py::TestJapan::test_invalid_years", "tests.py::TestJapan::test_labour_thanks_giving_day", "tests.py::TestJapan::test_marine_day", "tests.py::TestJapan::test_mountain_day", "tests.py::TestJapan::test_new_years_day", "tests.py::TestJapan::test_reiwa_emperor_holidays", "tests.py::TestJapan::test_respect_for_the_aged_day", "tests.py::TestJapan::test_showa_day", "tests.py::TestJapan::test_vernal_equinox_day", "tests.py::TestFrance::test_2017", "tests.py::TestFrance::test_alsace_moselle", "tests.py::TestFrance::test_guadeloupe", "tests.py::TestFrance::test_guyane", "tests.py::TestFrance::test_la_reunion", "tests.py::TestFrance::test_martinique", "tests.py::TestFrance::test_mayotte", "tests.py::TestFrance::test_nouvelle_caledonie", "tests.py::TestFrance::test_others", "tests.py::TestFrance::test_polynesie_francaise", "tests.py::TestFrance::test_saint_barthelemy", "tests.py::TestFrance::test_wallis_et_futuna", "tests.py::TestBelgium::test_2017", "tests.py::TestSouthAfrica::test_easter", "tests.py::TestSouthAfrica::test_elections", "tests.py::TestSouthAfrica::test_historic", "tests.py::TestSouthAfrica::test_new_years", "tests.py::TestSouthAfrica::test_not_holiday", "tests.py::TestSouthAfrica::test_onceoff", "tests.py::TestSouthAfrica::test_static", "tests.py::TestSI::test_holidays", "tests.py::TestSI::test_missing_years", "tests.py::TestSI::test_non_holidays", "tests.py::TestIE::test_august_bank_holiday", "tests.py::TestIE::test_christmas_period", "tests.py::TestIE::test_easter_monday", "tests.py::TestIE::test_june_bank_holiday", "tests.py::TestIE::test_may_bank_holiday", "tests.py::TestIE::test_new_year_day", "tests.py::TestIE::test_october_bank_holiday", "tests.py::TestIE::test_st_patricks_day", "tests.py::TestFinland::test_Juhannus", "tests.py::TestFinland::test_fixed_holidays", "tests.py::TestFinland::test_relative_holidays", "tests.py::TestHungary::test_2018", "tests.py::TestHungary::test_additional_day_off", "tests.py::TestHungary::test_all_saints_day_since_1999", "tests.py::TestHungary::test_christian_holidays_2nd_day_was_not_held_in_1955", "tests.py::TestHungary::test_foundation_day_renamed_during_communism", "tests.py::TestHungary::test_good_friday_since_2017", "tests.py::TestHungary::test_holidays_during_communism", "tests.py::TestHungary::test_labour_day_since_1946", "tests.py::TestHungary::test_labour_day_was_doubled_in_early_50s", "tests.py::TestHungary::test_monday_new_years_eve_day_off", "tests.py::TestHungary::test_national_day_was_not_celebrated_during_communism", "tests.py::TestHungary::test_october_national_day_since_1991", "tests.py::TestHungary::test_whit_monday_since_1992", "tests.py::TestSwitzerland::test_all_holidays_present", "tests.py::TestSwitzerland::test_allerheiligen", "tests.py::TestSwitzerland::test_auffahrt", "tests.py::TestSwitzerland::test_berchtoldstag", "tests.py::TestSwitzerland::test_bruder_chlaus", "tests.py::TestSwitzerland::test_fest_der_unabhaengikeit", "tests.py::TestSwitzerland::test_fixed_holidays", "tests.py::TestSwitzerland::test_fronleichnam", "tests.py::TestSwitzerland::test_heilige_drei_koenige", "tests.py::TestSwitzerland::test_jahrestag_der_ausrufung_der_republik", "tests.py::TestSwitzerland::test_jeune_genevois", "tests.py::TestSwitzerland::test_josefstag", "tests.py::TestSwitzerland::test_karfreitag", "tests.py::TestSwitzerland::test_lundi_du_jeune", "tests.py::TestSwitzerland::test_mariae_himmelfahrt", "tests.py::TestSwitzerland::test_naefelser_fahrt", "tests.py::TestSwitzerland::test_ostermontag", "tests.py::TestSwitzerland::test_ostern", "tests.py::TestSwitzerland::test_peter_und_paul", "tests.py::TestSwitzerland::test_pfingsten", "tests.py::TestSwitzerland::test_pfingstmontag", "tests.py::TestSwitzerland::test_stephanstag", "tests.py::TestSwitzerland::test_wiedererstellung_der_republik", "tests.py::TestAR::test_belgrano_day", "tests.py::TestAR::test_carnival_day", "tests.py::TestAR::test_christmas", "tests.py::TestAR::test_cultural_day", "tests.py::TestAR::test_guemes_day", "tests.py::TestAR::test_holy_week_day", "tests.py::TestAR::test_independence_day", "tests.py::TestAR::test_inmaculate_conception_day", "tests.py::TestAR::test_labor_day", "tests.py::TestAR::test_malvinas_war_day", "tests.py::TestAR::test_may_revolution_day", "tests.py::TestAR::test_memory_national_day", "tests.py::TestAR::test_national_sovereignty_day", "tests.py::TestAR::test_new_years", "tests.py::TestAR::test_san_martin_day", "tests.py::TestIND::test_2018", "tests.py::TestBelarus::test_2018", "tests.py::TestBelarus::test_before_1998", "tests.py::TestBelarus::test_new_year", "tests.py::TestBelarus::test_radunitsa", "tests.py::TestHonduras::test_2014", "tests.py::TestHonduras::test_2018", "tests.py::TestCroatia::test_2018", "tests.py::TestCroatia::test_2020_new", "tests.py::TestUkraine::test_2018", "tests.py::TestUkraine::test_before_1918", "tests.py::TestUkraine::test_old_holidays", "tests.py::TestBrazil::test_AC_holidays", "tests.py::TestBrazil::test_AL_holidays", "tests.py::TestBrazil::test_AM_holidays", "tests.py::TestBrazil::test_AP_holidays", "tests.py::TestBrazil::test_BA_holidays", "tests.py::TestBrazil::test_BR_holidays", "tests.py::TestBrazil::test_CE_holidays", "tests.py::TestBrazil::test_DF_holidays", "tests.py::TestBrazil::test_ES_holidays", "tests.py::TestBrazil::test_GO_holidays", "tests.py::TestBrazil::test_MA_holidays", "tests.py::TestBrazil::test_MG_holidays", "tests.py::TestBrazil::test_MS_holidays", "tests.py::TestBrazil::test_MT_holidays", "tests.py::TestBrazil::test_PA_holidays", "tests.py::TestBrazil::test_PB_holidays", "tests.py::TestBrazil::test_PE_holidays", "tests.py::TestBrazil::test_PI_holidays", "tests.py::TestBrazil::test_PR_holidays", "tests.py::TestBrazil::test_RJ_holidays", "tests.py::TestBrazil::test_RN_holidays", "tests.py::TestBrazil::test_RO_holidays", "tests.py::TestBrazil::test_RR_holidays", "tests.py::TestBrazil::test_RS_holidays", "tests.py::TestBrazil::test_SC_holidays", "tests.py::TestBrazil::test_SE_holidays", "tests.py::TestBrazil::test_SP_holidays", "tests.py::TestBrazil::test_TO_holidays", "tests.py::TestLU::test_2019", "tests.py::TestRomania::test_2020", "tests.py::TestRomania::test_children_s_day", "tests.py::TestRussia::test_2018", "tests.py::TestLatvia::test_2020", "tests.py::TestLithuania::test_2018", "tests.py::TestLithuania::test_day_of_dew", "tests.py::TestLithuania::test_easter", "tests.py::TestLithuania::test_fathers_day", "tests.py::TestLithuania::test_mothers_day", "tests.py::TestEstonia::test_boxing_day", "tests.py::TestEstonia::test_christmas_day", "tests.py::TestEstonia::test_christmas_eve", "tests.py::TestEstonia::test_easter_sunday", "tests.py::TestEstonia::test_good_friday", "tests.py::TestEstonia::test_independence_day", "tests.py::TestEstonia::test_midsummers_day", "tests.py::TestEstonia::test_new_years", "tests.py::TestEstonia::test_pentecost", "tests.py::TestEstonia::test_restoration_of_independence_day", "tests.py::TestEstonia::test_spring_day", "tests.py::TestEstonia::test_victory_day", "tests.py::TestIceland::test_commerce_day", "tests.py::TestIceland::test_first_day_of_summer", "tests.py::TestIceland::test_holy_friday", "tests.py::TestIceland::test_maundy_thursday", "tests.py::TestIceland::test_new_year", "tests.py::TestKenya::test_2019", "tests.py::TestHongKong::test_ching_ming_festival", "tests.py::TestHongKong::test_christmas_day", "tests.py::TestHongKong::test_chung_yeung_festival", "tests.py::TestHongKong::test_common", "tests.py::TestHongKong::test_easter", "tests.py::TestHongKong::test_first_day_of_january", "tests.py::TestHongKong::test_hksar_day", "tests.py::TestHongKong::test_labour_day", "tests.py::TestHongKong::test_lunar_new_year", "tests.py::TestHongKong::test_mid_autumn_festival", "tests.py::TestHongKong::test_national_day", "tests.py::TestHongKong::test_tuen_ng_festival", "tests.py::TestPeru::test_2019", "tests.py::TestNigeria::test_fixed_holidays", "tests.py::TestChile::test_2019", "tests.py::TestDominicanRepublic::test_do_holidays_2020", "tests.py::TestNicaragua::test_ni_holidays_2020", "tests.py::TestSingapore::test_Singapore", "tests.py::TestSerbia::test_armistice_day", "tests.py::TestSerbia::test_labour_day", "tests.py::TestSerbia::test_new_year", "tests.py::TestSerbia::test_religious_holidays", "tests.py::TestSerbia::test_statehood_day", "tests.py::TestEgypt::test_2019", "tests.py::TestEgypt::test_25_jan", "tests.py::TestEgypt::test_25_jan_from_2009", "tests.py::TestEgypt::test_coptic_christmas", "tests.py::TestEgypt::test_hijri_based", "tests.py::TestEgypt::test_labour_day", "tests.py::TestGreece::test_fixed_holidays", "tests.py::TestGreece::test_gr_clean_monday", "tests.py::TestGreece::test_gr_easter_monday", "tests.py::TestGreece::test_gr_monday_of_the_holy_spirit", "tests.py::TestParaguay::test_easter", "tests.py::TestParaguay::test_fixed_holidays", "tests.py::TestParaguay::test_no_observed", "tests.py::TestTurkey::test_2019", "tests.py::TestTurkey::test_hijri_based", "tests.py::TestKorea::test_birthday_of_buddha", "tests.py::TestKorea::test_childrens_day", "tests.py::TestKorea::test_christmas_day", "tests.py::TestKorea::test_chuseok", "tests.py::TestKorea::test_common", "tests.py::TestKorea::test_constitution_day", "tests.py::TestKorea::test_first_day_of_january", "tests.py::TestKorea::test_hangeul_day", "tests.py::TestKorea::test_independence_movement_day", "tests.py::TestKorea::test_labour_day", "tests.py::TestKorea::test_liberation_day", "tests.py::TestKorea::test_lunar_new_year", "tests.py::TestKorea::test_memorial_day", "tests.py::TestKorea::test_national_foundation_day", "tests.py::TestKorea::test_tree_planting_day", "tests.py::TestKorea::test_years_range", "tests.py::TestVietnam::test_common", "tests.py::TestVietnam::test_first_day_of_january", "tests.py::TestVietnam::test_independence_day", "tests.py::TestVietnam::test_international_labor_day", "tests.py::TestVietnam::test_king_hung_day", "tests.py::TestVietnam::test_liberation_day", "tests.py::TestVietnam::test_lunar_new_year", "tests.py::TestVietnam::test_years_range", "tests.py::TestMorocco::test_1961", "tests.py::TestMorocco::test_1999", "tests.py::TestMorocco::test_2019", "tests.py::TestMorocco::test_hijri_based", "tests.py::TestBurundi::test_all_saints_Day", "tests.py::TestBurundi::test_ascension_day", "tests.py::TestBurundi::test_assumption_Day", "tests.py::TestBurundi::test_christmas_Day", "tests.py::TestBurundi::test_eid_al_adha", "tests.py::TestBurundi::test_independence_day", "tests.py::TestBurundi::test_labour_day", "tests.py::TestBurundi::test_ndadaye_day", "tests.py::TestBurundi::test_new_year_day", "tests.py::TestBurundi::test_ntaryamira_day", "tests.py::TestBurundi::test_rwagasore_day", "tests.py::TestBurundi::test_unity_day", "tests.py::UnitedArabEmirates::test_2020", "tests.py::UnitedArabEmirates::test_commemoration_day_since_2015", "tests.py::UnitedArabEmirates::test_hijri_based", "tests.py::TestDjibouti::test_2019", "tests.py::TestDjibouti::test_hijri_based", "tests.py::TestDjibouti::test_labour_day" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-08 07:14:22+00:00
mit
1,988
dr-prodigy__python-holidays-469
diff --git a/CHANGES b/CHANGES index 4d38f383..3f990929 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,7 @@ Version 0.11.2 Released ????, ???? +- Support for Venezuela #470 (antusystem, dr-p) - Poland fix #464 (m-ganko) - Singapore updates for 2022 #456 (mborsetti) - .gitignore fix #462 (TheLastProject) diff --git a/README.rst b/README.rst index 4e8df697..cb44ba7c 100644 --- a/README.rst +++ b/README.rst @@ -191,6 +191,7 @@ UnitedStates US/USA state = AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FL FM, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VA, VI, WA, WV, WI, WY +Venezuela YV/VEN Vietnam VN/VNM Wales None =================== ========= ============================================================= diff --git a/holidays/countries/__init__.py b/holidays/countries/__init__.py index 7bb1c290..3584e388 100644 --- a/holidays/countries/__init__.py +++ b/holidays/countries/__init__.py @@ -92,4 +92,5 @@ from .united_kingdom import ( GBR, ) from .united_states import UnitedStates, US, USA +from .venezuela import Venezuela, YV, VEN from .vietnam import Vietnam, VN, VNM diff --git a/holidays/countries/spain.py b/holidays/countries/spain.py index 794032b1..6b2c8dd0 100644 --- a/holidays/countries/spain.py +++ b/holidays/countries/spain.py @@ -117,7 +117,7 @@ class Spain(HolidayBase): self._is_observed(date(year, MAR, 19), "San José") if self.prov and self.prov not in ["CT", "VC"]: self[easter(year) + rd(weeks=-1, weekday=TH)] = "Jueves Santo" - self[easter(year) + rd(weeks=-1, weekday=FR)] = "Viernes Santo" + self[easter(year) + rd(weeks=-1, weekday=FR)] = "Viernes Santo" if self.prov and self.prov in ["CT", "PV", "NC", "VC", "IB", "CM"]: self[easter(year) + rd(weekday=MO)] = "Lunes de Pascua" self._is_observed(date(year, MAY, 1), "Día del Trabajador") diff --git a/holidays/countries/venezuela.py b/holidays/countries/venezuela.py new file mode 100644 index 00000000..020a0122 --- /dev/null +++ b/holidays/countries/venezuela.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- + +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Author: ryanss <[email protected]> (c) 2014-2017 +# dr-prodigy <[email protected]> (c) 2017-2021 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from datetime import date + +from dateutil.easter import easter +from dateutil.relativedelta import relativedelta as rd, TH, FR + +from holidays.constants import ( + JAN, + MAR, + APR, + MAY, + JUN, + JUL, + AUG, + SEP, + OCT, + NOV, + DEC, +) +from holidays.holiday_base import HolidayBase + + +class Venezuela(HolidayBase): + """ + https://dias-festivos.eu/dias-festivos/venezuela/# + """ + + def __init__(self, **kwargs): + self.country = "YV" + HolidayBase.__init__(self, **kwargs) + + def _populate(self, year): + # New Year's Day + self[date(year, JAN, 1)] = "Año Nuevo [New Year's Day]" + + self[date(year, MAY, 1)] = "Dia Mundial del Trabajador" + + self[date(year, JUN, 24)] = "Batalla de Carabobo" + + self[date(year, JUL, 5)] = "Dia de la Independencia" + + self[date(year, JUL, 24)] = "Natalicio de Simón Bolívar" + + self[date(year, OCT, 12)] = "Día de la Resistencia Indígena" + + # Christmas Day + self[date(year, DEC, 24)] = "Nochebuena" + + self[date(year, DEC, 25)] = "Día de Navidad" + + self[date(year, DEC, 31)] = "Fiesta de Fin de Año" + + # Semana Santa y Carnaval + + if date(year, APR, 19) == (easter(year) - rd(days=2)): + self[ + easter(year) - rd(days=2) + ] = "Viernes Santo y Declaración de la Independencia" + else: + # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo" + self[date(year, APR, 19)] = "Declaración de la Independencia" + self[easter(year) - rd(days=2)] = "Viernes Santo" + + # self[easter(year) - rd(weekday=TH(-1))] = "Jueves Santo" + + if date(year, APR, 19) == (easter(year) - rd(days=3)): + self[easter(year) - rd(days=3)] = ( + "Jueves Santo y Declaración " "de la Independencia" + ) + else: + # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo" + self[date(year, APR, 19)] = "Declaración de la Independencia" + self[easter(year) - rd(days=3)] = "Jueves Santo" + + self[easter(year) - rd(days=47)] = "Martes de Carnaval" + + self[easter(year) - rd(days=48)] = "Lunes de Carnaval" + + +class YV(Venezuela): + pass + + +class VEN(Venezuela): + pass
dr-prodigy/python-holidays
a33745d6c356770a0c48949fdad262f71da403f2
diff --git a/test/countries/__init__.py b/test/countries/__init__.py index d0d28686..321e65f1 100644 --- a/test/countries/__init__.py +++ b/test/countries/__init__.py @@ -82,4 +82,5 @@ from .test_ukraine import * from .test_united_arab_emirates import * from .test_united_kingdom import * from .test_united_states import * +from .test_venezuela import * from .test_vietnam import * diff --git a/test/countries/test_spain.py b/test/countries/test_spain.py index 7e8baaa5..355e1359 100644 --- a/test/countries/test_spain.py +++ b/test/countries/test_spain.py @@ -63,9 +63,7 @@ class TestES(unittest.TestCase): self.assertEqual( date(2016, 3, 24) in prov_holidays, prov not in ["CT", "VC"] ) - self.assertEqual( - date(2016, 3, 25) in prov_holidays, prov not in ["CT", "VC"] - ) + assert date(2016, 3, 25) in prov_holidays self.assertEqual( date(2016, 3, 28) in prov_holidays, prov in ["CT", "PV", "NC", "VC", "IB", "CM"], diff --git a/test/countries/test_venezuela.py b/test/countries/test_venezuela.py new file mode 100644 index 00000000..c7ab4631 --- /dev/null +++ b/test/countries/test_venezuela.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Author: ryanss <[email protected]> (c) 2014-2017 +# dr-prodigy <[email protected]> (c) 2017-2021 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +import unittest + +from datetime import date + +import holidays + + +class TestVenezuela(unittest.TestCase): + def test_YV_holidays(self): + self.holidays = holidays.YV(years=2019) + self.assertIn("2019-01-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 1, 1)], "Año Nuevo [New Year's Day]" + ) + self.assertIn("2019-03-04", self.holidays) + self.assertEqual( + self.holidays[date(2019, 3, 4)], + "Lunes de Carnaval", + ) + self.assertIn("2019-03-05", self.holidays) + self.assertEqual(self.holidays[date(2019, 3, 5)], "Martes de Carnaval") + self.assertIn("2019-04-18", self.holidays) + self.assertEqual(self.holidays[date(2019, 4, 18)], "Jueves Santo") + self.assertIn("2019-04-19", self.holidays) + self.assertEqual( + self.holidays[date(2019, 4, 19)], + "Viernes Santo y Declaración de la Independencia", + ) + self.assertIn("2019-05-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 5, 1)], "Dia Mundial del Trabajador" + ) + self.assertIn("2019-06-24", self.holidays) + self.assertEqual( + self.holidays[date(2019, 6, 24)], "Batalla de Carabobo" + ) + self.assertIn("2019-05-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 7, 5)], "Dia de la Independencia" + ) + self.assertIn("2019-07-24", self.holidays) + self.assertEqual( + self.holidays[date(2019, 7, 24)], "Natalicio de Simón Bolívar" + ) + self.assertIn("2019-10-12", self.holidays) + self.assertEqual( + self.holidays[date(2019, 10, 12)], "Día de la Resistencia Indígena" + ) + self.assertIn("2019-12-24", self.holidays) + self.assertEqual(self.holidays[date(2019, 12, 24)], "Nochebuena") + self.assertIn("2019-12-25", self.holidays) + self.assertEqual(self.holidays[date(2019, 12, 25)], "Día de Navidad") + self.assertIn("2019-12-31", self.holidays) + self.assertEqual( + self.holidays[date(2019, 12, 31)], "Fiesta de Fin de Año" + )
2 april 2021 in spain hi, dt.date(2021, 4, 2) in holidays.ES() don't work
0.0
a33745d6c356770a0c48949fdad262f71da403f2
[ "test/countries/__init__.py::TestES::test_variable_days_in_2016", "test/countries/__init__.py::TestVenezuela::test_YV_holidays", "test/countries/test_spain.py::TestES::test_variable_days_in_2016", "test/countries/test_venezuela.py::TestVenezuela::test_YV_holidays" ]
[ "test/countries/__init__.py::TestAngola::test_easter", "test/countries/__init__.py::TestAngola::test_long_weekend", "test/countries/__init__.py::TestAngola::test_new_years", "test/countries/__init__.py::TestAngola::test_not_holiday", "test/countries/__init__.py::TestAngola::test_static", "test/countries/__init__.py::TestAR::test_belgrano_day", "test/countries/__init__.py::TestAR::test_carnival_day", "test/countries/__init__.py::TestAR::test_christmas", "test/countries/__init__.py::TestAR::test_cultural_day", "test/countries/__init__.py::TestAR::test_guemes_day", "test/countries/__init__.py::TestAR::test_holy_week_day", "test/countries/__init__.py::TestAR::test_independence_day", "test/countries/__init__.py::TestAR::test_inmaculate_conception_day", "test/countries/__init__.py::TestAR::test_labor_day", "test/countries/__init__.py::TestAR::test_malvinas_war_day", "test/countries/__init__.py::TestAR::test_may_revolution_day", "test/countries/__init__.py::TestAR::test_memory_national_day", "test/countries/__init__.py::TestAR::test_national_sovereignty_day", "test/countries/__init__.py::TestAR::test_new_years", "test/countries/__init__.py::TestAR::test_san_martin_day", "test/countries/__init__.py::TestAruba::test_2017", "test/countries/__init__.py::TestAruba::test_anthem_and_flag_day", "test/countries/__init__.py::TestAruba::test_ascension_day", "test/countries/__init__.py::TestAruba::test_betico_day", "test/countries/__init__.py::TestAruba::test_carnaval_monday", "test/countries/__init__.py::TestAruba::test_christmas", "test/countries/__init__.py::TestAruba::test_easter_monday", "test/countries/__init__.py::TestAruba::test_good_friday", "test/countries/__init__.py::TestAruba::test_kings_day_after_2014", "test/countries/__init__.py::TestAruba::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestAruba::test_labour_day", "test/countries/__init__.py::TestAruba::test_new_years", "test/countries/__init__.py::TestAruba::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestAruba::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestAruba::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestAruba::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestAruba::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestAruba::test_second_christmas", "test/countries/__init__.py::TestAU::test_adelaide_cup", "test/countries/__init__.py::TestAU::test_all_holidays", "test/countries/__init__.py::TestAU::test_anzac_day", "test/countries/__init__.py::TestAU::test_australia_day", "test/countries/__init__.py::TestAU::test_bank_holiday", "test/countries/__init__.py::TestAU::test_boxing_day", "test/countries/__init__.py::TestAU::test_christmas_day", "test/countries/__init__.py::TestAU::test_easter_monday", "test/countries/__init__.py::TestAU::test_easter_saturday", "test/countries/__init__.py::TestAU::test_easter_sunday", "test/countries/__init__.py::TestAU::test_family_and_community_day", "test/countries/__init__.py::TestAU::test_good_friday", "test/countries/__init__.py::TestAU::test_grand_final_day", "test/countries/__init__.py::TestAU::test_labour_day", "test/countries/__init__.py::TestAU::test_melbourne_cup", "test/countries/__init__.py::TestAU::test_new_years", "test/countries/__init__.py::TestAU::test_picnic_day", "test/countries/__init__.py::TestAU::test_queens_birthday", "test/countries/__init__.py::TestAU::test_reconciliation_day", "test/countries/__init__.py::TestAU::test_royal_queensland_show", "test/countries/__init__.py::TestAU::test_western_australia_day", "test/countries/__init__.py::TestAT::test_all_holidays_present", "test/countries/__init__.py::TestAT::test_christmas", "test/countries/__init__.py::TestAT::test_easter_monday", "test/countries/__init__.py::TestAT::test_national_day", "test/countries/__init__.py::TestAT::test_new_years", "test/countries/__init__.py::TestBangladesh::test_2020", "test/countries/__init__.py::TestBelarus::test_2018", "test/countries/__init__.py::TestBelarus::test_before_1998", "test/countries/__init__.py::TestBelarus::test_new_year", "test/countries/__init__.py::TestBelarus::test_radunitsa", "test/countries/__init__.py::TestBelgium::test_2017", "test/countries/__init__.py::TestBrazil::test_AC_holidays", "test/countries/__init__.py::TestBrazil::test_AL_holidays", "test/countries/__init__.py::TestBrazil::test_AM_holidays", "test/countries/__init__.py::TestBrazil::test_AP_holidays", "test/countries/__init__.py::TestBrazil::test_BA_holidays", "test/countries/__init__.py::TestBrazil::test_BR_holidays", "test/countries/__init__.py::TestBrazil::test_CE_holidays", "test/countries/__init__.py::TestBrazil::test_DF_holidays", "test/countries/__init__.py::TestBrazil::test_ES_holidays", "test/countries/__init__.py::TestBrazil::test_GO_holidays", "test/countries/__init__.py::TestBrazil::test_MA_holidays", "test/countries/__init__.py::TestBrazil::test_MG_holidays", "test/countries/__init__.py::TestBrazil::test_MS_holidays", "test/countries/__init__.py::TestBrazil::test_MT_holidays", "test/countries/__init__.py::TestBrazil::test_PA_holidays", "test/countries/__init__.py::TestBrazil::test_PB_holidays", "test/countries/__init__.py::TestBrazil::test_PE_holidays", "test/countries/__init__.py::TestBrazil::test_PI_holidays", "test/countries/__init__.py::TestBrazil::test_PR_holidays", "test/countries/__init__.py::TestBrazil::test_RJ_holidays", "test/countries/__init__.py::TestBrazil::test_RN_holidays", "test/countries/__init__.py::TestBrazil::test_RO_holidays", "test/countries/__init__.py::TestBrazil::test_RR_holidays", "test/countries/__init__.py::TestBrazil::test_RS_holidays", "test/countries/__init__.py::TestBrazil::test_SC_holidays", "test/countries/__init__.py::TestBrazil::test_SE_holidays", "test/countries/__init__.py::TestBrazil::test_SP_holidays", "test/countries/__init__.py::TestBrazil::test_TO_holidays", "test/countries/__init__.py::TestBulgaria::test_before_1990", "test/countries/__init__.py::TestBulgaria::test_christmas", "test/countries/__init__.py::TestBulgaria::test_easter", "test/countries/__init__.py::TestBulgaria::test_independence_day", "test/countries/__init__.py::TestBulgaria::test_labour_day", "test/countries/__init__.py::TestBulgaria::test_liberation_day", "test/countries/__init__.py::TestBulgaria::test_national_awakening_day", "test/countries/__init__.py::TestBulgaria::test_new_years_day", "test/countries/__init__.py::TestBulgaria::test_saint_georges_day", "test/countries/__init__.py::TestBulgaria::test_twenty_fourth_of_may", "test/countries/__init__.py::TestBulgaria::test_unification_day", "test/countries/__init__.py::TestBurundi::test_all_saints_Day", "test/countries/__init__.py::TestBurundi::test_ascension_day", "test/countries/__init__.py::TestBurundi::test_assumption_Day", "test/countries/__init__.py::TestBurundi::test_christmas_Day", "test/countries/__init__.py::TestBurundi::test_eid_al_adha", "test/countries/__init__.py::TestBurundi::test_independence_day", "test/countries/__init__.py::TestBurundi::test_labour_day", "test/countries/__init__.py::TestBurundi::test_ndadaye_day", "test/countries/__init__.py::TestBurundi::test_new_year_day", "test/countries/__init__.py::TestBurundi::test_ntaryamira_day", "test/countries/__init__.py::TestBurundi::test_rwagasore_day", "test/countries/__init__.py::TestBurundi::test_unity_day", "test/countries/__init__.py::TestCA::test_boxing_day", "test/countries/__init__.py::TestCA::test_canada_day", "test/countries/__init__.py::TestCA::test_christmas_day", "test/countries/__init__.py::TestCA::test_civic_holiday", "test/countries/__init__.py::TestCA::test_discovery_day", "test/countries/__init__.py::TestCA::test_easter_monday", "test/countries/__init__.py::TestCA::test_family_day", "test/countries/__init__.py::TestCA::test_good_friday", "test/countries/__init__.py::TestCA::test_islander_day", "test/countries/__init__.py::TestCA::test_labour_day", "test/countries/__init__.py::TestCA::test_national_aboriginal_day", "test/countries/__init__.py::TestCA::test_new_years", "test/countries/__init__.py::TestCA::test_nunavut_day", "test/countries/__init__.py::TestCA::test_remembrance_day", "test/countries/__init__.py::TestCA::test_st_georges_day", "test/countries/__init__.py::TestCA::test_st_jean_baptiste_day", "test/countries/__init__.py::TestCA::test_st_patricks_day", "test/countries/__init__.py::TestCA::test_thanksgiving", "test/countries/__init__.py::TestCA::test_victoria_day", "test/countries/__init__.py::TestChile::test_2009", "test/countries/__init__.py::TestChile::test_2017", "test/countries/__init__.py::TestChile::test_2018", "test/countries/__init__.py::TestChile::test_2019", "test/countries/__init__.py::TestChile::test_2020", "test/countries/__init__.py::TestChile::test_2021", "test/countries/__init__.py::TestChile::test_2024", "test/countries/__init__.py::TestChile::test_2029", "test/countries/__init__.py::TestCO::test_2016", "test/countries/__init__.py::TestCO::test_others", "test/countries/__init__.py::TestCroatia::test_2018", "test/countries/__init__.py::TestCroatia::test_2020_new", "test/countries/__init__.py::TestCuracao::test_2016", "test/countries/__init__.py::TestCuracao::test_ascension_day", "test/countries/__init__.py::TestCuracao::test_carnaval_monday", "test/countries/__init__.py::TestCuracao::test_curacao_day", "test/countries/__init__.py::TestCuracao::test_easter_monday", "test/countries/__init__.py::TestCuracao::test_first_christmas", "test/countries/__init__.py::TestCuracao::test_kings_day_after_2014", "test/countries/__init__.py::TestCuracao::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestCuracao::test_labour_day", "test/countries/__init__.py::TestCuracao::test_national_anthem_flagday", "test/countries/__init__.py::TestCuracao::test_new_years", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestCuracao::test_second_christmas", "test/countries/__init__.py::TestCZ::test_2017", "test/countries/__init__.py::TestCZ::test_czech_deprecated", "test/countries/__init__.py::TestCZ::test_others", "test/countries/__init__.py::TestDK::test_2016", "test/countries/__init__.py::TestDjibouti::test_2019", "test/countries/__init__.py::TestDjibouti::test_hijri_based", "test/countries/__init__.py::TestDjibouti::test_labour_day", "test/countries/__init__.py::TestDominicanRepublic::test_do_holidays_2020", "test/countries/__init__.py::TestEgypt::test_2019", "test/countries/__init__.py::TestEgypt::test_25_jan", "test/countries/__init__.py::TestEgypt::test_25_jan_from_2009", "test/countries/__init__.py::TestEgypt::test_coptic_christmas", "test/countries/__init__.py::TestEgypt::test_hijri_based", "test/countries/__init__.py::TestEgypt::test_labour_day", "test/countries/__init__.py::TestEstonia::test_boxing_day", "test/countries/__init__.py::TestEstonia::test_christmas_day", "test/countries/__init__.py::TestEstonia::test_christmas_eve", "test/countries/__init__.py::TestEstonia::test_easter_sunday", "test/countries/__init__.py::TestEstonia::test_good_friday", "test/countries/__init__.py::TestEstonia::test_independence_day", "test/countries/__init__.py::TestEstonia::test_midsummers_day", "test/countries/__init__.py::TestEstonia::test_new_years", "test/countries/__init__.py::TestEstonia::test_pentecost", "test/countries/__init__.py::TestEstonia::test_restoration_of_independence_day", "test/countries/__init__.py::TestEstonia::test_spring_day", "test/countries/__init__.py::TestEstonia::test_victory_day", "test/countries/__init__.py::TestTAR::test_26_december_day", "test/countries/__init__.py::TestTAR::test_all_holidays_present", "test/countries/__init__.py::TestTAR::test_christmas_day", "test/countries/__init__.py::TestTAR::test_easter_monday", "test/countries/__init__.py::TestTAR::test_good_friday", "test/countries/__init__.py::TestTAR::test_labour_day", "test/countries/__init__.py::TestTAR::test_new_years", "test/countries/__init__.py::TestECB::test_new_years", "test/countries/__init__.py::TestFinland::test_Juhannus", "test/countries/__init__.py::TestFinland::test_fixed_holidays", "test/countries/__init__.py::TestFinland::test_relative_holidays", "test/countries/__init__.py::TestFrance::test_2017", "test/countries/__init__.py::TestFrance::test_alsace_moselle", "test/countries/__init__.py::TestFrance::test_guadeloupe", "test/countries/__init__.py::TestFrance::test_guyane", "test/countries/__init__.py::TestFrance::test_la_reunion", "test/countries/__init__.py::TestFrance::test_martinique", "test/countries/__init__.py::TestFrance::test_mayotte", "test/countries/__init__.py::TestFrance::test_nouvelle_caledonie", "test/countries/__init__.py::TestFrance::test_others", "test/countries/__init__.py::TestFrance::test_polynesie_francaise", "test/countries/__init__.py::TestFrance::test_saint_barthelemy", "test/countries/__init__.py::TestFrance::test_wallis_et_futuna", "test/countries/__init__.py::TestGeorgia::test_2020", "test/countries/__init__.py::TestGeorgia::test_easter", "test/countries/__init__.py::TestGeorgia::test_not_holiday", "test/countries/__init__.py::TestDE::test_75_jahrestag_beendigung_zweiter_weltkrieg", "test/countries/__init__.py::TestDE::test_all_holidays_present", "test/countries/__init__.py::TestDE::test_allerheiligen", "test/countries/__init__.py::TestDE::test_buss_und_bettag", "test/countries/__init__.py::TestDE::test_christi_himmelfahrt", "test/countries/__init__.py::TestDE::test_fixed_holidays", "test/countries/__init__.py::TestDE::test_frauentag", "test/countries/__init__.py::TestDE::test_fronleichnam", "test/countries/__init__.py::TestDE::test_heilige_drei_koenige", "test/countries/__init__.py::TestDE::test_internationaler_frauentag", "test/countries/__init__.py::TestDE::test_karfreitag", "test/countries/__init__.py::TestDE::test_mariae_himmelfahrt", "test/countries/__init__.py::TestDE::test_no_data_before_1990", "test/countries/__init__.py::TestDE::test_ostermontag", "test/countries/__init__.py::TestDE::test_ostersonntag", "test/countries/__init__.py::TestDE::test_pfingstmontag", "test/countries/__init__.py::TestDE::test_pfingstsonntag", "test/countries/__init__.py::TestDE::test_reformationstag", "test/countries/__init__.py::TestDE::test_tag_der_deutschen_einheit_in_1990", "test/countries/__init__.py::TestDE::test_weltkindertag", "test/countries/__init__.py::TestGreece::test_fixed_holidays", "test/countries/__init__.py::TestGreece::test_gr_clean_monday", "test/countries/__init__.py::TestGreece::test_gr_easter_monday", "test/countries/__init__.py::TestGreece::test_gr_monday_of_the_holy_spirit", "test/countries/__init__.py::TestHonduras::test_2014", "test/countries/__init__.py::TestHonduras::test_2018", "test/countries/__init__.py::TestHongKong::test_ching_ming_festival", "test/countries/__init__.py::TestHongKong::test_christmas_day", "test/countries/__init__.py::TestHongKong::test_chung_yeung_festival", "test/countries/__init__.py::TestHongKong::test_common", "test/countries/__init__.py::TestHongKong::test_easter", "test/countries/__init__.py::TestHongKong::test_first_day_of_january", "test/countries/__init__.py::TestHongKong::test_hksar_day", "test/countries/__init__.py::TestHongKong::test_labour_day", "test/countries/__init__.py::TestHongKong::test_lunar_new_year", "test/countries/__init__.py::TestHongKong::test_mid_autumn_festival", "test/countries/__init__.py::TestHongKong::test_national_day", "test/countries/__init__.py::TestHongKong::test_tuen_ng_festival", "test/countries/__init__.py::TestHungary::test_2018", "test/countries/__init__.py::TestHungary::test_additional_day_off", "test/countries/__init__.py::TestHungary::test_all_saints_day_since_1999", "test/countries/__init__.py::TestHungary::test_christian_holidays_2nd_day_was_not_held_in_1955", "test/countries/__init__.py::TestHungary::test_foundation_day_renamed_during_communism", "test/countries/__init__.py::TestHungary::test_good_friday_since_2017", "test/countries/__init__.py::TestHungary::test_holidays_during_communism", "test/countries/__init__.py::TestHungary::test_labour_day_since_1946", "test/countries/__init__.py::TestHungary::test_labour_day_was_doubled_in_early_50s", "test/countries/__init__.py::TestHungary::test_monday_new_years_eve_day_off", "test/countries/__init__.py::TestHungary::test_national_day_was_not_celebrated_during_communism", "test/countries/__init__.py::TestHungary::test_october_national_day_since_1991", "test/countries/__init__.py::TestHungary::test_whit_monday_since_1992", "test/countries/__init__.py::TestIceland::test_commerce_day", "test/countries/__init__.py::TestIceland::test_first_day_of_summer", "test/countries/__init__.py::TestIceland::test_holy_friday", "test/countries/__init__.py::TestIceland::test_maundy_thursday", "test/countries/__init__.py::TestIceland::test_new_year", "test/countries/__init__.py::TestIND::test_2018", "test/countries/__init__.py::TestIreland::test_2020", "test/countries/__init__.py::TestIreland::test_may_day", "test/countries/__init__.py::TestIreland::test_st_stephens_day", "test/countries/__init__.py::TestIsrael::test_independence_day", "test/countries/__init__.py::TestIsrael::test_memorial_day", "test/countries/__init__.py::TestIsrael::test_purim_day", "test/countries/__init__.py::TestItaly::test_2017", "test/countries/__init__.py::TestItaly::test_christmas", "test/countries/__init__.py::TestItaly::test_easter", "test/countries/__init__.py::TestItaly::test_easter_monday", "test/countries/__init__.py::TestItaly::test_liberation_day_after_1946", "test/countries/__init__.py::TestItaly::test_liberation_day_before_1946", "test/countries/__init__.py::TestItaly::test_new_years", "test/countries/__init__.py::TestItaly::test_province_specific_days", "test/countries/__init__.py::TestItaly::test_republic_day_after_1948", "test/countries/__init__.py::TestItaly::test_republic_day_before_1948", "test/countries/__init__.py::TestItaly::test_saint_stephan", "test/countries/__init__.py::TestJamaica::test_ash_wednesday", "test/countries/__init__.py::TestJamaica::test_boxing_day", "test/countries/__init__.py::TestJamaica::test_christmas_day", "test/countries/__init__.py::TestJamaica::test_easter", "test/countries/__init__.py::TestJamaica::test_easter_monday", "test/countries/__init__.py::TestJamaica::test_emancipation_day", "test/countries/__init__.py::TestJamaica::test_fathers_day", "test/countries/__init__.py::TestJamaica::test_good_friday", "test/countries/__init__.py::TestJamaica::test_independence_day", "test/countries/__init__.py::TestJamaica::test_labour_day", "test/countries/__init__.py::TestJamaica::test_mothers_day", "test/countries/__init__.py::TestJamaica::test_national_heroes_day", "test/countries/__init__.py::TestJamaica::test_new_years_day", "test/countries/__init__.py::TestJamaica::test_valentines_day", "test/countries/__init__.py::TestJapan::test_autumnal_equinox_day", "test/countries/__init__.py::TestJapan::test_childrens_day", "test/countries/__init__.py::TestJapan::test_coming_of_age", "test/countries/__init__.py::TestJapan::test_constitution_memorial_day", "test/countries/__init__.py::TestJapan::test_culture_day", "test/countries/__init__.py::TestJapan::test_emperors_birthday", "test/countries/__init__.py::TestJapan::test_foundation_day", "test/countries/__init__.py::TestJapan::test_greenery_day", "test/countries/__init__.py::TestJapan::test_health_and_sports_day", "test/countries/__init__.py::TestJapan::test_heisei_emperor_holidays", "test/countries/__init__.py::TestJapan::test_invalid_years", "test/countries/__init__.py::TestJapan::test_labour_thanks_giving_day", "test/countries/__init__.py::TestJapan::test_marine_day", "test/countries/__init__.py::TestJapan::test_mountain_day", "test/countries/__init__.py::TestJapan::test_new_years_day", "test/countries/__init__.py::TestJapan::test_reiwa_emperor_holidays", "test/countries/__init__.py::TestJapan::test_respect_for_the_aged_day", "test/countries/__init__.py::TestJapan::test_showa_day", "test/countries/__init__.py::TestJapan::test_showa_emperor_holidays", "test/countries/__init__.py::TestJapan::test_vernal_equinox_day", "test/countries/__init__.py::TestKenya::test_2019", "test/countries/__init__.py::TestKorea::test_birthday_of_buddha", "test/countries/__init__.py::TestKorea::test_childrens_day", "test/countries/__init__.py::TestKorea::test_christmas_day", "test/countries/__init__.py::TestKorea::test_chuseok", "test/countries/__init__.py::TestKorea::test_common", "test/countries/__init__.py::TestKorea::test_constitution_day", "test/countries/__init__.py::TestKorea::test_first_day_of_january", "test/countries/__init__.py::TestKorea::test_hangeul_day", "test/countries/__init__.py::TestKorea::test_independence_movement_day", "test/countries/__init__.py::TestKorea::test_labour_day", "test/countries/__init__.py::TestKorea::test_liberation_day", "test/countries/__init__.py::TestKorea::test_lunar_new_year", "test/countries/__init__.py::TestKorea::test_memorial_day", "test/countries/__init__.py::TestKorea::test_national_foundation_day", "test/countries/__init__.py::TestKorea::test_tree_planting_day", "test/countries/__init__.py::TestKorea::test_years_range", "test/countries/__init__.py::TestLatvia::test_2020", "test/countries/__init__.py::TestLithuania::test_2018", "test/countries/__init__.py::TestLithuania::test_day_of_dew", "test/countries/__init__.py::TestLithuania::test_easter", "test/countries/__init__.py::TestLithuania::test_fathers_day", "test/countries/__init__.py::TestLithuania::test_mothers_day", "test/countries/__init__.py::TestLU::test_2019", "test/countries/__init__.py::TestMalawi::test_easter", "test/countries/__init__.py::TestMalawi::test_good_friday", "test/countries/__init__.py::TestMalawi::test_new_years", "test/countries/__init__.py::TestMalawi::test_not_holiday", "test/countries/__init__.py::TestMalawi::test_static", "test/countries/__init__.py::TestMX::test_benito_juarez", "test/countries/__init__.py::TestMX::test_change_of_government", "test/countries/__init__.py::TestMX::test_christmas", "test/countries/__init__.py::TestMX::test_constitution_day", "test/countries/__init__.py::TestMX::test_independence_day", "test/countries/__init__.py::TestMX::test_labor_day", "test/countries/__init__.py::TestMX::test_new_years", "test/countries/__init__.py::TestMX::test_revolution_day", "test/countries/__init__.py::TestMorocco::test_1961", "test/countries/__init__.py::TestMorocco::test_1999", "test/countries/__init__.py::TestMorocco::test_2019", "test/countries/__init__.py::TestMorocco::test_hijri_based", "test/countries/__init__.py::TestMozambique::test_easter", "test/countries/__init__.py::TestMozambique::test_new_years", "test/countries/__init__.py::TestMozambique::test_not_holiday", "test/countries/__init__.py::TestNetherlands::test_2017", "test/countries/__init__.py::TestNetherlands::test_ascension_day", "test/countries/__init__.py::TestNetherlands::test_easter", "test/countries/__init__.py::TestNetherlands::test_easter_monday", "test/countries/__init__.py::TestNetherlands::test_first_christmas", "test/countries/__init__.py::TestNetherlands::test_kings_day_after_2014", "test/countries/__init__.py::TestNetherlands::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestNetherlands::test_liberation_day", "test/countries/__init__.py::TestNetherlands::test_liberation_day_after_1990_in_lustrum_year", "test/countries/__init__.py::TestNetherlands::test_liberation_day_after_1990_non_lustrum_year", "test/countries/__init__.py::TestNetherlands::test_new_years", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestNetherlands::test_second_christmas", "test/countries/__init__.py::TestNetherlands::test_whit_monday", "test/countries/__init__.py::TestNetherlands::test_whit_sunday", "test/countries/__init__.py::TestNZ::test_all_holidays_present", "test/countries/__init__.py::TestNZ::test_anzac_day", "test/countries/__init__.py::TestNZ::test_auckland_anniversary_day", "test/countries/__init__.py::TestNZ::test_boxing_day", "test/countries/__init__.py::TestNZ::test_canterbury_anniversary_day", "test/countries/__init__.py::TestNZ::test_chatham_islands_anniversary_day", "test/countries/__init__.py::TestNZ::test_christmas_day", "test/countries/__init__.py::TestNZ::test_day_after_new_years", "test/countries/__init__.py::TestNZ::test_easter_monday", "test/countries/__init__.py::TestNZ::test_good_friday", "test/countries/__init__.py::TestNZ::test_hawkes_bay_anniversary_day", "test/countries/__init__.py::TestNZ::test_labour_day", "test/countries/__init__.py::TestNZ::test_marlborough_anniversary_day", "test/countries/__init__.py::TestNZ::test_nelson_anniversary_day", "test/countries/__init__.py::TestNZ::test_new_years", "test/countries/__init__.py::TestNZ::test_otago_anniversary_day", "test/countries/__init__.py::TestNZ::test_south_canterbury_anniversary_day", "test/countries/__init__.py::TestNZ::test_southland_anniversary_day", "test/countries/__init__.py::TestNZ::test_sovereigns_birthday", "test/countries/__init__.py::TestNZ::test_taranaki_anniversary_day", "test/countries/__init__.py::TestNZ::test_waitangi_day", "test/countries/__init__.py::TestNZ::test_wellington_anniversary_day", "test/countries/__init__.py::TestNZ::test_westland_anniversary_day", "test/countries/__init__.py::TestNicaragua::test_ni_holidays_2020", "test/countries/__init__.py::TestNigeria::test_fixed_holidays", "test/countries/__init__.py::TestNorway::test_christmas", "test/countries/__init__.py::TestNorway::test_constitution_day", "test/countries/__init__.py::TestNorway::test_easter", "test/countries/__init__.py::TestNorway::test_new_years", "test/countries/__init__.py::TestNorway::test_not_holiday", "test/countries/__init__.py::TestNorway::test_pentecost", "test/countries/__init__.py::TestNorway::test_sundays", "test/countries/__init__.py::TestNorway::test_workers_day", "test/countries/__init__.py::TestParaguay::test_easter", "test/countries/__init__.py::TestParaguay::test_fixed_holidays", "test/countries/__init__.py::TestParaguay::test_no_observed", "test/countries/__init__.py::TestPeru::test_2019", "test/countries/__init__.py::TestPL::test_2017", "test/countries/__init__.py::TestPL::test_2018", "test/countries/__init__.py::TestPL::test_polish_deprecated", "test/countries/__init__.py::TestPT::test_2017", "test/countries/__init__.py::TestPortugalExt::test_2017", "test/countries/__init__.py::TestRomania::test_2020", "test/countries/__init__.py::TestRomania::test_children_s_day", "test/countries/__init__.py::TestRussia::test_2018", "test/countries/__init__.py::TestRussia::test_before_2005", "test/countries/__init__.py::TestSaudiArabia::test_2020", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_not_observed", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_observed", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_with_two_holidays_in_one_year", "test/countries/__init__.py::TestSaudiArabia::test_national_day", "test/countries/__init__.py::TestSaudiArabia::test_national_day_not_observed", "test/countries/__init__.py::TestSaudiArabia::test_national_day_observed", "test/countries/__init__.py::TestSerbia::test_armistice_day", "test/countries/__init__.py::TestSerbia::test_labour_day", "test/countries/__init__.py::TestSerbia::test_new_year", "test/countries/__init__.py::TestSerbia::test_religious_holidays", "test/countries/__init__.py::TestSerbia::test_statehood_day", "test/countries/__init__.py::TestSingapore::test_Singapore", "test/countries/__init__.py::TestSK::test_2018", "test/countries/__init__.py::TestSK::test_slovak_deprecated", "test/countries/__init__.py::TestSI::test_holidays", "test/countries/__init__.py::TestSI::test_missing_years", "test/countries/__init__.py::TestSI::test_non_holidays", "test/countries/__init__.py::TestSouthAfrica::test_easter", "test/countries/__init__.py::TestSouthAfrica::test_elections", "test/countries/__init__.py::TestSouthAfrica::test_historic", "test/countries/__init__.py::TestSouthAfrica::test_new_years", "test/countries/__init__.py::TestSouthAfrica::test_not_holiday", "test/countries/__init__.py::TestSouthAfrica::test_onceoff", "test/countries/__init__.py::TestSouthAfrica::test_static", "test/countries/__init__.py::TestES::test_fixed_holidays", "test/countries/__init__.py::TestES::test_fixed_holidays_observed", "test/countries/__init__.py::TestES::test_province_specific_days", "test/countries/__init__.py::TestSweden::test_christmas", "test/countries/__init__.py::TestSweden::test_constitution_day", "test/countries/__init__.py::TestSweden::test_easter", "test/countries/__init__.py::TestSweden::test_new_years", "test/countries/__init__.py::TestSweden::test_not_holiday", "test/countries/__init__.py::TestSweden::test_pentecost", "test/countries/__init__.py::TestSweden::test_sundays", "test/countries/__init__.py::TestSweden::test_workers_day", "test/countries/__init__.py::TestSwitzerland::test_all_holidays_present", "test/countries/__init__.py::TestSwitzerland::test_allerheiligen", "test/countries/__init__.py::TestSwitzerland::test_auffahrt", "test/countries/__init__.py::TestSwitzerland::test_berchtoldstag", "test/countries/__init__.py::TestSwitzerland::test_bruder_chlaus", "test/countries/__init__.py::TestSwitzerland::test_fest_der_unabhaengikeit", "test/countries/__init__.py::TestSwitzerland::test_fixed_holidays", "test/countries/__init__.py::TestSwitzerland::test_fronleichnam", "test/countries/__init__.py::TestSwitzerland::test_heilige_drei_koenige", "test/countries/__init__.py::TestSwitzerland::test_jahrestag_der_ausrufung_der_republik", "test/countries/__init__.py::TestSwitzerland::test_jeune_genevois", "test/countries/__init__.py::TestSwitzerland::test_josefstag", "test/countries/__init__.py::TestSwitzerland::test_karfreitag", "test/countries/__init__.py::TestSwitzerland::test_lundi_du_jeune", "test/countries/__init__.py::TestSwitzerland::test_mariae_himmelfahrt", "test/countries/__init__.py::TestSwitzerland::test_naefelser_fahrt", "test/countries/__init__.py::TestSwitzerland::test_ostermontag", "test/countries/__init__.py::TestSwitzerland::test_ostern", "test/countries/__init__.py::TestSwitzerland::test_peter_und_paul", "test/countries/__init__.py::TestSwitzerland::test_pfingsten", "test/countries/__init__.py::TestSwitzerland::test_pfingstmontag", "test/countries/__init__.py::TestSwitzerland::test_stephanstag", "test/countries/__init__.py::TestSwitzerland::test_wiedererstellung_der_republik", "test/countries/__init__.py::TestTurkey::test_2019", "test/countries/__init__.py::TestTurkey::test_hijri_based", "test/countries/__init__.py::TestUkraine::test_2018", "test/countries/__init__.py::TestUkraine::test_before_1918", "test/countries/__init__.py::TestUkraine::test_old_holidays", "test/countries/__init__.py::UnitedArabEmirates::test_2020", "test/countries/__init__.py::UnitedArabEmirates::test_commemoration_day_since_2015", "test/countries/__init__.py::UnitedArabEmirates::test_hijri_based", "test/countries/__init__.py::TestUK::test_all_holidays_present", "test/countries/__init__.py::TestUK::test_boxing_day", "test/countries/__init__.py::TestUK::test_christmas_day", "test/countries/__init__.py::TestUK::test_easter_monday", "test/countries/__init__.py::TestUK::test_good_friday", "test/countries/__init__.py::TestUK::test_may_day", "test/countries/__init__.py::TestUK::test_new_years", "test/countries/__init__.py::TestUK::test_queens_jubilees", "test/countries/__init__.py::TestUK::test_royal_weddings", "test/countries/__init__.py::TestUK::test_spring_bank_holiday", "test/countries/__init__.py::TestScotland::test_2017", "test/countries/__init__.py::TestIsleOfMan::test_2018", "test/countries/__init__.py::TestNorthernIreland::test_2018", "test/countries/__init__.py::TestUS::test_alaska_day", "test/countries/__init__.py::TestUS::test_all_souls_day", "test/countries/__init__.py::TestUS::test_arbor_day", "test/countries/__init__.py::TestUS::test_bennington_battle_day", "test/countries/__init__.py::TestUS::test_casimir_pulaski_day", "test/countries/__init__.py::TestUS::test_cesar_chavez_day", "test/countries/__init__.py::TestUS::test_christmas_day", "test/countries/__init__.py::TestUS::test_christmas_eve", "test/countries/__init__.py::TestUS::test_columbus_day", "test/countries/__init__.py::TestUS::test_confederate_memorial_day", "test/countries/__init__.py::TestUS::test_constitution_day", "test/countries/__init__.py::TestUS::test_day_after_christmas", "test/countries/__init__.py::TestUS::test_discovery_day", "test/countries/__init__.py::TestUS::test_easter_monday", "test/countries/__init__.py::TestUS::test_election_day", "test/countries/__init__.py::TestUS::test_emancipation_day", "test/countries/__init__.py::TestUS::test_emancipation_day_in_puerto_rico", "test/countries/__init__.py::TestUS::test_emancipation_day_in_texas", "test/countries/__init__.py::TestUS::test_emancipation_day_in_virgin_islands", "test/countries/__init__.py::TestUS::test_epiphany", "test/countries/__init__.py::TestUS::test_evacuation_day", "test/countries/__init__.py::TestUS::test_good_friday", "test/countries/__init__.py::TestUS::test_guam_discovery_day", "test/countries/__init__.py::TestUS::test_holy_thursday", "test/countries/__init__.py::TestUS::test_inauguration_day", "test/countries/__init__.py::TestUS::test_independence_day", "test/countries/__init__.py::TestUS::test_jefferson_davis_birthday", "test/countries/__init__.py::TestUS::test_kamehameha_day", "test/countries/__init__.py::TestUS::test_labor_day", "test/countries/__init__.py::TestUS::test_lady_of_camarin_day", "test/countries/__init__.py::TestUS::test_lee_jackson_day", "test/countries/__init__.py::TestUS::test_liberation_day_guam", "test/countries/__init__.py::TestUS::test_liberty_day", "test/countries/__init__.py::TestUS::test_lincolns_birthday", "test/countries/__init__.py::TestUS::test_lyndon_baines_johnson_day", "test/countries/__init__.py::TestUS::test_mardi_gras", "test/countries/__init__.py::TestUS::test_martin_luther", "test/countries/__init__.py::TestUS::test_memorial_day", "test/countries/__init__.py::TestUS::test_nevada_day", "test/countries/__init__.py::TestUS::test_new_years", "test/countries/__init__.py::TestUS::test_new_years_eve", "test/countries/__init__.py::TestUS::test_patriots_day", "test/countries/__init__.py::TestUS::test_pioneer_day", "test/countries/__init__.py::TestUS::test_primary_election_day", "test/countries/__init__.py::TestUS::test_prince_jonah_kuhio_kalanianaole_day", "test/countries/__init__.py::TestUS::test_robert_lee_birthday", "test/countries/__init__.py::TestUS::test_san_jacinto_day", "test/countries/__init__.py::TestUS::test_statehood_day", "test/countries/__init__.py::TestUS::test_stewards_day", "test/countries/__init__.py::TestUS::test_susan_b_anthony_day", "test/countries/__init__.py::TestUS::test_texas_independence_day", "test/countries/__init__.py::TestUS::test_thanksgiving_day", "test/countries/__init__.py::TestUS::test_three_kings_day", "test/countries/__init__.py::TestUS::test_town_meeting_day", "test/countries/__init__.py::TestUS::test_transfer_day", "test/countries/__init__.py::TestUS::test_truman_day", "test/countries/__init__.py::TestUS::test_veterans_day", "test/countries/__init__.py::TestUS::test_victory_day", "test/countries/__init__.py::TestUS::test_washingtons_birthday", "test/countries/__init__.py::TestUS::test_west_virginia_day", "test/countries/__init__.py::TestVietnam::test_common", "test/countries/__init__.py::TestVietnam::test_first_day_of_january", "test/countries/__init__.py::TestVietnam::test_independence_day", "test/countries/__init__.py::TestVietnam::test_international_labor_day", "test/countries/__init__.py::TestVietnam::test_king_hung_day", "test/countries/__init__.py::TestVietnam::test_liberation_day", "test/countries/__init__.py::TestVietnam::test_lunar_new_year", "test/countries/__init__.py::TestVietnam::test_years_range", "test/countries/test_spain.py::TestES::test_fixed_holidays", "test/countries/test_spain.py::TestES::test_fixed_holidays_observed", "test/countries/test_spain.py::TestES::test_province_specific_days" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-06-07 17:00:48+00:00
mit
1,989
dr-prodigy__python-holidays-474
diff --git a/CHANGES b/CHANGES index 4d38f383..3f990929 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,7 @@ Version 0.11.2 Released ????, ???? +- Support for Venezuela #470 (antusystem, dr-p) - Poland fix #464 (m-ganko) - Singapore updates for 2022 #456 (mborsetti) - .gitignore fix #462 (TheLastProject) diff --git a/README.rst b/README.rst index 4e8df697..cb44ba7c 100644 --- a/README.rst +++ b/README.rst @@ -191,6 +191,7 @@ UnitedStates US/USA state = AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FL FM, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VA, VI, WA, WV, WI, WY +Venezuela YV/VEN Vietnam VN/VNM Wales None =================== ========= ============================================================= diff --git a/holidays/countries/__init__.py b/holidays/countries/__init__.py index 7bb1c290..3584e388 100644 --- a/holidays/countries/__init__.py +++ b/holidays/countries/__init__.py @@ -92,4 +92,5 @@ from .united_kingdom import ( GBR, ) from .united_states import UnitedStates, US, USA +from .venezuela import Venezuela, YV, VEN from .vietnam import Vietnam, VN, VNM diff --git a/holidays/countries/spain.py b/holidays/countries/spain.py index 794032b1..6b2c8dd0 100644 --- a/holidays/countries/spain.py +++ b/holidays/countries/spain.py @@ -117,7 +117,7 @@ class Spain(HolidayBase): self._is_observed(date(year, MAR, 19), "San José") if self.prov and self.prov not in ["CT", "VC"]: self[easter(year) + rd(weeks=-1, weekday=TH)] = "Jueves Santo" - self[easter(year) + rd(weeks=-1, weekday=FR)] = "Viernes Santo" + self[easter(year) + rd(weeks=-1, weekday=FR)] = "Viernes Santo" if self.prov and self.prov in ["CT", "PV", "NC", "VC", "IB", "CM"]: self[easter(year) + rd(weekday=MO)] = "Lunes de Pascua" self._is_observed(date(year, MAY, 1), "Día del Trabajador") diff --git a/holidays/countries/united_states.py b/holidays/countries/united_states.py index fa3a23da..4be7f73c 100644 --- a/holidays/countries/united_states.py +++ b/holidays/countries/united_states.py @@ -375,6 +375,10 @@ class UnitedStates(HolidayBase): elif date(year, JUN, 11).weekday() == SUN: self[date(year, JUN, 12)] = "Kamehameha Day (Observed)" + # Juneteenth National Independence Day + if year >= 2021: + self[date(year, JUN, 19)] = "Juneteenth National Independence Day" + # Emancipation Day In Texas if self.state == "TX" and year >= 1980: self[date(year, JUN, 19)] = "Emancipation Day In Texas" diff --git a/holidays/countries/venezuela.py b/holidays/countries/venezuela.py new file mode 100644 index 00000000..020a0122 --- /dev/null +++ b/holidays/countries/venezuela.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- + +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Author: ryanss <[email protected]> (c) 2014-2017 +# dr-prodigy <[email protected]> (c) 2017-2021 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +from datetime import date + +from dateutil.easter import easter +from dateutil.relativedelta import relativedelta as rd, TH, FR + +from holidays.constants import ( + JAN, + MAR, + APR, + MAY, + JUN, + JUL, + AUG, + SEP, + OCT, + NOV, + DEC, +) +from holidays.holiday_base import HolidayBase + + +class Venezuela(HolidayBase): + """ + https://dias-festivos.eu/dias-festivos/venezuela/# + """ + + def __init__(self, **kwargs): + self.country = "YV" + HolidayBase.__init__(self, **kwargs) + + def _populate(self, year): + # New Year's Day + self[date(year, JAN, 1)] = "Año Nuevo [New Year's Day]" + + self[date(year, MAY, 1)] = "Dia Mundial del Trabajador" + + self[date(year, JUN, 24)] = "Batalla de Carabobo" + + self[date(year, JUL, 5)] = "Dia de la Independencia" + + self[date(year, JUL, 24)] = "Natalicio de Simón Bolívar" + + self[date(year, OCT, 12)] = "Día de la Resistencia Indígena" + + # Christmas Day + self[date(year, DEC, 24)] = "Nochebuena" + + self[date(year, DEC, 25)] = "Día de Navidad" + + self[date(year, DEC, 31)] = "Fiesta de Fin de Año" + + # Semana Santa y Carnaval + + if date(year, APR, 19) == (easter(year) - rd(days=2)): + self[ + easter(year) - rd(days=2) + ] = "Viernes Santo y Declaración de la Independencia" + else: + # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo" + self[date(year, APR, 19)] = "Declaración de la Independencia" + self[easter(year) - rd(days=2)] = "Viernes Santo" + + # self[easter(year) - rd(weekday=TH(-1))] = "Jueves Santo" + + if date(year, APR, 19) == (easter(year) - rd(days=3)): + self[easter(year) - rd(days=3)] = ( + "Jueves Santo y Declaración " "de la Independencia" + ) + else: + # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo" + self[date(year, APR, 19)] = "Declaración de la Independencia" + self[easter(year) - rd(days=3)] = "Jueves Santo" + + self[easter(year) - rd(days=47)] = "Martes de Carnaval" + + self[easter(year) - rd(days=48)] = "Lunes de Carnaval" + + +class YV(Venezuela): + pass + + +class VEN(Venezuela): + pass
dr-prodigy/python-holidays
a33745d6c356770a0c48949fdad262f71da403f2
diff --git a/test/countries/__init__.py b/test/countries/__init__.py index d0d28686..321e65f1 100644 --- a/test/countries/__init__.py +++ b/test/countries/__init__.py @@ -82,4 +82,5 @@ from .test_ukraine import * from .test_united_arab_emirates import * from .test_united_kingdom import * from .test_united_states import * +from .test_venezuela import * from .test_vietnam import * diff --git a/test/countries/test_spain.py b/test/countries/test_spain.py index 7e8baaa5..6108ad57 100644 --- a/test/countries/test_spain.py +++ b/test/countries/test_spain.py @@ -19,7 +19,7 @@ from datetime import date import holidays -class TestES(unittest.TestCase): +class TestSpain(unittest.TestCase): def setUp(self): self.holidays = holidays.ES(observed=False) self.holidays_observed = holidays.ES() @@ -63,9 +63,7 @@ class TestES(unittest.TestCase): self.assertEqual( date(2016, 3, 24) in prov_holidays, prov not in ["CT", "VC"] ) - self.assertEqual( - date(2016, 3, 25) in prov_holidays, prov not in ["CT", "VC"] - ) + assert date(2016, 3, 25) in prov_holidays self.assertEqual( date(2016, 3, 28) in prov_holidays, prov in ["CT", "PV", "NC", "VC", "IB", "CM"], diff --git a/test/countries/test_united_states.py b/test/countries/test_united_states.py index 4fb4fbf2..1e1a344f 100644 --- a/test/countries/test_united_states.py +++ b/test/countries/test_united_states.py @@ -667,9 +667,15 @@ class TestUS(unittest.TestCase): def test_emancipation_day_in_texas(self): tx_holidays = holidays.US(state="TX") self.assertNotIn(date(1979, 6, 19), tx_holidays) - for year in (1980, 2050): + for year in (1980, 2020): self.assertNotIn(date(year, 6, 19), self.holidays) self.assertIn(date(year, 6, 19), tx_holidays) + for year in (2021, 2050): + self.assertIn(date(year, 6, 19), tx_holidays) + + def test_juneteenth(self): + self.assertNotIn(date(2020, 6, 19), self.holidays) + self.assertIn(date(2021, 6, 19), self.holidays) def test_west_virginia_day(self): wv_holidays = holidays.US(state="WV") diff --git a/test/countries/test_venezuela.py b/test/countries/test_venezuela.py new file mode 100644 index 00000000..c7ab4631 --- /dev/null +++ b/test/countries/test_venezuela.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# python-holidays +# --------------- +# A fast, efficient Python library for generating country, province and state +# specific sets of holidays on the fly. It aims to make determining whether a +# specific date is a holiday as fast and flexible as possible. +# +# Author: ryanss <[email protected]> (c) 2014-2017 +# dr-prodigy <[email protected]> (c) 2017-2021 +# Website: https://github.com/dr-prodigy/python-holidays +# License: MIT (see LICENSE file) + +import unittest + +from datetime import date + +import holidays + + +class TestVenezuela(unittest.TestCase): + def test_YV_holidays(self): + self.holidays = holidays.YV(years=2019) + self.assertIn("2019-01-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 1, 1)], "Año Nuevo [New Year's Day]" + ) + self.assertIn("2019-03-04", self.holidays) + self.assertEqual( + self.holidays[date(2019, 3, 4)], + "Lunes de Carnaval", + ) + self.assertIn("2019-03-05", self.holidays) + self.assertEqual(self.holidays[date(2019, 3, 5)], "Martes de Carnaval") + self.assertIn("2019-04-18", self.holidays) + self.assertEqual(self.holidays[date(2019, 4, 18)], "Jueves Santo") + self.assertIn("2019-04-19", self.holidays) + self.assertEqual( + self.holidays[date(2019, 4, 19)], + "Viernes Santo y Declaración de la Independencia", + ) + self.assertIn("2019-05-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 5, 1)], "Dia Mundial del Trabajador" + ) + self.assertIn("2019-06-24", self.holidays) + self.assertEqual( + self.holidays[date(2019, 6, 24)], "Batalla de Carabobo" + ) + self.assertIn("2019-05-01", self.holidays) + self.assertEqual( + self.holidays[date(2019, 7, 5)], "Dia de la Independencia" + ) + self.assertIn("2019-07-24", self.holidays) + self.assertEqual( + self.holidays[date(2019, 7, 24)], "Natalicio de Simón Bolívar" + ) + self.assertIn("2019-10-12", self.holidays) + self.assertEqual( + self.holidays[date(2019, 10, 12)], "Día de la Resistencia Indígena" + ) + self.assertIn("2019-12-24", self.holidays) + self.assertEqual(self.holidays[date(2019, 12, 24)], "Nochebuena") + self.assertIn("2019-12-25", self.holidays) + self.assertEqual(self.holidays[date(2019, 12, 25)], "Día de Navidad") + self.assertIn("2019-12-31", self.holidays) + self.assertEqual( + self.holidays[date(2019, 12, 31)], "Fiesta de Fin de Año" + )
Add Juneteenth https://www.nytimes.com/2021/06/17/us/politics/juneteenth-holiday-biden.html
0.0
a33745d6c356770a0c48949fdad262f71da403f2
[ "test/countries/__init__.py::TestSpain::test_variable_days_in_2016", "test/countries/__init__.py::TestUS::test_juneteenth", "test/countries/__init__.py::TestVenezuela::test_YV_holidays", "test/countries/test_spain.py::TestSpain::test_variable_days_in_2016", "test/countries/test_united_states.py::TestUS::test_juneteenth", "test/countries/test_venezuela.py::TestVenezuela::test_YV_holidays" ]
[ "test/countries/__init__.py::TestAngola::test_easter", "test/countries/__init__.py::TestAngola::test_long_weekend", "test/countries/__init__.py::TestAngola::test_new_years", "test/countries/__init__.py::TestAngola::test_not_holiday", "test/countries/__init__.py::TestAngola::test_static", "test/countries/__init__.py::TestAR::test_belgrano_day", "test/countries/__init__.py::TestAR::test_carnival_day", "test/countries/__init__.py::TestAR::test_christmas", "test/countries/__init__.py::TestAR::test_cultural_day", "test/countries/__init__.py::TestAR::test_guemes_day", "test/countries/__init__.py::TestAR::test_holy_week_day", "test/countries/__init__.py::TestAR::test_independence_day", "test/countries/__init__.py::TestAR::test_inmaculate_conception_day", "test/countries/__init__.py::TestAR::test_labor_day", "test/countries/__init__.py::TestAR::test_malvinas_war_day", "test/countries/__init__.py::TestAR::test_may_revolution_day", "test/countries/__init__.py::TestAR::test_memory_national_day", "test/countries/__init__.py::TestAR::test_national_sovereignty_day", "test/countries/__init__.py::TestAR::test_new_years", "test/countries/__init__.py::TestAR::test_san_martin_day", "test/countries/__init__.py::TestAruba::test_2017", "test/countries/__init__.py::TestAruba::test_anthem_and_flag_day", "test/countries/__init__.py::TestAruba::test_ascension_day", "test/countries/__init__.py::TestAruba::test_betico_day", "test/countries/__init__.py::TestAruba::test_carnaval_monday", "test/countries/__init__.py::TestAruba::test_christmas", "test/countries/__init__.py::TestAruba::test_easter_monday", "test/countries/__init__.py::TestAruba::test_good_friday", "test/countries/__init__.py::TestAruba::test_kings_day_after_2014", "test/countries/__init__.py::TestAruba::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestAruba::test_labour_day", "test/countries/__init__.py::TestAruba::test_new_years", "test/countries/__init__.py::TestAruba::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestAruba::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestAruba::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestAruba::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestAruba::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestAruba::test_second_christmas", "test/countries/__init__.py::TestAU::test_adelaide_cup", "test/countries/__init__.py::TestAU::test_all_holidays", "test/countries/__init__.py::TestAU::test_anzac_day", "test/countries/__init__.py::TestAU::test_australia_day", "test/countries/__init__.py::TestAU::test_bank_holiday", "test/countries/__init__.py::TestAU::test_boxing_day", "test/countries/__init__.py::TestAU::test_christmas_day", "test/countries/__init__.py::TestAU::test_easter_monday", "test/countries/__init__.py::TestAU::test_easter_saturday", "test/countries/__init__.py::TestAU::test_easter_sunday", "test/countries/__init__.py::TestAU::test_family_and_community_day", "test/countries/__init__.py::TestAU::test_good_friday", "test/countries/__init__.py::TestAU::test_grand_final_day", "test/countries/__init__.py::TestAU::test_labour_day", "test/countries/__init__.py::TestAU::test_melbourne_cup", "test/countries/__init__.py::TestAU::test_new_years", "test/countries/__init__.py::TestAU::test_picnic_day", "test/countries/__init__.py::TestAU::test_queens_birthday", "test/countries/__init__.py::TestAU::test_reconciliation_day", "test/countries/__init__.py::TestAU::test_royal_queensland_show", "test/countries/__init__.py::TestAU::test_western_australia_day", "test/countries/__init__.py::TestAT::test_all_holidays_present", "test/countries/__init__.py::TestAT::test_christmas", "test/countries/__init__.py::TestAT::test_easter_monday", "test/countries/__init__.py::TestAT::test_national_day", "test/countries/__init__.py::TestAT::test_new_years", "test/countries/__init__.py::TestBangladesh::test_2020", "test/countries/__init__.py::TestBelarus::test_2018", "test/countries/__init__.py::TestBelarus::test_before_1998", "test/countries/__init__.py::TestBelarus::test_new_year", "test/countries/__init__.py::TestBelarus::test_radunitsa", "test/countries/__init__.py::TestBelgium::test_2017", "test/countries/__init__.py::TestBrazil::test_AC_holidays", "test/countries/__init__.py::TestBrazil::test_AL_holidays", "test/countries/__init__.py::TestBrazil::test_AM_holidays", "test/countries/__init__.py::TestBrazil::test_AP_holidays", "test/countries/__init__.py::TestBrazil::test_BA_holidays", "test/countries/__init__.py::TestBrazil::test_BR_holidays", "test/countries/__init__.py::TestBrazil::test_CE_holidays", "test/countries/__init__.py::TestBrazil::test_DF_holidays", "test/countries/__init__.py::TestBrazil::test_ES_holidays", "test/countries/__init__.py::TestBrazil::test_GO_holidays", "test/countries/__init__.py::TestBrazil::test_MA_holidays", "test/countries/__init__.py::TestBrazil::test_MG_holidays", "test/countries/__init__.py::TestBrazil::test_MS_holidays", "test/countries/__init__.py::TestBrazil::test_MT_holidays", "test/countries/__init__.py::TestBrazil::test_PA_holidays", "test/countries/__init__.py::TestBrazil::test_PB_holidays", "test/countries/__init__.py::TestBrazil::test_PE_holidays", "test/countries/__init__.py::TestBrazil::test_PI_holidays", "test/countries/__init__.py::TestBrazil::test_PR_holidays", "test/countries/__init__.py::TestBrazil::test_RJ_holidays", "test/countries/__init__.py::TestBrazil::test_RN_holidays", "test/countries/__init__.py::TestBrazil::test_RO_holidays", "test/countries/__init__.py::TestBrazil::test_RR_holidays", "test/countries/__init__.py::TestBrazil::test_RS_holidays", "test/countries/__init__.py::TestBrazil::test_SC_holidays", "test/countries/__init__.py::TestBrazil::test_SE_holidays", "test/countries/__init__.py::TestBrazil::test_SP_holidays", "test/countries/__init__.py::TestBrazil::test_TO_holidays", "test/countries/__init__.py::TestBulgaria::test_before_1990", "test/countries/__init__.py::TestBulgaria::test_christmas", "test/countries/__init__.py::TestBulgaria::test_easter", "test/countries/__init__.py::TestBulgaria::test_independence_day", "test/countries/__init__.py::TestBulgaria::test_labour_day", "test/countries/__init__.py::TestBulgaria::test_liberation_day", "test/countries/__init__.py::TestBulgaria::test_national_awakening_day", "test/countries/__init__.py::TestBulgaria::test_new_years_day", "test/countries/__init__.py::TestBulgaria::test_saint_georges_day", "test/countries/__init__.py::TestBulgaria::test_twenty_fourth_of_may", "test/countries/__init__.py::TestBulgaria::test_unification_day", "test/countries/__init__.py::TestBurundi::test_all_saints_Day", "test/countries/__init__.py::TestBurundi::test_ascension_day", "test/countries/__init__.py::TestBurundi::test_assumption_Day", "test/countries/__init__.py::TestBurundi::test_christmas_Day", "test/countries/__init__.py::TestBurundi::test_eid_al_adha", "test/countries/__init__.py::TestBurundi::test_independence_day", "test/countries/__init__.py::TestBurundi::test_labour_day", "test/countries/__init__.py::TestBurundi::test_ndadaye_day", "test/countries/__init__.py::TestBurundi::test_new_year_day", "test/countries/__init__.py::TestBurundi::test_ntaryamira_day", "test/countries/__init__.py::TestBurundi::test_rwagasore_day", "test/countries/__init__.py::TestBurundi::test_unity_day", "test/countries/__init__.py::TestCA::test_boxing_day", "test/countries/__init__.py::TestCA::test_canada_day", "test/countries/__init__.py::TestCA::test_christmas_day", "test/countries/__init__.py::TestCA::test_civic_holiday", "test/countries/__init__.py::TestCA::test_discovery_day", "test/countries/__init__.py::TestCA::test_easter_monday", "test/countries/__init__.py::TestCA::test_family_day", "test/countries/__init__.py::TestCA::test_good_friday", "test/countries/__init__.py::TestCA::test_islander_day", "test/countries/__init__.py::TestCA::test_labour_day", "test/countries/__init__.py::TestCA::test_national_aboriginal_day", "test/countries/__init__.py::TestCA::test_new_years", "test/countries/__init__.py::TestCA::test_nunavut_day", "test/countries/__init__.py::TestCA::test_remembrance_day", "test/countries/__init__.py::TestCA::test_st_georges_day", "test/countries/__init__.py::TestCA::test_st_jean_baptiste_day", "test/countries/__init__.py::TestCA::test_st_patricks_day", "test/countries/__init__.py::TestCA::test_thanksgiving", "test/countries/__init__.py::TestCA::test_victoria_day", "test/countries/__init__.py::TestChile::test_2009", "test/countries/__init__.py::TestChile::test_2017", "test/countries/__init__.py::TestChile::test_2018", "test/countries/__init__.py::TestChile::test_2019", "test/countries/__init__.py::TestChile::test_2020", "test/countries/__init__.py::TestChile::test_2021", "test/countries/__init__.py::TestChile::test_2024", "test/countries/__init__.py::TestChile::test_2029", "test/countries/__init__.py::TestCO::test_2016", "test/countries/__init__.py::TestCO::test_others", "test/countries/__init__.py::TestCroatia::test_2018", "test/countries/__init__.py::TestCroatia::test_2020_new", "test/countries/__init__.py::TestCuracao::test_2016", "test/countries/__init__.py::TestCuracao::test_ascension_day", "test/countries/__init__.py::TestCuracao::test_carnaval_monday", "test/countries/__init__.py::TestCuracao::test_curacao_day", "test/countries/__init__.py::TestCuracao::test_easter_monday", "test/countries/__init__.py::TestCuracao::test_first_christmas", "test/countries/__init__.py::TestCuracao::test_kings_day_after_2014", "test/countries/__init__.py::TestCuracao::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestCuracao::test_labour_day", "test/countries/__init__.py::TestCuracao::test_national_anthem_flagday", "test/countries/__init__.py::TestCuracao::test_new_years", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestCuracao::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestCuracao::test_second_christmas", "test/countries/__init__.py::TestCZ::test_2017", "test/countries/__init__.py::TestCZ::test_czech_deprecated", "test/countries/__init__.py::TestCZ::test_others", "test/countries/__init__.py::TestDK::test_2016", "test/countries/__init__.py::TestDjibouti::test_2019", "test/countries/__init__.py::TestDjibouti::test_hijri_based", "test/countries/__init__.py::TestDjibouti::test_labour_day", "test/countries/__init__.py::TestDominicanRepublic::test_do_holidays_2020", "test/countries/__init__.py::TestEgypt::test_2019", "test/countries/__init__.py::TestEgypt::test_25_jan", "test/countries/__init__.py::TestEgypt::test_25_jan_from_2009", "test/countries/__init__.py::TestEgypt::test_coptic_christmas", "test/countries/__init__.py::TestEgypt::test_hijri_based", "test/countries/__init__.py::TestEgypt::test_labour_day", "test/countries/__init__.py::TestEstonia::test_boxing_day", "test/countries/__init__.py::TestEstonia::test_christmas_day", "test/countries/__init__.py::TestEstonia::test_christmas_eve", "test/countries/__init__.py::TestEstonia::test_easter_sunday", "test/countries/__init__.py::TestEstonia::test_good_friday", "test/countries/__init__.py::TestEstonia::test_independence_day", "test/countries/__init__.py::TestEstonia::test_midsummers_day", "test/countries/__init__.py::TestEstonia::test_new_years", "test/countries/__init__.py::TestEstonia::test_pentecost", "test/countries/__init__.py::TestEstonia::test_restoration_of_independence_day", "test/countries/__init__.py::TestEstonia::test_spring_day", "test/countries/__init__.py::TestEstonia::test_victory_day", "test/countries/__init__.py::TestTAR::test_26_december_day", "test/countries/__init__.py::TestTAR::test_all_holidays_present", "test/countries/__init__.py::TestTAR::test_christmas_day", "test/countries/__init__.py::TestTAR::test_easter_monday", "test/countries/__init__.py::TestTAR::test_good_friday", "test/countries/__init__.py::TestTAR::test_labour_day", "test/countries/__init__.py::TestTAR::test_new_years", "test/countries/__init__.py::TestECB::test_new_years", "test/countries/__init__.py::TestFinland::test_Juhannus", "test/countries/__init__.py::TestFinland::test_fixed_holidays", "test/countries/__init__.py::TestFinland::test_relative_holidays", "test/countries/__init__.py::TestFrance::test_2017", "test/countries/__init__.py::TestFrance::test_alsace_moselle", "test/countries/__init__.py::TestFrance::test_guadeloupe", "test/countries/__init__.py::TestFrance::test_guyane", "test/countries/__init__.py::TestFrance::test_la_reunion", "test/countries/__init__.py::TestFrance::test_martinique", "test/countries/__init__.py::TestFrance::test_mayotte", "test/countries/__init__.py::TestFrance::test_nouvelle_caledonie", "test/countries/__init__.py::TestFrance::test_others", "test/countries/__init__.py::TestFrance::test_polynesie_francaise", "test/countries/__init__.py::TestFrance::test_saint_barthelemy", "test/countries/__init__.py::TestFrance::test_wallis_et_futuna", "test/countries/__init__.py::TestGeorgia::test_2020", "test/countries/__init__.py::TestGeorgia::test_easter", "test/countries/__init__.py::TestGeorgia::test_not_holiday", "test/countries/__init__.py::TestDE::test_75_jahrestag_beendigung_zweiter_weltkrieg", "test/countries/__init__.py::TestDE::test_all_holidays_present", "test/countries/__init__.py::TestDE::test_allerheiligen", "test/countries/__init__.py::TestDE::test_buss_und_bettag", "test/countries/__init__.py::TestDE::test_christi_himmelfahrt", "test/countries/__init__.py::TestDE::test_fixed_holidays", "test/countries/__init__.py::TestDE::test_frauentag", "test/countries/__init__.py::TestDE::test_fronleichnam", "test/countries/__init__.py::TestDE::test_heilige_drei_koenige", "test/countries/__init__.py::TestDE::test_internationaler_frauentag", "test/countries/__init__.py::TestDE::test_karfreitag", "test/countries/__init__.py::TestDE::test_mariae_himmelfahrt", "test/countries/__init__.py::TestDE::test_no_data_before_1990", "test/countries/__init__.py::TestDE::test_ostermontag", "test/countries/__init__.py::TestDE::test_ostersonntag", "test/countries/__init__.py::TestDE::test_pfingstmontag", "test/countries/__init__.py::TestDE::test_pfingstsonntag", "test/countries/__init__.py::TestDE::test_reformationstag", "test/countries/__init__.py::TestDE::test_tag_der_deutschen_einheit_in_1990", "test/countries/__init__.py::TestDE::test_weltkindertag", "test/countries/__init__.py::TestGreece::test_fixed_holidays", "test/countries/__init__.py::TestGreece::test_gr_clean_monday", "test/countries/__init__.py::TestGreece::test_gr_easter_monday", "test/countries/__init__.py::TestGreece::test_gr_monday_of_the_holy_spirit", "test/countries/__init__.py::TestHonduras::test_2014", "test/countries/__init__.py::TestHonduras::test_2018", "test/countries/__init__.py::TestHongKong::test_ching_ming_festival", "test/countries/__init__.py::TestHongKong::test_christmas_day", "test/countries/__init__.py::TestHongKong::test_chung_yeung_festival", "test/countries/__init__.py::TestHongKong::test_common", "test/countries/__init__.py::TestHongKong::test_easter", "test/countries/__init__.py::TestHongKong::test_first_day_of_january", "test/countries/__init__.py::TestHongKong::test_hksar_day", "test/countries/__init__.py::TestHongKong::test_labour_day", "test/countries/__init__.py::TestHongKong::test_lunar_new_year", "test/countries/__init__.py::TestHongKong::test_mid_autumn_festival", "test/countries/__init__.py::TestHongKong::test_national_day", "test/countries/__init__.py::TestHongKong::test_tuen_ng_festival", "test/countries/__init__.py::TestHungary::test_2018", "test/countries/__init__.py::TestHungary::test_additional_day_off", "test/countries/__init__.py::TestHungary::test_all_saints_day_since_1999", "test/countries/__init__.py::TestHungary::test_christian_holidays_2nd_day_was_not_held_in_1955", "test/countries/__init__.py::TestHungary::test_foundation_day_renamed_during_communism", "test/countries/__init__.py::TestHungary::test_good_friday_since_2017", "test/countries/__init__.py::TestHungary::test_holidays_during_communism", "test/countries/__init__.py::TestHungary::test_labour_day_since_1946", "test/countries/__init__.py::TestHungary::test_labour_day_was_doubled_in_early_50s", "test/countries/__init__.py::TestHungary::test_monday_new_years_eve_day_off", "test/countries/__init__.py::TestHungary::test_national_day_was_not_celebrated_during_communism", "test/countries/__init__.py::TestHungary::test_october_national_day_since_1991", "test/countries/__init__.py::TestHungary::test_whit_monday_since_1992", "test/countries/__init__.py::TestIceland::test_commerce_day", "test/countries/__init__.py::TestIceland::test_first_day_of_summer", "test/countries/__init__.py::TestIceland::test_holy_friday", "test/countries/__init__.py::TestIceland::test_maundy_thursday", "test/countries/__init__.py::TestIceland::test_new_year", "test/countries/__init__.py::TestIND::test_2018", "test/countries/__init__.py::TestIreland::test_2020", "test/countries/__init__.py::TestIreland::test_may_day", "test/countries/__init__.py::TestIreland::test_st_stephens_day", "test/countries/__init__.py::TestIsrael::test_independence_day", "test/countries/__init__.py::TestIsrael::test_memorial_day", "test/countries/__init__.py::TestIsrael::test_purim_day", "test/countries/__init__.py::TestItaly::test_2017", "test/countries/__init__.py::TestItaly::test_christmas", "test/countries/__init__.py::TestItaly::test_easter", "test/countries/__init__.py::TestItaly::test_easter_monday", "test/countries/__init__.py::TestItaly::test_liberation_day_after_1946", "test/countries/__init__.py::TestItaly::test_liberation_day_before_1946", "test/countries/__init__.py::TestItaly::test_new_years", "test/countries/__init__.py::TestItaly::test_province_specific_days", "test/countries/__init__.py::TestItaly::test_republic_day_after_1948", "test/countries/__init__.py::TestItaly::test_republic_day_before_1948", "test/countries/__init__.py::TestItaly::test_saint_stephan", "test/countries/__init__.py::TestJamaica::test_ash_wednesday", "test/countries/__init__.py::TestJamaica::test_boxing_day", "test/countries/__init__.py::TestJamaica::test_christmas_day", "test/countries/__init__.py::TestJamaica::test_easter", "test/countries/__init__.py::TestJamaica::test_easter_monday", "test/countries/__init__.py::TestJamaica::test_emancipation_day", "test/countries/__init__.py::TestJamaica::test_fathers_day", "test/countries/__init__.py::TestJamaica::test_good_friday", "test/countries/__init__.py::TestJamaica::test_independence_day", "test/countries/__init__.py::TestJamaica::test_labour_day", "test/countries/__init__.py::TestJamaica::test_mothers_day", "test/countries/__init__.py::TestJamaica::test_national_heroes_day", "test/countries/__init__.py::TestJamaica::test_new_years_day", "test/countries/__init__.py::TestJamaica::test_valentines_day", "test/countries/__init__.py::TestJapan::test_autumnal_equinox_day", "test/countries/__init__.py::TestJapan::test_childrens_day", "test/countries/__init__.py::TestJapan::test_coming_of_age", "test/countries/__init__.py::TestJapan::test_constitution_memorial_day", "test/countries/__init__.py::TestJapan::test_culture_day", "test/countries/__init__.py::TestJapan::test_emperors_birthday", "test/countries/__init__.py::TestJapan::test_foundation_day", "test/countries/__init__.py::TestJapan::test_greenery_day", "test/countries/__init__.py::TestJapan::test_health_and_sports_day", "test/countries/__init__.py::TestJapan::test_heisei_emperor_holidays", "test/countries/__init__.py::TestJapan::test_invalid_years", "test/countries/__init__.py::TestJapan::test_labour_thanks_giving_day", "test/countries/__init__.py::TestJapan::test_marine_day", "test/countries/__init__.py::TestJapan::test_mountain_day", "test/countries/__init__.py::TestJapan::test_new_years_day", "test/countries/__init__.py::TestJapan::test_reiwa_emperor_holidays", "test/countries/__init__.py::TestJapan::test_respect_for_the_aged_day", "test/countries/__init__.py::TestJapan::test_showa_day", "test/countries/__init__.py::TestJapan::test_showa_emperor_holidays", "test/countries/__init__.py::TestJapan::test_vernal_equinox_day", "test/countries/__init__.py::TestKenya::test_2019", "test/countries/__init__.py::TestKorea::test_birthday_of_buddha", "test/countries/__init__.py::TestKorea::test_childrens_day", "test/countries/__init__.py::TestKorea::test_christmas_day", "test/countries/__init__.py::TestKorea::test_chuseok", "test/countries/__init__.py::TestKorea::test_common", "test/countries/__init__.py::TestKorea::test_constitution_day", "test/countries/__init__.py::TestKorea::test_first_day_of_january", "test/countries/__init__.py::TestKorea::test_hangeul_day", "test/countries/__init__.py::TestKorea::test_independence_movement_day", "test/countries/__init__.py::TestKorea::test_labour_day", "test/countries/__init__.py::TestKorea::test_liberation_day", "test/countries/__init__.py::TestKorea::test_lunar_new_year", "test/countries/__init__.py::TestKorea::test_memorial_day", "test/countries/__init__.py::TestKorea::test_national_foundation_day", "test/countries/__init__.py::TestKorea::test_tree_planting_day", "test/countries/__init__.py::TestKorea::test_years_range", "test/countries/__init__.py::TestLatvia::test_2020", "test/countries/__init__.py::TestLithuania::test_2018", "test/countries/__init__.py::TestLithuania::test_day_of_dew", "test/countries/__init__.py::TestLithuania::test_easter", "test/countries/__init__.py::TestLithuania::test_fathers_day", "test/countries/__init__.py::TestLithuania::test_mothers_day", "test/countries/__init__.py::TestLU::test_2019", "test/countries/__init__.py::TestMalawi::test_easter", "test/countries/__init__.py::TestMalawi::test_good_friday", "test/countries/__init__.py::TestMalawi::test_new_years", "test/countries/__init__.py::TestMalawi::test_not_holiday", "test/countries/__init__.py::TestMalawi::test_static", "test/countries/__init__.py::TestMX::test_benito_juarez", "test/countries/__init__.py::TestMX::test_change_of_government", "test/countries/__init__.py::TestMX::test_christmas", "test/countries/__init__.py::TestMX::test_constitution_day", "test/countries/__init__.py::TestMX::test_independence_day", "test/countries/__init__.py::TestMX::test_labor_day", "test/countries/__init__.py::TestMX::test_new_years", "test/countries/__init__.py::TestMX::test_revolution_day", "test/countries/__init__.py::TestMorocco::test_1961", "test/countries/__init__.py::TestMorocco::test_1999", "test/countries/__init__.py::TestMorocco::test_2019", "test/countries/__init__.py::TestMorocco::test_hijri_based", "test/countries/__init__.py::TestMozambique::test_easter", "test/countries/__init__.py::TestMozambique::test_new_years", "test/countries/__init__.py::TestMozambique::test_not_holiday", "test/countries/__init__.py::TestNetherlands::test_2017", "test/countries/__init__.py::TestNetherlands::test_ascension_day", "test/countries/__init__.py::TestNetherlands::test_easter", "test/countries/__init__.py::TestNetherlands::test_easter_monday", "test/countries/__init__.py::TestNetherlands::test_first_christmas", "test/countries/__init__.py::TestNetherlands::test_kings_day_after_2014", "test/countries/__init__.py::TestNetherlands::test_kings_day_after_2014_substituted_earlier", "test/countries/__init__.py::TestNetherlands::test_liberation_day", "test/countries/__init__.py::TestNetherlands::test_liberation_day_after_1990_in_lustrum_year", "test/countries/__init__.py::TestNetherlands::test_liberation_day_after_1990_non_lustrum_year", "test/countries/__init__.py::TestNetherlands::test_new_years", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1891_and_1948", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1891_and_1948_substituted_later", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1949_and_1980_substituted_later", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1949_and_2013", "test/countries/__init__.py::TestNetherlands::test_queens_day_between_1980_and_2013_substituted_earlier", "test/countries/__init__.py::TestNetherlands::test_second_christmas", "test/countries/__init__.py::TestNetherlands::test_whit_monday", "test/countries/__init__.py::TestNetherlands::test_whit_sunday", "test/countries/__init__.py::TestNZ::test_all_holidays_present", "test/countries/__init__.py::TestNZ::test_anzac_day", "test/countries/__init__.py::TestNZ::test_auckland_anniversary_day", "test/countries/__init__.py::TestNZ::test_boxing_day", "test/countries/__init__.py::TestNZ::test_canterbury_anniversary_day", "test/countries/__init__.py::TestNZ::test_chatham_islands_anniversary_day", "test/countries/__init__.py::TestNZ::test_christmas_day", "test/countries/__init__.py::TestNZ::test_day_after_new_years", "test/countries/__init__.py::TestNZ::test_easter_monday", "test/countries/__init__.py::TestNZ::test_good_friday", "test/countries/__init__.py::TestNZ::test_hawkes_bay_anniversary_day", "test/countries/__init__.py::TestNZ::test_labour_day", "test/countries/__init__.py::TestNZ::test_marlborough_anniversary_day", "test/countries/__init__.py::TestNZ::test_nelson_anniversary_day", "test/countries/__init__.py::TestNZ::test_new_years", "test/countries/__init__.py::TestNZ::test_otago_anniversary_day", "test/countries/__init__.py::TestNZ::test_south_canterbury_anniversary_day", "test/countries/__init__.py::TestNZ::test_southland_anniversary_day", "test/countries/__init__.py::TestNZ::test_sovereigns_birthday", "test/countries/__init__.py::TestNZ::test_taranaki_anniversary_day", "test/countries/__init__.py::TestNZ::test_waitangi_day", "test/countries/__init__.py::TestNZ::test_wellington_anniversary_day", "test/countries/__init__.py::TestNZ::test_westland_anniversary_day", "test/countries/__init__.py::TestNicaragua::test_ni_holidays_2020", "test/countries/__init__.py::TestNigeria::test_fixed_holidays", "test/countries/__init__.py::TestNorway::test_christmas", "test/countries/__init__.py::TestNorway::test_constitution_day", "test/countries/__init__.py::TestNorway::test_easter", "test/countries/__init__.py::TestNorway::test_new_years", "test/countries/__init__.py::TestNorway::test_not_holiday", "test/countries/__init__.py::TestNorway::test_pentecost", "test/countries/__init__.py::TestNorway::test_sundays", "test/countries/__init__.py::TestNorway::test_workers_day", "test/countries/__init__.py::TestParaguay::test_easter", "test/countries/__init__.py::TestParaguay::test_fixed_holidays", "test/countries/__init__.py::TestParaguay::test_no_observed", "test/countries/__init__.py::TestPeru::test_2019", "test/countries/__init__.py::TestPL::test_2017", "test/countries/__init__.py::TestPL::test_2018", "test/countries/__init__.py::TestPL::test_polish_deprecated", "test/countries/__init__.py::TestPT::test_2017", "test/countries/__init__.py::TestPortugalExt::test_2017", "test/countries/__init__.py::TestRomania::test_2020", "test/countries/__init__.py::TestRomania::test_children_s_day", "test/countries/__init__.py::TestRussia::test_2018", "test/countries/__init__.py::TestRussia::test_before_2005", "test/countries/__init__.py::TestSaudiArabia::test_2020", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_not_observed", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_observed", "test/countries/__init__.py::TestSaudiArabia::test_hijri_based_with_two_holidays_in_one_year", "test/countries/__init__.py::TestSaudiArabia::test_national_day", "test/countries/__init__.py::TestSaudiArabia::test_national_day_not_observed", "test/countries/__init__.py::TestSaudiArabia::test_national_day_observed", "test/countries/__init__.py::TestSerbia::test_armistice_day", "test/countries/__init__.py::TestSerbia::test_labour_day", "test/countries/__init__.py::TestSerbia::test_new_year", "test/countries/__init__.py::TestSerbia::test_religious_holidays", "test/countries/__init__.py::TestSerbia::test_statehood_day", "test/countries/__init__.py::TestSingapore::test_Singapore", "test/countries/__init__.py::TestSK::test_2018", "test/countries/__init__.py::TestSK::test_slovak_deprecated", "test/countries/__init__.py::TestSI::test_holidays", "test/countries/__init__.py::TestSI::test_missing_years", "test/countries/__init__.py::TestSI::test_non_holidays", "test/countries/__init__.py::TestSouthAfrica::test_easter", "test/countries/__init__.py::TestSouthAfrica::test_elections", "test/countries/__init__.py::TestSouthAfrica::test_historic", "test/countries/__init__.py::TestSouthAfrica::test_new_years", "test/countries/__init__.py::TestSouthAfrica::test_not_holiday", "test/countries/__init__.py::TestSouthAfrica::test_onceoff", "test/countries/__init__.py::TestSouthAfrica::test_static", "test/countries/__init__.py::TestSpain::test_fixed_holidays", "test/countries/__init__.py::TestSpain::test_fixed_holidays_observed", "test/countries/__init__.py::TestSpain::test_province_specific_days", "test/countries/__init__.py::TestSweden::test_christmas", "test/countries/__init__.py::TestSweden::test_constitution_day", "test/countries/__init__.py::TestSweden::test_easter", "test/countries/__init__.py::TestSweden::test_new_years", "test/countries/__init__.py::TestSweden::test_not_holiday", "test/countries/__init__.py::TestSweden::test_pentecost", "test/countries/__init__.py::TestSweden::test_sundays", "test/countries/__init__.py::TestSweden::test_workers_day", "test/countries/__init__.py::TestSwitzerland::test_all_holidays_present", "test/countries/__init__.py::TestSwitzerland::test_allerheiligen", "test/countries/__init__.py::TestSwitzerland::test_auffahrt", "test/countries/__init__.py::TestSwitzerland::test_berchtoldstag", "test/countries/__init__.py::TestSwitzerland::test_bruder_chlaus", "test/countries/__init__.py::TestSwitzerland::test_fest_der_unabhaengikeit", "test/countries/__init__.py::TestSwitzerland::test_fixed_holidays", "test/countries/__init__.py::TestSwitzerland::test_fronleichnam", "test/countries/__init__.py::TestSwitzerland::test_heilige_drei_koenige", "test/countries/__init__.py::TestSwitzerland::test_jahrestag_der_ausrufung_der_republik", "test/countries/__init__.py::TestSwitzerland::test_jeune_genevois", "test/countries/__init__.py::TestSwitzerland::test_josefstag", "test/countries/__init__.py::TestSwitzerland::test_karfreitag", "test/countries/__init__.py::TestSwitzerland::test_lundi_du_jeune", "test/countries/__init__.py::TestSwitzerland::test_mariae_himmelfahrt", "test/countries/__init__.py::TestSwitzerland::test_naefelser_fahrt", "test/countries/__init__.py::TestSwitzerland::test_ostermontag", "test/countries/__init__.py::TestSwitzerland::test_ostern", "test/countries/__init__.py::TestSwitzerland::test_peter_und_paul", "test/countries/__init__.py::TestSwitzerland::test_pfingsten", "test/countries/__init__.py::TestSwitzerland::test_pfingstmontag", "test/countries/__init__.py::TestSwitzerland::test_stephanstag", "test/countries/__init__.py::TestSwitzerland::test_wiedererstellung_der_republik", "test/countries/__init__.py::TestTurkey::test_2019", "test/countries/__init__.py::TestTurkey::test_hijri_based", "test/countries/__init__.py::TestUkraine::test_2018", "test/countries/__init__.py::TestUkraine::test_before_1918", "test/countries/__init__.py::TestUkraine::test_old_holidays", "test/countries/__init__.py::UnitedArabEmirates::test_2020", "test/countries/__init__.py::UnitedArabEmirates::test_commemoration_day_since_2015", "test/countries/__init__.py::UnitedArabEmirates::test_hijri_based", "test/countries/__init__.py::TestUK::test_all_holidays_present", "test/countries/__init__.py::TestUK::test_boxing_day", "test/countries/__init__.py::TestUK::test_christmas_day", "test/countries/__init__.py::TestUK::test_easter_monday", "test/countries/__init__.py::TestUK::test_good_friday", "test/countries/__init__.py::TestUK::test_may_day", "test/countries/__init__.py::TestUK::test_new_years", "test/countries/__init__.py::TestUK::test_queens_jubilees", "test/countries/__init__.py::TestUK::test_royal_weddings", "test/countries/__init__.py::TestUK::test_spring_bank_holiday", "test/countries/__init__.py::TestScotland::test_2017", "test/countries/__init__.py::TestIsleOfMan::test_2018", "test/countries/__init__.py::TestNorthernIreland::test_2018", "test/countries/__init__.py::TestUS::test_alaska_day", "test/countries/__init__.py::TestUS::test_all_souls_day", "test/countries/__init__.py::TestUS::test_arbor_day", "test/countries/__init__.py::TestUS::test_bennington_battle_day", "test/countries/__init__.py::TestUS::test_casimir_pulaski_day", "test/countries/__init__.py::TestUS::test_cesar_chavez_day", "test/countries/__init__.py::TestUS::test_christmas_day", "test/countries/__init__.py::TestUS::test_christmas_eve", "test/countries/__init__.py::TestUS::test_columbus_day", "test/countries/__init__.py::TestUS::test_confederate_memorial_day", "test/countries/__init__.py::TestUS::test_constitution_day", "test/countries/__init__.py::TestUS::test_day_after_christmas", "test/countries/__init__.py::TestUS::test_discovery_day", "test/countries/__init__.py::TestUS::test_easter_monday", "test/countries/__init__.py::TestUS::test_election_day", "test/countries/__init__.py::TestUS::test_emancipation_day", "test/countries/__init__.py::TestUS::test_emancipation_day_in_puerto_rico", "test/countries/__init__.py::TestUS::test_emancipation_day_in_texas", "test/countries/__init__.py::TestUS::test_emancipation_day_in_virgin_islands", "test/countries/__init__.py::TestUS::test_epiphany", "test/countries/__init__.py::TestUS::test_evacuation_day", "test/countries/__init__.py::TestUS::test_good_friday", "test/countries/__init__.py::TestUS::test_guam_discovery_day", "test/countries/__init__.py::TestUS::test_holy_thursday", "test/countries/__init__.py::TestUS::test_inauguration_day", "test/countries/__init__.py::TestUS::test_independence_day", "test/countries/__init__.py::TestUS::test_jefferson_davis_birthday", "test/countries/__init__.py::TestUS::test_kamehameha_day", "test/countries/__init__.py::TestUS::test_labor_day", "test/countries/__init__.py::TestUS::test_lady_of_camarin_day", "test/countries/__init__.py::TestUS::test_lee_jackson_day", "test/countries/__init__.py::TestUS::test_liberation_day_guam", "test/countries/__init__.py::TestUS::test_liberty_day", "test/countries/__init__.py::TestUS::test_lincolns_birthday", "test/countries/__init__.py::TestUS::test_lyndon_baines_johnson_day", "test/countries/__init__.py::TestUS::test_mardi_gras", "test/countries/__init__.py::TestUS::test_martin_luther", "test/countries/__init__.py::TestUS::test_memorial_day", "test/countries/__init__.py::TestUS::test_nevada_day", "test/countries/__init__.py::TestUS::test_new_years", "test/countries/__init__.py::TestUS::test_new_years_eve", "test/countries/__init__.py::TestUS::test_patriots_day", "test/countries/__init__.py::TestUS::test_pioneer_day", "test/countries/__init__.py::TestUS::test_primary_election_day", "test/countries/__init__.py::TestUS::test_prince_jonah_kuhio_kalanianaole_day", "test/countries/__init__.py::TestUS::test_robert_lee_birthday", "test/countries/__init__.py::TestUS::test_san_jacinto_day", "test/countries/__init__.py::TestUS::test_statehood_day", "test/countries/__init__.py::TestUS::test_stewards_day", "test/countries/__init__.py::TestUS::test_susan_b_anthony_day", "test/countries/__init__.py::TestUS::test_texas_independence_day", "test/countries/__init__.py::TestUS::test_thanksgiving_day", "test/countries/__init__.py::TestUS::test_three_kings_day", "test/countries/__init__.py::TestUS::test_town_meeting_day", "test/countries/__init__.py::TestUS::test_transfer_day", "test/countries/__init__.py::TestUS::test_truman_day", "test/countries/__init__.py::TestUS::test_veterans_day", "test/countries/__init__.py::TestUS::test_victory_day", "test/countries/__init__.py::TestUS::test_washingtons_birthday", "test/countries/__init__.py::TestUS::test_west_virginia_day", "test/countries/__init__.py::TestVietnam::test_common", "test/countries/__init__.py::TestVietnam::test_first_day_of_january", "test/countries/__init__.py::TestVietnam::test_independence_day", "test/countries/__init__.py::TestVietnam::test_international_labor_day", "test/countries/__init__.py::TestVietnam::test_king_hung_day", "test/countries/__init__.py::TestVietnam::test_liberation_day", "test/countries/__init__.py::TestVietnam::test_lunar_new_year", "test/countries/__init__.py::TestVietnam::test_years_range", "test/countries/test_spain.py::TestSpain::test_fixed_holidays", "test/countries/test_spain.py::TestSpain::test_fixed_holidays_observed", "test/countries/test_spain.py::TestSpain::test_province_specific_days", "test/countries/test_united_states.py::TestUS::test_alaska_day", "test/countries/test_united_states.py::TestUS::test_all_souls_day", "test/countries/test_united_states.py::TestUS::test_arbor_day", "test/countries/test_united_states.py::TestUS::test_bennington_battle_day", "test/countries/test_united_states.py::TestUS::test_casimir_pulaski_day", "test/countries/test_united_states.py::TestUS::test_cesar_chavez_day", "test/countries/test_united_states.py::TestUS::test_christmas_day", "test/countries/test_united_states.py::TestUS::test_christmas_eve", "test/countries/test_united_states.py::TestUS::test_columbus_day", "test/countries/test_united_states.py::TestUS::test_confederate_memorial_day", "test/countries/test_united_states.py::TestUS::test_constitution_day", "test/countries/test_united_states.py::TestUS::test_day_after_christmas", "test/countries/test_united_states.py::TestUS::test_discovery_day", "test/countries/test_united_states.py::TestUS::test_easter_monday", "test/countries/test_united_states.py::TestUS::test_election_day", "test/countries/test_united_states.py::TestUS::test_emancipation_day", "test/countries/test_united_states.py::TestUS::test_emancipation_day_in_puerto_rico", "test/countries/test_united_states.py::TestUS::test_emancipation_day_in_texas", "test/countries/test_united_states.py::TestUS::test_emancipation_day_in_virgin_islands", "test/countries/test_united_states.py::TestUS::test_epiphany", "test/countries/test_united_states.py::TestUS::test_evacuation_day", "test/countries/test_united_states.py::TestUS::test_good_friday", "test/countries/test_united_states.py::TestUS::test_guam_discovery_day", "test/countries/test_united_states.py::TestUS::test_holy_thursday", "test/countries/test_united_states.py::TestUS::test_inauguration_day", "test/countries/test_united_states.py::TestUS::test_independence_day", "test/countries/test_united_states.py::TestUS::test_jefferson_davis_birthday", "test/countries/test_united_states.py::TestUS::test_kamehameha_day", "test/countries/test_united_states.py::TestUS::test_labor_day", "test/countries/test_united_states.py::TestUS::test_lady_of_camarin_day", "test/countries/test_united_states.py::TestUS::test_lee_jackson_day", "test/countries/test_united_states.py::TestUS::test_liberation_day_guam", "test/countries/test_united_states.py::TestUS::test_liberty_day", "test/countries/test_united_states.py::TestUS::test_lincolns_birthday", "test/countries/test_united_states.py::TestUS::test_lyndon_baines_johnson_day", "test/countries/test_united_states.py::TestUS::test_mardi_gras", "test/countries/test_united_states.py::TestUS::test_martin_luther", "test/countries/test_united_states.py::TestUS::test_memorial_day", "test/countries/test_united_states.py::TestUS::test_nevada_day", "test/countries/test_united_states.py::TestUS::test_new_years", "test/countries/test_united_states.py::TestUS::test_new_years_eve", "test/countries/test_united_states.py::TestUS::test_patriots_day", "test/countries/test_united_states.py::TestUS::test_pioneer_day", "test/countries/test_united_states.py::TestUS::test_primary_election_day", "test/countries/test_united_states.py::TestUS::test_prince_jonah_kuhio_kalanianaole_day", "test/countries/test_united_states.py::TestUS::test_robert_lee_birthday", "test/countries/test_united_states.py::TestUS::test_san_jacinto_day", "test/countries/test_united_states.py::TestUS::test_statehood_day", "test/countries/test_united_states.py::TestUS::test_stewards_day", "test/countries/test_united_states.py::TestUS::test_susan_b_anthony_day", "test/countries/test_united_states.py::TestUS::test_texas_independence_day", "test/countries/test_united_states.py::TestUS::test_thanksgiving_day", "test/countries/test_united_states.py::TestUS::test_three_kings_day", "test/countries/test_united_states.py::TestUS::test_town_meeting_day", "test/countries/test_united_states.py::TestUS::test_transfer_day", "test/countries/test_united_states.py::TestUS::test_truman_day", "test/countries/test_united_states.py::TestUS::test_veterans_day", "test/countries/test_united_states.py::TestUS::test_victory_day", "test/countries/test_united_states.py::TestUS::test_washingtons_birthday", "test/countries/test_united_states.py::TestUS::test_west_virginia_day" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-06-22 21:22:30+00:00
mit
1,990
dr-prodigy__python-holidays-555
diff --git a/holidays/countries/spain.py b/holidays/countries/spain.py index 6b2c8dd0..3fd94870 100644 --- a/holidays/countries/spain.py +++ b/holidays/countries/spain.py @@ -185,7 +185,10 @@ class Spain(HolidayBase): elif self.prov == "NC": self._is_observed(date(year, SEP, 27), "Día de Navarra") elif self.prov == "PV": - self._is_observed(date(year, OCT, 25), "Día del Páis Vasco") + if 2011 <= year <= 2013: + self._is_observed( + date(year, OCT, 25), "Día del Páis Vasco" + ) elif self.prov == "RI": self._is_observed(date(year, JUN, 9), "Día de La Rioja")
dr-prodigy/python-holidays
5d89951a3390a8cf3ff73580e93aaace0bca0071
diff --git a/test/countries/test_spain.py b/test/countries/test_spain.py index 6108ad57..822ced95 100644 --- a/test/countries/test_spain.py +++ b/test/countries/test_spain.py @@ -84,7 +84,6 @@ class TestSpain(unittest.TestCase): (9, 11): ["CT"], (9, 27): ["NC"], (10, 9): ["VC"], - (10, 25): ["PV"], } for prov, prov_holidays in self.prov_holidays.items(): for year in range(2010, 2025): @@ -142,3 +141,11 @@ class TestSpain(unittest.TestCase): date(year, *fest_day) in prov_holidays, prov in fest_prov, ) + + def test_change_of_province_specific_days(self): + prov_holidays = self.prov_holidays["PV"] + self.assertNotIn(date(2010, 10, 25), prov_holidays) + self.assertIn(date(2011, 10, 25), prov_holidays) + self.assertIn(date(2012, 10, 25), prov_holidays) + self.assertIn(date(2013, 10, 25), prov_holidays) + self.assertNotIn(date(2014, 10, 25), prov_holidays)
October 25 is no longer holiday in Spain Prov=PV I'm using the WORKDAY integration of Home Assistant to obtain a binary sensor for workdays. AFAIK python-holidays is being used "under the hood" in this integration Yesterday October 25th was wrongly marked as holiday. It's not holiday since 2014. More info (sorry, in spanish): [https://es.wikipedia.org/wiki/D%C3%ADa_del_Pa%C3%ADs_Vasco#Creaci%C3%B3n_y_desaparici%C3%B3n_de_la_festividad]
0.0
5d89951a3390a8cf3ff73580e93aaace0bca0071
[ "test/countries/test_spain.py::TestSpain::test_change_of_province_specific_days" ]
[ "test/countries/test_spain.py::TestSpain::test_fixed_holidays", "test/countries/test_spain.py::TestSpain::test_fixed_holidays_observed", "test/countries/test_spain.py::TestSpain::test_province_specific_days", "test/countries/test_spain.py::TestSpain::test_variable_days_in_2016" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-11-17 13:26:13+00:00
mit
1,991
dr-prodigy__python-holidays-794
diff --git a/holidays/countries/eswatini.py b/holidays/countries/eswatini.py index 00ca75bf..798bd495 100644 --- a/holidays/countries/eswatini.py +++ b/holidays/countries/eswatini.py @@ -80,11 +80,13 @@ class Eswatini(HolidayBase): class Swaziland(Eswatini): - warnings.warn( - "Swaziland is deprecated, use Eswatini instead.", - DeprecationWarning, - ) - pass + def __init__(self, *args, **kwargs) -> None: + warnings.warn( + "Swaziland is deprecated, use Eswatini instead.", + DeprecationWarning, + ) + + super().__init__(*args, **kwargs) class SZ(Eswatini):
dr-prodigy/python-holidays
6f3242d6e357c00dd5878e1f21d24cbe1aaa25ed
diff --git a/test/countries/test_eswatini.py b/test/countries/test_eswatini.py index 29d3d34e..038c2b92 100644 --- a/test/countries/test_eswatini.py +++ b/test/countries/test_eswatini.py @@ -10,6 +10,7 @@ # License: MIT (see LICENSE file) import unittest +import warnings from datetime import date import holidays @@ -59,3 +60,12 @@ class TestEswatini(unittest.TestCase): self.assertIn(date(2021, 4, 26), self.holidays) self.assertIn(date(2021, 12, 27), self.holidays) self.assertIn(date(2023, 1, 2), self.holidays) + + def test_swaziland_deprecation_warning(self): + warnings.simplefilter("default") + with self.assertWarns(Warning): + holidays.Swaziland() + + warnings.simplefilter("error") + with self.assertRaises(Warning): + holidays.Swaziland()
DeprecationWarning upon "import holidays" in version 0.17 The implementation of deprecating the Swaziland calendar contains a bug. Just importing the holidays package is enough to fire the `DeprecationWarning`. **Steps to reproduce (in bash):** ```bash # Setup python -m venv demo source demo/bin/activate pip install --upgrade pip # Bad version pip install holidays==0.17 # Expose bug python -W error::DeprecationWarning -c 'import holidays' # Workoround pip uninstall -y holidays pip install holidays!=0.17 python -W error::DeprecationWarning -c 'import holidays' # Cleanup deactivate rm -rf demo ``` **Expected behavior:** The `DeprecationWarning` should only fire when the user constructs an instance of the `Swaziland` or a subclass.
0.0
6f3242d6e357c00dd5878e1f21d24cbe1aaa25ed
[ "test/countries/test_eswatini.py::TestEswatini::test_swaziland_deprecation_warning" ]
[ "test/countries/test_eswatini.py::TestEswatini::test_easter", "test/countries/test_eswatini.py::TestEswatini::test_holidays", "test/countries/test_eswatini.py::TestEswatini::test_kings_birthday", "test/countries/test_eswatini.py::TestEswatini::test_national_flag_day", "test/countries/test_eswatini.py::TestEswatini::test_new_years", "test/countries/test_eswatini.py::TestEswatini::test_observed", "test/countries/test_eswatini.py::TestEswatini::test_once_off", "test/countries/test_eswatini.py::TestEswatini::test_out_of_range" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-11-15 00:30:03+00:00
mit
1,992
drdoctr__doctr-123
diff --git a/doctr/__main__.py b/doctr/__main__.py index 25889d4c..a50c3236 100644 --- a/doctr/__main__.py +++ b/doctr/__main__.py @@ -182,14 +182,15 @@ def configure(args, parser): login_kwargs = {'auth': None, 'headers': None} build_repo = input("What repo do you want to build the docs for (org/reponame, like 'drdoctr/doctr')? ") - is_private = check_repo_exists(build_repo, **login_kwargs) + is_private = check_repo_exists(build_repo, service='github', **login_kwargs) + check_repo_exists(build_repo, service='travis') deploy_repo = input("What repo do you want to deploy the docs to? [{build_repo}] ".format(build_repo=build_repo)) if not deploy_repo: deploy_repo = build_repo if deploy_repo != build_repo: - check_repo_exists(deploy_repo, **login_kwargs) + check_repo_exists(deploy_repo, service='github', **login_kwargs) N = IncrementingInt(1) diff --git a/doctr/local.py b/doctr/local.py index 7fbf9004..8fe0b6ef 100644 --- a/doctr/local.py +++ b/doctr/local.py @@ -212,7 +212,7 @@ def generate_ssh_key(note, keypath='github_deploy_key'): with open(keypath + ".pub") as f: return f.read() -def check_repo_exists(deploy_repo, *, auth=None, headers=None): +def check_repo_exists(deploy_repo, service='github', *, auth=None, headers=None): """ Checks that the repository exists on GitHub. @@ -227,11 +227,19 @@ def check_repo_exists(deploy_repo, *, auth=None, headers=None): raise RuntimeError('"{deploy_repo}" should be in the form username/repo'.format(deploy_repo=deploy_repo)) user, repo = deploy_repo.split('/') - REPO_URL = 'https://api.github.com/repos/{user}/{repo}' + if service == 'github': + REPO_URL = 'https://api.github.com/repos/{user}/{repo}' + elif service == 'travis': + REPO_URL = 'https://api.travis-ci.org/repos/{user}/{repo}' + else: + raise RuntimeError('Invalid service specified for repo check (neither "travis" nor "github")') + r = requests.get(REPO_URL.format(user=user, repo=repo), auth=auth, headers=headers) if r.status_code == requests.codes.not_found: - raise RuntimeError('"{user}/{repo}" not found on GitHub. Exiting'.format(user=user, repo=repo)) + raise RuntimeError('"{user}/{repo}" not found on {service}. Exiting'.format(user=user, + repo=repo, + service=service)) r.raise_for_status()
drdoctr/doctr
45305afb454eb5dda06fd0deafce6ce70a0e5cee
diff --git a/doctr/tests/test_local.py b/doctr/tests/test_local.py index ba07bb4b..897cfa27 100644 --- a/doctr/tests/test_local.py +++ b/doctr/tests/test_local.py @@ -11,20 +11,33 @@ else: HEADERS = None -def test_bad_user(): +def test_github_bad_user(): with raises(RuntimeError): check_repo_exists('---/invaliduser', headers=HEADERS) -def test_bad_repo(): +def test_github_bad_repo(): with raises(RuntimeError): check_repo_exists('drdoctr/---', headers=HEADERS) -def test_repo_exists(): +def test_github_repo_exists(): assert not check_repo_exists('drdoctr/doctr', headers=HEADERS) -def test_invalid_repo(): +def test_github_invalid_repo(): with raises(RuntimeError): check_repo_exists('fdsf', headers=HEADERS) with raises(RuntimeError): check_repo_exists('fdsf/fdfs/fd', headers=HEADERS) + +def test_travis_bad_user(): + with raises(RuntimeError): + # Travis is case-sensitive + check_repo_exists('dRdoctr/doctr', service='travis') + +def test_travis_bad_repo(): + with raises(RuntimeError): + # Travis is case-sensitive + check_repo_exists('drdoctr/DoCtR', service='travis') + +def test_travis_repo_exists(): + assert not check_repo_exists('drdoctr/doctr', service='travis')
Check for travis repo before generating keys. Otherwise it will just fail and you'll have to regenerate. It's a small optimisation though, that will mostly affect users that make typos. Note that github is not case sensitive for usernames, travis is so for example, I regularly get into trouble when I write my username lowercase and it involves travis.
0.0
45305afb454eb5dda06fd0deafce6ce70a0e5cee
[ "doctr/tests/test_local.py::test_travis_bad_user", "doctr/tests/test_local.py::test_travis_bad_repo" ]
[ "doctr/tests/test_local.py::test_github_bad_user", "doctr/tests/test_local.py::test_github_bad_repo", "doctr/tests/test_local.py::test_github_repo_exists", "doctr/tests/test_local.py::test_github_invalid_repo" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-09-20 19:35:45+00:00
mit
1,993
drdoctr__doctr-217
diff --git a/doctr/__init__.py b/doctr/__init__.py index 9ef98056..d85651c8 100644 --- a/doctr/__init__.py +++ b/doctr/__init__.py @@ -1,6 +1,6 @@ from .local import (encrypt_variable, encrypt_file, GitHub_post, generate_GitHub_token, upload_GitHub_deploy_key, generate_ssh_key, - check_repo_exists) + check_repo_exists, guess_github_repo) from .travis import (decrypt_file, setup_deploy_key, get_token, run, setup_GitHub_push, checkout_deploy_branch, deploy_branch_exists, set_git_user_email, create_deploy_branch, copy_to_tmp, sync_from_log, @@ -9,7 +9,7 @@ from .travis import (decrypt_file, setup_deploy_key, get_token, run, __all__ = [ 'encrypt_variable', 'encrypt_file', 'GitHub_post', 'generate_GitHub_token', 'upload_GitHub_deploy_key', 'generate_ssh_key', - 'check_repo_exists', + 'check_repo_exists', 'guess_github_repo', 'decrypt_file', 'setup_deploy_key', 'get_token', 'run', 'setup_GitHub_push', 'set_git_user_email', 'checkout_deploy_branch', 'deploy_branch_exists', diff --git a/doctr/__main__.py b/doctr/__main__.py index 41f5f9e9..89f07443 100644 --- a/doctr/__main__.py +++ b/doctr/__main__.py @@ -35,7 +35,8 @@ from pathlib import Path from textwrap import dedent from .local import (generate_GitHub_token, encrypt_variable, encrypt_file, - upload_GitHub_deploy_key, generate_ssh_key, check_repo_exists, GitHub_login) + upload_GitHub_deploy_key, generate_ssh_key, check_repo_exists, + GitHub_login, guess_github_repo) from .travis import (setup_GitHub_push, commit_docs, push_docs, get_current_repo, sync_from_log, find_sphinx_build_dir, run, get_travis_branch, copy_to_tmp, checkout_deploy_branch) @@ -326,9 +327,15 @@ def configure(args, parser): login_kwargs = {'auth': None, 'headers': None} get_build_repo = False + default_repo = guess_github_repo() while not get_build_repo: try: - build_repo = input("What repo do you want to build the docs for (org/reponame, like 'drdoctr/doctr')? ") + if default_repo: + build_repo = input("What repo do you want to build the docs for [{default_repo}]? ".format(default_repo=default_repo)) + if not build_repo: + build_repo = default_repo + else: + build_repo = input("What repo do you want to build the docs for (org/reponame, like 'drdoctr/doctr')? ") is_private = check_repo_exists(build_repo, service='github', **login_kwargs) check_repo_exists(build_repo, service='travis') get_build_repo = True diff --git a/doctr/local.py b/doctr/local.py index 0fb5c85b..a2f702d3 100644 --- a/doctr/local.py +++ b/doctr/local.py @@ -7,6 +7,7 @@ import json import uuid import base64 import subprocess +import re from getpass import getpass import requests @@ -254,3 +255,22 @@ def check_repo_exists(deploy_repo, service='github', *, auth=None, headers=None) r.raise_for_status() return r.json().get('private', False) + +GIT_URL = re.compile(r'(?:git@|https://|git://)github\.com[:/](.*?)(?:\.git)?') + +def guess_github_repo(): + """ + Guesses the github repo for the current directory + + Returns False if no guess can be made. + """ + p = subprocess.run(['git', 'ls-remote', '--get-url', 'origin'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) + if p.stderr or p.returncode: + return False + + url = p.stdout.decode('utf-8').strip() + m = GIT_URL.fullmatch(url) + if not m: + return False + return m.group(1)
drdoctr/doctr
4e6a21054a6a6199ecc2500f4cfa7071b9617472
diff --git a/doctr/tests/test_local.py b/doctr/tests/test_local.py index 21c9aaf2..4d579ed7 100644 --- a/doctr/tests/test_local.py +++ b/doctr/tests/test_local.py @@ -1,6 +1,7 @@ import os -from ..local import check_repo_exists +from ..local import check_repo_exists, GIT_URL, guess_github_repo +from ..__main__ import on_travis import pytest from pytest import raises @@ -46,3 +47,24 @@ def test_travis_bad_repo(): def test_travis_repo_exists(): assert not check_repo_exists('drdoctr/doctr', service='travis') + +def test_GIT_URL(): + for url in [ + 'https://github.com/drdoctr/doctr.git', + 'https://github.com/drdoctr/doctr', + 'git://github.com/drdoctr/doctr.git', + 'git://github.com/drdoctr/doctr', + '[email protected]:drdoctr/doctr.git', + '[email protected]:drdoctr/doctr', + ]: + assert GIT_URL.fullmatch(url).groups() == ('drdoctr/doctr',), url + + assert not GIT_URL.fullmatch('https://gitlab.com/drdoctr/doctr.git') + +def test_guess_github_repo(): + """ + Only works if run in this repo, and if cloned from origin. For safety, + only run on Travis + """ + if on_travis(): + assert guess_github_repo() == 'drdoctr/doctr'
doctr configure should guess that the docs are being built for the current repo We will probably need to use the GitHub API some here, because some people clone from the original repo and some people clone from their forks, so we have to detect the root (non-fork) repo. Although as a first pass, just guessing the repo for `origin` would go a long way.
0.0
4e6a21054a6a6199ecc2500f4cfa7071b9617472
[ "doctr/tests/test_local.py::test_travis_bad_user", "doctr/tests/test_local.py::test_travis_bad_repo", "doctr/tests/test_local.py::test_GIT_URL", "doctr/tests/test_local.py::test_guess_github_repo" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-07-15 21:27:30+00:00
mit
1,994
drdoctr__doctr-225
diff --git a/.travis.yml b/.travis.yml index c621f5a3..13a07f42 100644 --- a/.travis.yml +++ b/.travis.yml @@ -51,6 +51,8 @@ script: # GitHub Wiki deploy echo "This page was automatically deployed by doctr on $(date)" > deploy-test.md; python -m doctr deploy --sync --key-path deploy_key.enc --no-require-master --deploy-repo drdoctr/doctr.wiki . --built-docs deploy-test.md; + # Build on tags + python -m doctr deploy --sync --key-path deploy_key.enc "tag-$TRAVIS_TAG" --build-tags --branch-whitelist; fi - if [[ "${TESTS}" == "true" ]]; then pyflakes doctr; diff --git a/docs/recipes.rst b/docs/recipes.rst index a9459026..756a7c06 100644 --- a/docs/recipes.rst +++ b/docs/recipes.rst @@ -41,6 +41,35 @@ For security purposes, it is not possible to deploy from branches on forks requests from forks). If you want to deploy the docs for a branch from a pull request, you will need to push it up to the main repository. +Deploy docs from git tags +========================= + +Travis CI runs separate builds for git tags that are pushed to your repo. By +default, doctr does not deploy on these builds, but it can be enabled with the +``--build-tags`` flag to ``doctr deploy``. This is useful if you want to use +doctr to deploy versioned docs for releases, for example. + +On Travis CI, the tag is set to the environment variable ``$TRAVIS_TAG``, +which is empty otherwise. The following will deploy the docs to ``dev`` for +normal ``master`` builds, and ``version-<TAG NAME>`` for tag builds: + +.. code:: yaml + + - if [[ -z "$TRAVIS_TAG" ]]; then + DEPLOY_DIR=dev; + else + DEPLOY_DIR="version-$TRAVIS_TAG"; + fi + - doctr deploy --build-tags --built-docs build/ $DEPLOY_DIR + +If you want to deploy only on a tag, use ``--branch-whitelist`` with no +arguments to tell doctr to not deploy from any branch. For instance, to deploy +only tags to ``latest``: + +.. code:: yaml + + - doctr deploy latest --built-docs build/ --build-tags --branch-whitelist + Deploy to a separate repo ========================= diff --git a/doctr/__main__.py b/doctr/__main__.py index 524dacc8..befc05a2 100644 --- a/doctr/__main__.py +++ b/doctr/__main__.py @@ -145,6 +145,10 @@ options available. help=argparse.SUPPRESS) deploy_parser_add_argument('--deploy-repo', default=None, help="""Repo to deploy the docs to. By default, it deploys to the repo Doctr is run from.""") + deploy_parser_add_argument('--branch-whitelist', default=None, nargs='*', + help="""Branches to deploy from. Pass no arguments to not build on any branch + (typically used in conjunction with --build-tags). Note that you can + deploy from every branch with --no-require-master.""", type=set, metavar="BRANCH") deploy_parser_add_argument('--no-require-master', dest='require_master', action='store_false', default=True, help="""Allow docs to be pushed from a branch other than master""") deploy_parser_add_argument('--command', default=None, @@ -163,6 +167,11 @@ options available. deploy_parser_add_argument('--no-push', dest='push', action='store_false', default=True, help="Run all the steps except the last push step. " "Useful for debugging") + deploy_parser_add_argument('--build-tags', action='store_true', + default=False, help="""Deploy on tag builds. On a tag build, + $TRAVIS_TAG is set to the name of the tag. The default is to not + deploy on tag builds. Note that this will still build on a branch, + unless --branch-whitelist (with no arguments) is passed.""") deploy_parser_add_argument('--gh-pages-docs', default=None, help="""!!DEPRECATED!! Directory to deploy the html documentation to on gh-pages. The default is %(default)r. The deploy directory should be passed as @@ -273,13 +282,19 @@ def deploy(args, parser): current_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip() try: - branch_whitelist = {'master'} if args.require_master else set(get_travis_branch()) + branch_whitelist = set() if args.require_master else set(get_travis_branch()) branch_whitelist.update(set(config.get('branches',set({})))) + if args.branch_whitelist is not None: + branch_whitelist.update(args.branch_whitelist) + if not args.branch_whitelist: + branch_whitelist = {'master'} canpush = setup_GitHub_push(deploy_repo, deploy_branch=deploy_branch, auth_type='token' if args.token else 'deploy_key', full_key_path=keypath, - branch_whitelist=branch_whitelist, env_name=env_name) + branch_whitelist=branch_whitelist, + build_tags=args.build_tags, + env_name=env_name) if args.sync: built_docs = args.built_docs or find_sphinx_build_dir() diff --git a/doctr/travis.py b/doctr/travis.py index 557c4a9d..9682022c 100644 --- a/doctr/travis.py +++ b/doctr/travis.py @@ -183,8 +183,10 @@ def get_travis_branch(): else: return os.environ.get("TRAVIS_BRANCH", "") -def setup_GitHub_push(deploy_repo, auth_type='deploy_key', full_key_path='github_deploy_key.enc', - require_master=None, branch_whitelist=None, deploy_branch='gh-pages', env_name='DOCTR_DEPLOY_ENCRYPTION_KEY'): +def setup_GitHub_push(deploy_repo, *, auth_type='deploy_key', + full_key_path='github_deploy_key.enc', require_master=None, + branch_whitelist=None, deploy_branch='gh-pages', + env_name='DOCTR_DEPLOY_ENCRYPTION_KEY', build_tags=False): """ Setup the remote to push to GitHub (to be run on Travis). @@ -196,6 +198,8 @@ def setup_GitHub_push(deploy_repo, auth_type='deploy_key', full_key_path='github For ``auth_type='deploy_key'``, this sets up the remote with ssh access. """ + # Set to the name of the tag for tag builds + TRAVIS_TAG = os.environ.get("TRAVIS_TAG", "") if not branch_whitelist: branch_whitelist={'master'} @@ -213,8 +217,12 @@ def setup_GitHub_push(deploy_repo, auth_type='deploy_key', full_key_path='github TRAVIS_BRANCH = os.environ.get("TRAVIS_BRANCH", "") TRAVIS_PULL_REQUEST = os.environ.get("TRAVIS_PULL_REQUEST", "") - canpush = determine_push_rights(branch_whitelist, TRAVIS_BRANCH, - TRAVIS_PULL_REQUEST) + canpush = determine_push_rights( + branch_whitelist=branch_whitelist, + TRAVIS_BRANCH=TRAVIS_BRANCH, + TRAVIS_PULL_REQUEST=TRAVIS_PULL_REQUEST, + TRAVIS_TAG=TRAVIS_TAG, + build_tags=build_tags) print("Setting git attributes") set_git_user_email() @@ -441,6 +449,9 @@ def commit_docs(*, added, removed): TRAVIS_COMMIT = os.environ.get("TRAVIS_COMMIT", "<unknown>") TRAVIS_REPO_SLUG = os.environ.get("TRAVIS_REPO_SLUG", "<unknown>") TRAVIS_JOB_ID = os.environ.get("TRAVIS_JOB_ID", "") + TRAVIS_TAG = os.environ.get("TRAVIS_TAG", "") + branch = "tag" if TRAVIS_TAG else "branch" + DOCTR_COMMAND = ' '.join(map(shlex.quote, sys.argv)) for f in added: @@ -452,7 +463,7 @@ def commit_docs(*, added, removed): Update docs after building Travis build {TRAVIS_BUILD_NUMBER} of {TRAVIS_REPO_SLUG} -The docs were built from the branch '{TRAVIS_BRANCH}' against the commit +The docs were built from the {branch} '{TRAVIS_BRANCH}' against the commit {TRAVIS_COMMIT}. The Travis build that generated this commit is at @@ -462,6 +473,7 @@ The doctr command that was run is {DOCTR_COMMAND} """.format( + branch=branch, TRAVIS_BUILD_NUMBER=TRAVIS_BUILD_NUMBER, TRAVIS_BRANCH=TRAVIS_BRANCH, TRAVIS_COMMIT=TRAVIS_COMMIT, @@ -504,12 +516,18 @@ def push_docs(deploy_branch='gh-pages', retries=3): return sys.exit("Giving up...") -def determine_push_rights(branch_whitelist, TRAVIS_BRANCH, TRAVIS_PULL_REQUEST): +def determine_push_rights(*, branch_whitelist, TRAVIS_BRANCH, + TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags): """Check if Travis is running on ``master`` (or a whitelisted branch) to determine if we can/should push the docs to the deploy repo """ canpush = True + if TRAVIS_TAG: + if not build_tags: + print("The docs are not pushed on tag builds. To push on future tag builds, use --build-tags") + return build_tags + if not any([re.compile(x).match(TRAVIS_BRANCH) for x in branch_whitelist]): print("The docs are only pushed to gh-pages from master. To allow pushing from " "a non-master branch, use the --no-require-master flag", file=sys.stderr)
drdoctr/doctr
adcb6b2106ee463af488a901f9aac646e23b6853
diff --git a/doctr/tests/test_travis.py b/doctr/tests/test_travis.py index 6a4c3bbe..136ddeaf 100644 --- a/doctr/tests/test_travis.py +++ b/doctr/tests/test_travis.py @@ -144,16 +144,51 @@ def test_sync_from_log(src, dst): os.chdir(old_curdir) [email protected]("travis_branch, travis_pr, whitelist, canpush", - [('doctr', 'true', 'master', False), - ('doctr', 'false', 'master', False), - ('master', 'true', 'master', False), - ('master', 'false', 'master', True), - ('doctr', 'True', 'doctr', False), - ('doctr', 'false', 'doctr', True), - ('doctr', 'false', 'set()', False), - ]) -def test_determine_push_rights(travis_branch, travis_pr, whitelist, canpush, monkeypatch): - branch_whitelist = {whitelist} [email protected]("""branch_whitelist, TRAVIS_BRANCH, + TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, + canpush""", + [ + + ('master', 'doctr', 'true', "", False, False), + ('master', 'doctr', 'false', "", False, False), + ('master', 'master', 'true', "", False, False), + ('master', 'master', 'false', "", False, True), + ('doctr', 'doctr', 'True', "", False, False), + ('doctr', 'doctr', 'false', "", False, True), + ('set()', 'doctr', 'false', "", False, False), + + ('master', 'doctr', 'true', "tagname", False, False), + ('master', 'doctr', 'false', "tagname", False, False), + ('master', 'master', 'true', "tagname", False, False), + ('master', 'master', 'false', "tagname", False, False), + ('doctr', 'doctr', 'True', "tagname", False, False), + ('doctr', 'doctr', 'false', "tagname", False, False), + ('set()', 'doctr', 'false', "tagname", False, False), + + ('master', 'doctr', 'true', "", True, False), + ('master', 'doctr', 'false', "", True, False), + ('master', 'master', 'true', "", True, False), + ('master', 'master', 'false', "", True, True), + ('doctr', 'doctr', 'True', "", True, False), + ('doctr', 'doctr', 'false', "", True, True), + ('set()', 'doctr', 'false', "", True, False), + + ('master', 'doctr', 'true', "tagname", True, True), + ('master', 'doctr', 'false', "tagname", True, True), + ('master', 'master', 'true', "tagname", True, True), + ('master', 'master', 'false', "tagname", True, True), + ('doctr', 'doctr', 'True', "tagname", True, True), + ('doctr', 'doctr', 'false', "tagname", True, True), + ('set()', 'doctr', 'false', "tagname", True, True), - assert determine_push_rights(branch_whitelist, travis_branch, travis_pr) == canpush + ]) +def test_determine_push_rights(branch_whitelist, TRAVIS_BRANCH, + TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, canpush, monkeypatch): + branch_whitelist = {branch_whitelist} + + assert determine_push_rights( + branch_whitelist=branch_whitelist, + TRAVIS_BRANCH=TRAVIS_BRANCH, + TRAVIS_PULL_REQUEST=TRAVIS_PULL_REQUEST, + TRAVIS_TAG=TRAVIS_TAG, + build_tags=build_tags) == canpush
Ability to do something different on a tag This tool is mainly designed for uploading dev docs, but it can also be used to upload release docs. In that case, we might need some way to do something different on a tag. Or maybe the logic for uploading on a tag should just go in the individual .travis.yml files, in which case we can at least document what it could look like.
0.0
adcb6b2106ee463af488a901f9aac646e23b6853
[ "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true--False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false--False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true--False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false--False-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True--False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false--False-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false--False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false-tagname-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true--True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false--True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true--True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false--True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True--True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false--True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false--True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false-tagname-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false-tagname-True-True]" ]
[ "doctr/tests/test_travis.py::test_sync_from_log[.-src]", "doctr/tests/test_travis.py::test_sync_from_log[dst-src]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-07-16 21:04:11+00:00
mit
1,995
drdoctr__doctr-332
diff --git a/.travis.yml b/.travis.yml index 5e0cee53..5badcd81 100644 --- a/.travis.yml +++ b/.travis.yml @@ -41,7 +41,10 @@ script: echo `date` >> test python -m doctr deploy --key-path deploy_key.enc --no-require-master docs; # Test syncing a tracked file with a change - python -m doctr deploy --sync --key-path deploy_key.enc stash-test --built-docs test; + python -m doctr deploy --sync --key-path deploy_key.enc stash-test/ --built-docs test; + # Test syncing a single file + echo `date` >> test-file + python -m doctr deploy --sync --key-path deploy_key.enc . --built-docs test-file; # Test deploy branch creation. Delete the branch gh-pages-testing on drdoctr/doctr whenever you want to test this. python -m doctr deploy --sync --key-path deploy_key.enc --no-require-master --deploy-branch gh-pages-testing docs; # Test pushing to .github.io @@ -64,7 +67,7 @@ script: fi - if [[ "${TESTS}" == "true" ]]; then pyflakes doctr; - py.test doctr; + py.test doctr -v -rs; fi doctr: diff --git a/doctr/travis.py b/doctr/travis.py index 8df96da2..5f34d682 100644 --- a/doctr/travis.py +++ b/doctr/travis.py @@ -13,6 +13,8 @@ import pathlib import tempfile import time +import requests + from cryptography.fernet import Fernet from .common import red, blue @@ -214,10 +216,21 @@ def setup_GitHub_push(deploy_repo, *, auth_type='deploy_key', TRAVIS_BRANCH = os.environ.get("TRAVIS_BRANCH", "") TRAVIS_PULL_REQUEST = os.environ.get("TRAVIS_PULL_REQUEST", "") + # Check if the repo is a fork + TRAVIS_REPO_SLUG = os.environ["TRAVIS_REPO_SLUG"] + REPO_URL = 'https://api.github.com/repos/{slug}' + r = requests.get(REPO_URL.format(slug=TRAVIS_REPO_SLUG)) + fork = r.json().get('fork', False) + # Rate limits prevent this check from working every time. By default, we + # assume it isn't a fork so that things just work on non-fork builds. + if r.status_code == 403: + print(red("Warning: GitHub's API rate limits prevented doctr from detecting if this build is a fork. If it is, doctr will fail with an error like 'DOCTR_DEPLOY_ENCRYPTION_KEY environment variable is not set'. This error can be safely ignored. If this is not a fork build, you can ignore this warning."), file=sys.stderr) + canpush = determine_push_rights( branch_whitelist=branch_whitelist, TRAVIS_BRANCH=TRAVIS_BRANCH, TRAVIS_PULL_REQUEST=TRAVIS_PULL_REQUEST, + fork=fork, TRAVIS_TAG=TRAVIS_TAG, build_tags=build_tags) @@ -434,14 +447,17 @@ def sync_from_log(src, dst, log_file, exclude=()): files = glob.iglob(join(src, '**'), recursive=True) else: files = [src] - src = os.path.dirname(src) + os.sep + src = os.path.dirname(src) + os.sep if os.sep in src else '' + + os.makedirs(dst, exist_ok=True) # sorted makes this easier to test for f in sorted(files): if any(is_subdir(f, os.path.join(src, i)) for i in exclude): continue new_f = join(dst, f[len(src):]) - if isdir(f): + + if isdir(f) or f.endswith(os.sep): os.makedirs(new_f, exist_ok=True) else: shutil.copy2(f, new_f) @@ -549,7 +565,7 @@ def last_commit_by_doctr(): return False def determine_push_rights(*, branch_whitelist, TRAVIS_BRANCH, - TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags): + TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, fork): """Check if Travis is running on ``master`` (or a whitelisted branch) to determine if we can/should push the docs to the deploy repo """ @@ -570,6 +586,10 @@ def determine_push_rights(*, branch_whitelist, TRAVIS_BRANCH, print("The website and docs are not pushed to gh-pages on pull requests", file=sys.stderr) canpush = False + if fork: + print("The website and docs are not pushed to gh-pages on fork builds.", file=sys.stderr) + canpush = False + if last_commit_by_doctr(): print(red("The last commit on this branch was pushed by doctr. Not pushing to " "avoid an infinite build-loop."), file=sys.stderr)
drdoctr/doctr
3d81f52da6c52b0e062a3c7c5d179cc062287a6b
diff --git a/doctr/tests/test_local.py b/doctr/tests/test_local.py index 78064556..70ea9c94 100644 --- a/doctr/tests/test_local.py +++ b/doctr/tests/test_local.py @@ -68,10 +68,11 @@ def test_GIT_URL(): assert not GIT_URL.fullmatch('https://gitlab.com/drdoctr/doctr.git') [email protected](os.environ.get('TRAVIS_REPO_SLUG', '') != 'drdoctr/doctr', reason="Not run on Travis fork builds") [email protected](not on_travis(), reason="Not on Travis") def test_guess_github_repo(): """ Only works if run in this repo, and if cloned from origin. For safety, - only run on Travis + only run on Travis and not run on fork builds. """ - if on_travis(): - assert guess_github_repo() == 'drdoctr/doctr' + assert guess_github_repo() == 'drdoctr/doctr' diff --git a/doctr/tests/test_travis.py b/doctr/tests/test_travis.py index 09b9e5bf..81286cec 100644 --- a/doctr/tests/test_travis.py +++ b/doctr/tests/test_travis.py @@ -221,46 +221,91 @@ def test_sync_from_log(src, dst): os.chdir(old_curdir) [email protected]("dst", ['dst', 'dst/']) +def test_sync_from_log_file_to_dir(dst): + with tempfile.TemporaryDirectory() as dir: + try: + old_curdir = os.path.abspath(os.curdir) + os.chdir(dir) + + src = 'file' + + with open(src, 'w') as f: + f.write('test1') + + # Test that the sync happens + added, removed = sync_from_log(src, dst, 'logfile') + + assert added == [ + os.path.join('dst', 'file'), + 'logfile', + ] + + assert removed == [] + + assert os.path.isdir(dst) + # Make sure dst is a file + with open(os.path.join('dst', 'file')) as f: + assert f.read() == 'test1' + + + with open('logfile') as f: + assert f.read() == '\n'.join([ + os.path.join('dst', 'file') + ]) + + finally: + os.chdir(old_curdir) + + @pytest.mark.parametrize("""branch_whitelist, TRAVIS_BRANCH, - TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, + TRAVIS_PULL_REQUEST, TRAVIS_TAG, fork, build_tags, canpush""", [ - ('master', 'doctr', 'true', "", False, False), - ('master', 'doctr', 'false', "", False, False), - ('master', 'master', 'true', "", False, False), - ('master', 'master', 'false', "", False, True), - ('doctr', 'doctr', 'True', "", False, False), - ('doctr', 'doctr', 'false', "", False, True), - ('set()', 'doctr', 'false', "", False, False), - - ('master', 'doctr', 'true', "tagname", False, False), - ('master', 'doctr', 'false', "tagname", False, False), - ('master', 'master', 'true', "tagname", False, False), - ('master', 'master', 'false', "tagname", False, False), - ('doctr', 'doctr', 'True', "tagname", False, False), - ('doctr', 'doctr', 'false', "tagname", False, False), - ('set()', 'doctr', 'false', "tagname", False, False), - - ('master', 'doctr', 'true', "", True, False), - ('master', 'doctr', 'false', "", True, False), - ('master', 'master', 'true', "", True, False), - ('master', 'master', 'false', "", True, True), - ('doctr', 'doctr', 'True', "", True, False), - ('doctr', 'doctr', 'false', "", True, True), - ('set()', 'doctr', 'false', "", True, False), - - ('master', 'doctr', 'true', "tagname", True, True), - ('master', 'doctr', 'false', "tagname", True, True), - ('master', 'master', 'true', "tagname", True, True), - ('master', 'master', 'false', "tagname", True, True), - ('doctr', 'doctr', 'True', "tagname", True, True), - ('doctr', 'doctr', 'false', "tagname", True, True), - ('set()', 'doctr', 'false', "tagname", True, True), + ('master', 'doctr', 'true', "", False, False, False), + ('master', 'doctr', 'false', "", False, False, False), + ('master', 'master', 'true', "", False, False, False), + ('master', 'master', 'false', "", False, False, True), + ('doctr', 'doctr', 'True', "", False, False, False), + ('doctr', 'doctr', 'false', "", False, False, True), + ('set()', 'doctr', 'false', "", False, False, False), + + ('master', 'doctr', 'true', "tagname", False, False, False), + ('master', 'doctr', 'false', "tagname", False, False, False), + ('master', 'master', 'true', "tagname", False, False, False), + ('master', 'master', 'false', "tagname", False, False, False), + ('doctr', 'doctr', 'True', "tagname", False, False, False), + ('doctr', 'doctr', 'false', "tagname", False, False, False), + ('set()', 'doctr', 'false', "tagname", False, False, False), + + ('master', 'doctr', 'true', "", False, True, False), + ('master', 'doctr', 'false', "", False, True, False), + ('master', 'master', 'true', "", False, True, False), + ('master', 'master', 'false', "", False, True, True), + ('doctr', 'doctr', 'True', "", False, True, False), + ('doctr', 'doctr', 'false', "", False, True, True), + ('set()', 'doctr', 'false', "", False, True, False), + + ('master', 'doctr', 'true', "tagname", False, True, True), + ('master', 'doctr', 'false', "tagname", False, True, True), + ('master', 'master', 'true', "tagname", False, True, True), + ('master', 'master', 'false', "tagname", False, True, True), + ('doctr', 'doctr', 'True', "tagname", False, True, True), + ('doctr', 'doctr', 'false', "tagname", False, True, True), + ('set()', 'doctr', 'false', "tagname", False, True, True), + + ('master', 'doctr', 'true', "", True, False, False), + ('master', 'doctr', 'false', "", True, False, False), + ('master', 'master', 'true', "", True, False, False), + ('master', 'master', 'false', "", True, False, False), + ('doctr', 'doctr', 'True', "", True, False, False), + ('doctr', 'doctr', 'false', "", True, False, False), + ('set()', 'doctr', 'false', "", True, False, False), ]) def test_determine_push_rights(branch_whitelist, TRAVIS_BRANCH, - TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, canpush, monkeypatch): + TRAVIS_PULL_REQUEST, TRAVIS_TAG, build_tags, fork, canpush, monkeypatch): branch_whitelist = {branch_whitelist} assert determine_push_rights( @@ -268,6 +313,7 @@ def test_determine_push_rights(branch_whitelist, TRAVIS_BRANCH, TRAVIS_BRANCH=TRAVIS_BRANCH, TRAVIS_PULL_REQUEST=TRAVIS_PULL_REQUEST, TRAVIS_TAG=TRAVIS_TAG, + fork=fork, build_tags=build_tags) == canpush @pytest.mark.parametrize("src", ["src", "."])
Detect if the repo is a fork If I'm understanding the behavior I'm seeing correctly, encrypted environment variables aren't available on forks at all, even if they are encrypted with the key for the fork.
0.0
3d81f52da6c52b0e062a3c7c5d179cc062287a6b
[ "doctr/tests/test_travis.py::test_sync_from_log_file_to_dir[dst]", "doctr/tests/test_travis.py::test_sync_from_log_file_to_dir[dst/]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true--False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false--False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true--False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false--False-False-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True--False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false--False-False-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false--False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false-tagname-False-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true--False-True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false--False-True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true--False-True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false--False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True--False-True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false--False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false--False-True-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false-tagname-False-True-True]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-true--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-doctr-false--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-true--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[master-master-false--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-True--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[doctr-doctr-false--True-False-False]", "doctr/tests/test_travis.py::test_determine_push_rights[set()-doctr-false--True-False-False]" ]
[ "doctr/tests/test_local.py::test_GIT_URL", "doctr/tests/test_travis.py::test_sync_from_log[.-src]", "doctr/tests/test_travis.py::test_sync_from_log[dst-src]", "doctr/tests/test_travis.py::test_copy_to_tmp[src]", "doctr/tests/test_travis.py::test_copy_to_tmp[.]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-18 21:47:06+00:00
mit
1,996
drdoctr__doctr-87
diff --git a/docs/changelog.rst b/docs/changelog.rst index 87ee43d7..37c7e2f1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -17,6 +17,7 @@ Minor Changes ------------- - Add a GitHub banner to the docs. (#64) - Move to the GitHub organization `drdoctr <https://github.com/drdoctr>`_. (#67) +- Check if user/org and repo are valid before generating ssh keys or pinging travis (#77) 1.1.1 (2016-08-09) ================== diff --git a/doctr/__init__.py b/doctr/__init__.py index b5afeea2..a0c84a61 100644 --- a/doctr/__init__.py +++ b/doctr/__init__.py @@ -1,5 +1,6 @@ from .local import (encrypt_variable, encrypt_file, GitHub_post, - generate_GitHub_token, upload_GitHub_deploy_key, generate_ssh_key) + generate_GitHub_token, upload_GitHub_deploy_key, generate_ssh_key, + check_repo_exists) from .travis import (decrypt_file, setup_deploy_key, get_token, run, setup_GitHub_push, gh_pages_exists, create_gh_pages, sync_from_log, commit_docs, push_docs, get_current_repo, find_sphinx_build_dir) @@ -7,6 +8,7 @@ from .travis import (decrypt_file, setup_deploy_key, get_token, run, __all__ = [ 'encrypt_variable', 'encrypt_file', 'GitHub_post', 'generate_GitHub_token', 'upload_GitHub_deploy_key', 'generate_ssh_key', + 'check_repo_exists', 'decrypt_file', 'setup_deploy_key', 'get_token', 'run', 'setup_GitHub_push', 'gh_pages_exists', 'create_gh_pages', 'sync_from_log', 'commit_docs', 'push_docs', 'get_current_repo', 'find_sphinx_build_dir' diff --git a/doctr/__main__.py b/doctr/__main__.py index ab10378e..0e19d118 100644 --- a/doctr/__main__.py +++ b/doctr/__main__.py @@ -28,7 +28,7 @@ import argparse from textwrap import dedent from .local import (generate_GitHub_token, encrypt_variable, encrypt_file, - upload_GitHub_deploy_key, generate_ssh_key) + upload_GitHub_deploy_key, generate_ssh_key, check_repo_exists) from .travis import setup_GitHub_push, commit_docs, push_docs, get_current_repo from . import __version__ @@ -135,6 +135,8 @@ def configure(args, parser): if not deploy_repo: deploy_repo = build_repo + check_repo_exists(deploy_repo) + N = IncrementingInt(1) header = "\n================== You should now do the following ==================\n" diff --git a/doctr/local.py b/doctr/local.py index 16a58ac9..8213044d 100644 --- a/doctr/local.py +++ b/doctr/local.py @@ -2,12 +2,12 @@ The code that should be run locally """ -from getpass import getpass -import base64 +import os import json import uuid +import base64 import subprocess -import os +from getpass import getpass import requests from requests.auth import HTTPBasicAuth @@ -39,9 +39,10 @@ def encrypt_variable(variable, build_repo, public_key=None): raise ValueError("variable should be of the form 'VARIABLE=value'") if not public_key: - # TODO: Error handling r = requests.get('https://api.travis-ci.org/repos/{build_repo}/key'.format(build_repo=build_repo), headers={'Accept': 'application/vnd.travis-ci.2+json'}) + if r.status_code == requests.codes.not_found: + raise RuntimeError('Could not find requested repo on Travis. Is Travis enabled?') r.raise_for_status() public_key = r.json()['key'] @@ -172,3 +173,18 @@ def generate_ssh_key(note, keypath='github_deploy_key'): with open(keypath + ".pub") as f: return f.read() + +def check_repo_exists(deploy_repo): + """Checks that the deploy repository exists on GitHub before allowing + user to generate a key to deploy to that repo. + """ + user, repo = deploy_repo.split('/') + search = 'https://api.github.com/search/repositories?q={repo}+user:{user}' + r = requests.get(search.format(user=user, repo=repo)) + + if r.status_code == requests.codes.unprocessable_entity: + raise RuntimeError('User/org "{user}" not found on GitHub. Exiting'.format(user=user)) + elif not r.json()['items']: + raise RuntimeError('No repo named "{repo}" found for user/org "{user}"'.format(repo=repo, user=user)) + + return True
drdoctr/doctr
065c4c64f5a49dcd1e90e78a25d5d8449fcb9d5e
diff --git a/doctr/tests/test_local.py b/doctr/tests/test_local.py new file mode 100644 index 00000000..3a3d9455 --- /dev/null +++ b/doctr/tests/test_local.py @@ -0,0 +1,14 @@ +from ..local import check_repo_exists + +from pytest import raises + +def test_bad_user(): + with raises(RuntimeError): + check_repo_exists('---/invaliduser') + +def test_bad_repo(): + with raises(RuntimeError): + check_repo_exists('drdoctr/---') + +def test_repo_exists(): + assert check_repo_exists('drdoctr/doctr')
Catch exception if travis isn't set up Just caught this when I tried to regenerate the deploy key without first enabling travis Key generation went fine but then requests barfed when it couldn't talk to travis ```console Traceback (most recent call last): File "/home/gil/anaconda/bin/doctr", line 9, in <module> load_entry_point('doctr==1.1.1+42.g9c5359b', 'console_scripts', 'doctr')() File "/home/gil/anaconda/lib/python3.5/site-packages/doctr-1.1.1+42.g9c5359b-py3.5.egg/doctr/__main__.py", line 210, in main return process_args(get_parser()) File "/home/gil/anaconda/lib/python3.5/site-packages/doctr-1.1.1+42.g9c5359b-py3.5.egg/doctr/__main__.py", line 96, in process_args return args.func(args, parser) File "/home/gil/anaconda/lib/python3.5/site-packages/doctr-1.1.1+42.g9c5359b-py3.5.egg/doctr/__main__.py", line 153, in configure encrypted_variable = encrypt_variable(b"DOCTR_DEPLOY_ENCRYPTION_KEY=" + key, build_repo=build_repo) File "/home/gil/anaconda/lib/python3.5/site-packages/doctr-1.1.1+42.g9c5359b-py3.5.egg/doctr/local.py", line 45, in encrypt_variable r.raise_for_status() File "/home/gil/anaconda/lib/python3.5/site-packages/requests/models.py", line 837, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.travis-ci.org/repos/drdoctr/doctr/key ``` We can just catch this exception and gently remind the user to go to travis and enable the repository
0.0
065c4c64f5a49dcd1e90e78a25d5d8449fcb9d5e
[ "doctr/tests/test_local.py::test_bad_user", "doctr/tests/test_local.py::test_bad_repo", "doctr/tests/test_local.py::test_repo_exists" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-08-19 15:17:36+00:00
mit
1,997
drewkerrigan__nagios-http-json-62
diff --git a/check_http_json.py b/check_http_json.py index 6b74bd9..4781abd 100755 --- a/check_http_json.py +++ b/check_http_json.py @@ -225,9 +225,9 @@ class JsonRuleProcessor: if self.rules.value_separator: value_separator = self.rules.value_separator self.helper = JsonHelper(self.data, separator, value_separator) - debugPrint(rules_args.debug, "rules:%s" % rules_args) - debugPrint(rules_args.debug, "separator:%s" % separator) - debugPrint(rules_args.debug, "value_separator:%s" % value_separator) + debugPrint(rules_args.debug, "rules: %s" % rules_args) + debugPrint(rules_args.debug, "separator: %s" % separator) + debugPrint(rules_args.debug, "value_separator: %s" % value_separator) self.metric_list = self.expandKeys(self.rules.metric_list) self.key_threshold_warning = self.expandKeys( self.rules.key_threshold_warning) @@ -346,6 +346,8 @@ class JsonRuleProcessor: def checkCritical(self): failure = '' + if not self.data: + failure = " Empty JSON data." if self.key_threshold_critical is not None: failure += self.checkThresholds(self.key_threshold_critical) if self.key_value_list_critical is not None:
drewkerrigan/nagios-http-json
41279cad2cfdb58ee051db887ee94daea1f578f8
diff --git a/test/test_check_http_json.py b/test/test_check_http_json.py index 489213a..659e77c 100644 --- a/test/test_check_http_json.py +++ b/test/test_check_http_json.py @@ -256,7 +256,7 @@ class UtilTest(unittest.TestCase): # This should not throw a KeyError data = '{}' - self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, WARNING_CODE) + self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, CRITICAL_CODE) def test_subelem(self): @@ -274,3 +274,23 @@ class UtilTest(unittest.TestCase): self.check_data(rules.dash_E(['(*).capacity.value.too_deep']), data, CRITICAL_CODE) # Should not throw keyerror self.check_data(rules.dash_E(['foo']), data, CRITICAL_CODE) + + + def test_empty_key_value_array(self): + """ + https://github.com/drewkerrigan/nagios-http-json/issues/61 + """ + + rules = RulesHelper() + + # This should simply work + data = '[{"update_status": "finished"},{"update_status": "finished"}]' + self.check_data(rules.dash_q(['(*).update_status,finished']), data, OK_CODE) + + # This should warn us + data = '[{"update_status": "finished"},{"update_status": "failure"}]' + self.check_data(rules.dash_q(['(*).update_status,finished']), data, WARNING_CODE) + + # This should throw an error + data = '[]' + self.check_data(rules.dash_q(['(*).update_status,warn_me']), data, CRITICAL_CODE) diff --git a/test/test_main.py b/test/test_main.py index 47d77c7..a531af7 100644 --- a/test/test_main.py +++ b/test/test_main.py @@ -12,7 +12,7 @@ from check_http_json import main class MockResponse(): - def __init__(self, status_code=200, content='{}'): + def __init__(self, status_code=200, content='{"foo": "bar"}'): self.status_code = status_code self.content = content
Using --key-equals with an empty list returns OK Trying to monitor the GitLab mirror status of some projects through the API. Since I don't know how many mirrors exist for a particular project, I use the 'data for keys of all items in a list' notation. This works fine, but the check returns an OK status if the response is an empty list (`[]`). That would mean that if somebody accidentally removed all mirrors we would not be alerted. Equality check used: `-q "(*).update_status,finished"`
0.0
41279cad2cfdb58ee051db887ee94daea1f578f8
[ "test/test_check_http_json.py::UtilTest::test_array_with_missing_element", "test/test_check_http_json.py::UtilTest::test_empty_key_value_array" ]
[ "test/test_check_http_json.py::UtilTest::test_critical_thresholds", "test/test_check_http_json.py::UtilTest::test_equality", "test/test_check_http_json.py::UtilTest::test_equality_colon", "test/test_check_http_json.py::UtilTest::test_exists", "test/test_check_http_json.py::UtilTest::test_metrics", "test/test_check_http_json.py::UtilTest::test_non_equality", "test/test_check_http_json.py::UtilTest::test_separator", "test/test_check_http_json.py::UtilTest::test_subarrayelem_missing_elem", "test/test_check_http_json.py::UtilTest::test_subelem", "test/test_check_http_json.py::UtilTest::test_unknown", "test/test_check_http_json.py::UtilTest::test_warning_thresholds", "test/test_main.py::MainTest::test_main_version", "test/test_main.py::MainTest::test_main_with_http_error_no_json", "test/test_main.py::MainTest::test_main_with_http_error_valid_json", "test/test_main.py::MainTest::test_main_with_parse_error", "test/test_main.py::MainTest::test_main_with_ssl", "test/test_main.py::MainTest::test_main_with_url_error" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-27 06:01:13+00:00
apache-2.0
1,998
dreynolds__local-lambda-17
diff --git a/setup.py b/setup.py index af9a656..9595884 100644 --- a/setup.py +++ b/setup.py @@ -3,23 +3,26 @@ import pathlib from setuptools import find_packages, setup here = pathlib.Path(__file__).parent.resolve() -long_description = (here / 'README.md').read_text(encoding='utf-8') +long_description = (here / "README.md").read_text(encoding="utf-8") setup( - name='local_lambda', - description='Simple mechanism for running lambdas locally for testing', + name="local_lambda", + description="Simple mechanism for running lambdas locally for testing", long_description=long_description, - long_description_content_type='text/markdown', - package_dir={'': 'src'}, # Optional - packages=find_packages(where='src'), - python_requires='>=3.6, <4', + long_description_content_type="text/markdown", + package_dir={"": "src"}, # Optional + packages=find_packages(where="src"), + python_requires=">=3.6, <4", install_requires=[ - 'jsonschema==3.2.0', + "jsonschema==3.2.0", ], use_scm_version=True, setup_requires=['setuptools_scm'], - scripts=['src/scripts/local_lambda'], + scripts=[ + "src/scripts/local_lambda", + "src/scripts/call_command.py", + ], url="https://github.com/dreynolds/local-lambda", author="David Reynolds", author_email="[email protected]", diff --git a/src/config.py b/src/config.py index 2fcfe2b..b0944f9 100644 --- a/src/config.py +++ b/src/config.py @@ -36,6 +36,7 @@ class UrlConfigFile: config_file = self.load_file(self.file_name) try: config_data = json.load(config_file.open()) + LOG.debug(config_data) except json.decoder.JSONDecodeError: LOG.debug(f'"{self.file_name}" is not readable JSON') return None diff --git a/src/config_schema.py b/src/config_schema.py index bab5cef..eebbdb9 100644 --- a/src/config_schema.py +++ b/src/config_schema.py @@ -11,7 +11,10 @@ CONFIG_SCHEMA = { "patternProperties": { ".*": { "type": "object", - "properties": {"function": {"type": "string"}}, + "properties": { + "function": {"type": "string"}, + "env": {"type": "object"}, + }, "required": ["function"], } }, diff --git a/src/lambda_server.py b/src/lambda_server.py index ac3414e..5f2cd91 100644 --- a/src/lambda_server.py +++ b/src/lambda_server.py @@ -4,7 +4,7 @@ import os import sys from config import UrlConfigFile -from server import run, server_methods, AlreadyRegistered +from server import AlreadyRegistered, run, server_methods LOG = logging.getLogger(__name__) DEFAULT_PORT = 5000 @@ -40,6 +40,7 @@ def main() -> None: action="store", help="The port to run the API on", default=os.environ.get("PORT", DEFAULT_PORT), + type=int, ) parser.add_argument( "-c", diff --git a/src/scripts/call_command.py b/src/scripts/call_command.py new file mode 100644 index 0000000..1bbfc39 --- /dev/null +++ b/src/scripts/call_command.py @@ -0,0 +1,40 @@ +import argparse +import sys +import json +from pathlib import Path + +from utils import get_function_from_string + +sys.path.insert(0, Path.cwd().as_posix()) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("command", type=str, nargs=1, help="The command to call") + parser.add_argument( + "--event", + type=str, + action="store", + help="The event to pass to the command", + default="{}", + ) + parser.add_argument( + "--context", + type=str, + action="store", + help="The event to pass to the command", + default="{}", + ) + args = parser.parse_args() + + func = get_function_from_string(args.command[0]) + if func: + try: + event = json.loads(args.event) + except json.JSONDecodeError: + event = {} + try: + context = json.loads(args.context) + except json.JSONDecodeError: + context = {} + output = func(event, context) + print(json.dumps(output)) diff --git a/src/server.py b/src/server.py index 41ba4e3..f19c8a4 100644 --- a/src/server.py +++ b/src/server.py @@ -1,36 +1,61 @@ -from collections import OrderedDict -from http.server import HTTPServer, BaseHTTPRequestHandler +import json import logging -from urllib.parse import urlparse, parse_qs +import os +import subprocess +from collections import OrderedDict +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, HTTPServer +from urllib.parse import parse_qs, urlparse -from utils import get_function_from_string, request_to_event +from utils import request_to_event LOG = logging.getLogger(__name__) class LambdaHandler(BaseHTTPRequestHandler): - def _call_method(self, path, method, qs, body, headers): - function_path = ( - server_methods.get(path, {}).get(method, {}).get("function", None) - ) - if function_path is not None: - func = get_function_from_string(function_path) - if func is not None: - event = request_to_event(path, method, qs, body, headers) - return func(event, {}) + + def _bad_method_response(self): return { "body": "Bad method", - "statusCode": 405, + "statusCode": HTTPStatus.METHOD_NOT_ALLOWED.value, } - def _process(self, method): + def _call_method(self, path, method, qs, body, headers): + function_details = server_methods.get(path, {}).get(method, {}) + function_path = function_details.get("function", None) + function_env = function_details.get("env", {}) + current_env = os.environ.copy() + current_env.update(function_env) + LOG.debug("Generated ENV: %s", current_env) + + if function_path is not None: + event = request_to_event(path, method, qs, body, headers) + command = ["call_command.py", function_path, "--event", json.dumps(event)] + LOG.debug("Command %s", ' '.join(command)) + output = subprocess.check_output( + command, + env=current_env, + ) + try: + output = json.loads(output) + except json.JSONDecodeError: + LOG.exception("Error decoding method output: %s", output) + output = self._bad_method_response() + else: + LOG.debug("Command output: %s", output) + return output + return self._bad_method_response() + + def _process(self, method, body=None): + if body is None: + body = "" url = urlparse(self.path) qs = parse_qs(url.query) response = self._call_method( url.path, method, qs, - "", + body, self.headers.__dict__, ) self.send_response(response["statusCode"]) @@ -43,7 +68,9 @@ class LambdaHandler(BaseHTTPRequestHandler): self._process("GET") def do_POST(self): - self._process("POST") + content_length = int(self.headers.get('Content-Length', 0)) + post_data = self.rfile.read(content_length) + self._process("POST", post_data.decode('utf8')) def do_HEAD(self): self._process("HEAD") diff --git a/src/utils.py b/src/utils.py index a118004..be9e18b 100644 --- a/src/utils.py +++ b/src/utils.py @@ -31,8 +31,10 @@ def request_to_event( "path": path, "httpMethod": method, "isBase64Encoded": False, - "headers": headers, + "headers": {}, "queryStringParameters": qs, } + for k, v in headers.get("_headers", []): + event["headers"][k] = v LOG.debug(event) return event
dreynolds/local-lambda
d722dce8110ec25506b6b1fc912cd45b7cf450e2
diff --git a/tests/functions/main.py b/tests/functions/main.py index eec8935..7cb2f7a 100644 --- a/tests/functions/main.py +++ b/tests/functions/main.py @@ -1,6 +1,14 @@ +import os +import json + + def debug_me(event, context): + body = { + "AWS_DEFAULT_REGION": os.environ.get("AWS_DEFAULT_REGION", ""), + "AWS_ACCOUNT": os.environ.get("AWS_ACCOUNT", ""), + } return { "headers": {}, "statusCode": 200, - "body": "TEST_CODE", + "body": json.dumps(body), } diff --git a/tests/test_utils.py b/tests/test_utils.py index c0ea535..768997f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -9,7 +9,7 @@ def test_request_to_event(): method = "POST" qs = {} body = "BODY" - headers = {"Host": "example.org", "Connection": "keep-alive"} + headers = {"_headers": [("Host", "example.org"), ("Connection", "keep-alive")]} event = request_to_event(path, method, qs, body, headers) assert event == { "body": body, @@ -17,7 +17,10 @@ def test_request_to_event(): "path": path, "httpMethod": method, "isBase64Encoded": False, - "headers": headers, + "headers": { + "Host": "example.org", + "Connection": "keep-alive", + }, "queryStringParameters": qs, }
Run each request in a process so we can inject in environment variables I'm open to other ways of doing this too.
0.0
d722dce8110ec25506b6b1fc912cd45b7cf450e2
[ "tests/test_utils.py::test_request_to_event" ]
[ "tests/test_utils.py::test_register_methods" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-04-03 21:59:00+00:00
mit
1,999
drhagen__parsita-63
diff --git a/docs/alternative_parsers.md b/docs/alternative_parsers.md index 120938f..0253fb0 100644 --- a/docs/alternative_parsers.md +++ b/docs/alternative_parsers.md @@ -2,7 +2,7 @@ ## `parser1 | parser2`: alternative parser -This tries to match `parser1`. If it fails, it then tries to match `parser2`. If both fail, it returns the failure message from whichever one got farther. Either side can be a bare string, not both because `'a' | 'b'` tries to call `__or__` on `str` which fails. To try alternative literals, use `lit` with multiple arguments. +This tries to match `parser1` and `parser2`. If one succeeds and the other fails, it returns the value of the one that succeeded. If both succeed, it returns the value of the one that consumed more input in order to succeed. If both fail, it returns the failure message from whichever one got farther. Either side can be a bare string, but not both because `'a' | 'b'` tries to call `__or__` on `str` which fails. To try alternative literals, use `lit` with multiple arguments. ```python from parsita import * @@ -15,52 +15,53 @@ class NumberParsers(TextParsers): assert NumberParsers.number.parse('4.0000') == Success(4.0) ``` -Currently, `first(a, b, c)` is an alias for `a | b | c`. This reflects the current behavior of the alternative parser, which is to return immediately when there is a success and not try any later parsers. In most parsers, the first and longest alternative parsers have the same behavior, especially if the order of the alternatives is carefully considered. In a future release of Parsita, the `a | b` syntax will construct a `longest` parser, which tries all the parsers and returns the success that consumed the most input. If the current behavior of stopping on the first success is important, construct the parser with the `first` function so that it will continue to operate as expected in future releases. +`a | b | c` is syntactic sugar for `longest(a, b, c)`. There is similar function `first(a, b, c)` that succeeds with the value of the first option to succeed instead of the one that consumed the most input. In most parsers, the first and longest alternative parsers have the same behavior, especially if the order of the alternatives is carefully considered. In version 1 of Parsita, the `a | b` syntax constructed a `first` parser. This was changed in version 2. If the old behavior of stopping on the first success is important, construct the parser with the `first` function to recover the old behavior. -## `first(*parsers)`: first alternative parser +## `longest(*parsers)`: longest alternative parser -This tries to match each parser supplied. As soon as one parser succeeds, this returns with that parser's successful value. If later parsers would have succeeded, that is irrelevant because they are not tried. If all supplied parsers fail, this fails with the longest failure. +This tries to match each parser supplied. After it has tried them all, it returns the result of the one that made the most progress, that is, consumed the most input. If none of the supplied parsers succeeds, then an error is returned corresponding to the parser that got farthest. If two or more parsers are successful and are tied for making the most progress, the result of the first such parser is returned. ```python from parsita import * class ExpressionParsers(TextParsers): - keyword = lit('pi', 'nan', 'inf') name = reg(r'[a-zA-Z_]+') function = name & '(' >> expression << ')' - expression = first(keyword, function, name) + expression = longest(name, function) assert ExpressionParsers.expression.parse('f(x)') == Success(['f', 'x']) -assert ExpressionParsers.expression.parse('pi(x)') == Failure(ParseError( - "Expected end of source but found '('\n" - "Line 1, character 3\n\n" - "pi(x)\n" - " ^ " -)) -# Note how the above fails because `keyword` is matched by `first` so that -# `function`, which would have matched the input, was not tried. ``` -This is the current implementation of the `a | b | c` syntax. In a future version of Parsita, the longest alternative parser will be used instead. +As of version 2 of Parsita, `longest` is the implementation behind the `a | b | c` syntax. It replaced `first`, which was the implementation in version 1. -## `longest(*parsers)`: longest alternative parser +## `first(*parsers)`: first alternative parser -This tries to match each parser supplied. Unlike `first`, `longest` keeps trying parsers even if one or more succeed. After it has tried them all, it returns the result of the one that made the most progress, that is, consumed the most input. If none of the supplied parsers succeeds, then an error is returned corresponding to the parser that got farthest. If two or more parsers are successful and are tied for making the most progress, the result of the first such parser is returned. +This tries to match each parser supplied. As soon as one parser succeeds, this returns with that parser's successful value. If later parsers would have succeeded, that is irrelevant because they are not tried. If all supplied parsers fail, this fails with the longest failure. ```python from parsita import * class ExpressionParsers(TextParsers): + keyword = lit('pi', 'nan', 'inf') name = reg(r'[a-zA-Z_]+') function = name & '(' >> expression << ')' - expression = longest(name, function) + expression = first(keyword, function, name) assert ExpressionParsers.expression.parse('f(x)') == Success(['f', 'x']) +assert str(ExpressionParsers.expression.parse('pi(x)').failure()) == ( + "Expected end of source but found '('\n" + "Line 1, character 3\n\n" + "pi(x)\n" + " ^ " +) +# Note how the above fails because `keyword` is matched by `first` so that +# `function`, which would have matched the input, was not tried. ``` -In a future version of Parsita, this will replace `first` as the implementation behind the `a | b | c` syntax. +In version 1 of Parsita, this was the implementation behind the `a | b | c` syntax. As of version 2, `longest` is used instead. ## `opt(parser)`: optional parser + An optional parser tries to match its argument. If the argument succeeds, it returns a list of length one with the successful value as its only element. If the argument fails, then `opt` succeeds anyway, but returns an empty list and consumes no input. ```python diff --git a/docs/miscellaneous_parsers.md b/docs/miscellaneous_parsers.md index 275d512..825a438 100644 --- a/docs/miscellaneous_parsers.md +++ b/docs/miscellaneous_parsers.md @@ -108,8 +108,9 @@ class HostnameParsers(TextParsers, whitespace=None): host = rep1sep(reg('[A-Za-z0-9]+([-]+[A-Za-z0-9]+)*'), '.') server = host << ':' & port -assert HostnameParsers.server.parse('drhagen.com:443') == \ - Failure('Expected no other port than 80 but found end of source') +assert str(HostnameParsers.server.parse('drhagen.com:443').failure()) == ( + 'Expected no other port than 80 but found end of source' +) ``` ## `debug(parser, *, verbose=False, callback=None)`: debug a parser diff --git a/src/parsita/parsers/__init__.py b/src/parsita/parsers/__init__.py index 1be60ca..cce412a 100644 --- a/src/parsita/parsers/__init__.py +++ b/src/parsita/parsers/__init__.py @@ -1,4 +1,4 @@ -from ._alternative import AlternativeParser, LongestAlternativeParser, first, longest +from ._alternative import FirstAlternativeParser, LongestAlternativeParser, first, longest from ._any import AnyParser, any1 from ._base import Parser, completely_parse_reader from ._conversion import ConversionParser, TransformationParser diff --git a/src/parsita/parsers/_alternative.py b/src/parsita/parsers/_alternative.py index d9f915d..dfab5a1 100644 --- a/src/parsita/parsers/_alternative.py +++ b/src/parsita/parsers/_alternative.py @@ -1,4 +1,4 @@ -__all__ = ["AlternativeParser", "first", "LongestAlternativeParser", "longest"] +__all__ = ["FirstAlternativeParser", "first", "LongestAlternativeParser", "longest"] from typing import Generic, Optional, Sequence, Union @@ -7,7 +7,7 @@ from ._base import Parser from ._literal import lit -class AlternativeParser(Generic[Input, Output], Parser[Input, Output]): +class FirstAlternativeParser(Generic[Input, Output], Parser[Input, Output]): def __init__(self, parser: Parser[Input, Output], *parsers: Parser[Input, Output]): super().__init__() self.parsers = (parser, *parsers) @@ -25,12 +25,12 @@ class AlternativeParser(Generic[Input, Output], Parser[Input, Output]): for parser in self.parsers: names.append(parser.name_or_repr()) - return self.name_or_nothing() + " | ".join(names) + return self.name_or_nothing() + f"first({', '.join(names)})" def first( parser: Union[Parser[Input, Output], Sequence[Input]], *parsers: Union[Parser[Input, Output], Sequence[Input]] -) -> AlternativeParser[Input, Output]: +) -> FirstAlternativeParser[Input, Output]: """Match the first of several alternative parsers. A ``AlternativeParser`` attempts to match each supplied parser. If a parser @@ -46,7 +46,7 @@ def first( *parsers: Non-empty list of ``Parser``s or literals to try """ cleaned_parsers = [lit(parser_i) if isinstance(parser_i, str) else parser_i for parser_i in [parser, *parsers]] - return AlternativeParser(*cleaned_parsers) + return FirstAlternativeParser(*cleaned_parsers) class LongestAlternativeParser(Generic[Input, Output], Parser[Input, Output]): @@ -69,7 +69,7 @@ class LongestAlternativeParser(Generic[Input, Output], Parser[Input, Output]): for parser in self.parsers: names.append(parser.name_or_repr()) - return self.name_or_nothing() + f"longest({', '.join(names)})" + return self.name_or_nothing() + " | ".join(names) def longest( diff --git a/src/parsita/parsers/_base.py b/src/parsita/parsers/_base.py index 4a20f36..740b666 100644 --- a/src/parsita/parsers/_base.py +++ b/src/parsita/parsers/_base.py @@ -149,19 +149,19 @@ class Parser(Generic[Input, Output]): return options.handle_literal(obj) def __or__(self, other) -> Parser: - from ._alternative import AlternativeParser + from ._alternative import LongestAlternativeParser other = self.handle_other(other) parsers: List[Parser] = [] - if isinstance(self, AlternativeParser) and not self.protected: + if isinstance(self, LongestAlternativeParser) and not self.protected: parsers.extend(self.parsers) else: parsers.append(self) - if isinstance(other, AlternativeParser) and not other.protected: + if isinstance(other, LongestAlternativeParser) and not other.protected: parsers.extend(other.parsers) else: parsers.append(other) - return AlternativeParser(*parsers) + return LongestAlternativeParser(*parsers) def __ror__(self, other) -> Parser: other = self.handle_other(other) diff --git a/src/parsita/parsers/_literal.py b/src/parsita/parsers/_literal.py index 0ccc8f2..34920d2 100644 --- a/src/parsita/parsers/_literal.py +++ b/src/parsita/parsers/_literal.py @@ -77,8 +77,8 @@ def lit(literal: Sequence[Input], *literals: Sequence[Input]) -> Parser[str, str arguments are provided. """ if len(literals) > 0: - from ._alternative import AlternativeParser + from ._alternative import LongestAlternativeParser - return AlternativeParser(options.handle_literal(literal), *map(options.handle_literal, literals)) + return LongestAlternativeParser(options.handle_literal(literal), *map(options.handle_literal, literals)) else: return options.handle_literal(literal)
drhagen/parsita
61bf389c6fe69e6f6fb90d9bea0cb06ad3fb35c5
diff --git a/tests/test_basic.py b/tests/test_basic.py index b06200e..0a30f62 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -10,9 +10,9 @@ from parsita import ( any1, eof, failure, + first, fwd, lit, - longest, opt, pred, rep, @@ -201,12 +201,12 @@ def test_multiple_messages_duplicate(): assert TestParsers.either.parse("cc") == Failure(ParseError(SequenceReader("cc", 0), ["a"])) -def test_longest(): +def test_first(): class TestParsers(GeneralParsers): a = lit("a") - either = longest(a, "b") + either = first(a, "b") - assert str(TestParsers.either) == "either = longest(a, 'b')" + assert str(TestParsers.either) == "either = first(a, 'b')" def test_sequential(): diff --git a/tests/test_regex.py b/tests/test_regex.py index 7b195ca..916d7d0 100644 --- a/tests/test_regex.py +++ b/tests/test_regex.py @@ -48,6 +48,13 @@ def test_literal_no_whitespace(): assert str(TestParsers.hundred) == "hundred = '100'" +def test_literal_multiple(): + class TestParsers(TextParsers): + keyword = lit("in", "int") + + assert TestParsers.keyword.parse("int") == Success("int") + + def test_interval(): class TestParsers(TextParsers): number = reg(r"\d+") > int @@ -121,6 +128,19 @@ def test_multiple_messages(): assert TestParsers.any.parse("func[var") == Failure(ParseError(StringReader("func[var", 8), ["']'"])) +def test_alternative_longest(): + class TestParsers(TextParsers): + name = reg("[a-z]+") + function = name & "(" >> name << ")" + index = name & "[" >> name << "]" + any = name | function | index + + assert TestParsers.any.parse("var(arg)") == Success(["var", "arg"]) + assert TestParsers.any.parse("func{var}") == Failure( + ParseError(StringReader("func{var}", 4), ["'('", "'['", "end of source"]) + ) + + def test_first_function(): class TestParsers(TextParsers): name = reg("[a-z]+") @@ -128,7 +148,9 @@ def test_first_function(): index = name & "[" >> name << "]" any = first(name, function, index) + assert TestParsers.any.parse("var") == Success("var") assert TestParsers.any.parse("var(arg)") == Failure(ParseError(StringReader("var(arg)", 3), ["end of source"])) + assert TestParsers.any.parse("") == Failure(ParseError(StringReader("", 0), ["r'[a-z]+'"])) def test_longest_function():
Make `longest` the default alternative parser `longest` was added in #21. It was always intended that it would replace `first` as the behavior of `parser | parser` in version 2.0. Well, version 2.0 is here, so it is time.
0.0
61bf389c6fe69e6f6fb90d9bea0cb06ad3fb35c5
[ "tests/test_basic.py::test_first", "tests/test_regex.py::test_literal_multiple", "tests/test_regex.py::test_alternative_longest" ]
[ "tests/test_basic.py::test_literals", "tests/test_basic.py::test_multiple_literals", "tests/test_basic.py::test_predicate", "tests/test_basic.py::test_forward_declaration", "tests/test_basic.py::test_forward_expression", "tests/test_basic.py::test_manual_forward", "tests/test_basic.py::test_manual_forward_mutual", "tests/test_basic.py::test_multiple_references", "tests/test_basic.py::test_optional", "tests/test_basic.py::test_optional_longer", "tests/test_basic.py::test_optional_literal", "tests/test_basic.py::test_alternative", "tests/test_basic.py::test_multiple", "tests/test_basic.py::test_right_or", "tests/test_basic.py::test_multiple_messages_duplicate", "tests/test_basic.py::test_sequential", "tests/test_basic.py::test_discard_left", "tests/test_basic.py::test_discard_right", "tests/test_basic.py::test_discard_bare_literals", "tests/test_basic.py::test_repeated", "tests/test_basic.py::test_repeated_with_bounds", "tests/test_basic.py::test_repeated_longer", "tests/test_basic.py::test_repeated_separated", "tests/test_basic.py::test_repeated_separated_nonliteral", "tests/test_basic.py::test_repeated_separated_with_bounds", "tests/test_basic.py::test_infinite_recursion_protection", "tests/test_basic.py::test_conversion", "tests/test_basic.py::test_recursion", "tests/test_basic.py::test_protection", "tests/test_basic.py::test_eof_protection", "tests/test_basic.py::test_success_failure_protection", "tests/test_basic.py::test_until_parser", "tests/test_basic.py::test_any", "tests/test_basic.py::test_nested_class", "tests/test_basic.py::test_disallow_instatiation", "tests/test_regex.py::test_literal", "tests/test_regex.py::test_literal_no_whitespace", "tests/test_regex.py::test_interval", "tests/test_regex.py::test_regex", "tests/test_regex.py::test_regex_no_whitespace", "tests/test_regex.py::test_regex_custom_whitespace", "tests/test_regex.py::test_optional", "tests/test_regex.py::test_multiple_messages", "tests/test_regex.py::test_first_function", "tests/test_regex.py::test_longest_function", "tests/test_regex.py::test_longest_function_shortest_later", "tests/test_regex.py::test_longest_function_all_failures", "tests/test_regex.py::test_sequential", "tests/test_regex.py::test_multiline", "tests/test_regex.py::test_repeated", "tests/test_regex.py::test_transformation_as_fallible_conversion", "tests/test_regex.py::test_transformation_as_parameterized_parser", "tests/test_regex.py::test_transformation_error_propogation", "tests/test_regex.py::test_debug_callback", "tests/test_regex.py::test_debug_verbose", "tests/test_regex.py::test_until_parser", "tests/test_regex.py::test_heredoc", "tests/test_regex.py::test_recursion_literals", "tests/test_regex.py::test_recursion_regex", "tests/test_regex.py::test_infinite_recursion_protection", "tests/test_regex.py::test_protection", "tests/test_regex.py::test_failures_with_duplicate_tokens", "tests/test_regex.py::test_nested_class", "tests/test_regex.py::test_general_in_regex" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-15 02:04:43+00:00
mit
2,000
dropbox__pyannotate-26
diff --git a/pyannotate_tools/annotations/__main__.py b/pyannotate_tools/annotations/__main__.py index 709fafa..f1c8190 100644 --- a/pyannotate_tools/annotations/__main__.py +++ b/pyannotate_tools/annotations/__main__.py @@ -42,7 +42,7 @@ def main(): # Run pass 2 with output written to a temporary file. infile = args.type_info - generate_annotations_json(infile, tf.name) + generate_annotations_json(infile, tf.name, target_stream=tf) # Run pass 3 reading from a temporary file. FixAnnotateJson.stub_json_file = tf.name diff --git a/pyannotate_tools/annotations/main.py b/pyannotate_tools/annotations/main.py index 123fa0c..aea22c2 100644 --- a/pyannotate_tools/annotations/main.py +++ b/pyannotate_tools/annotations/main.py @@ -2,7 +2,7 @@ import json -from typing import List +from typing import List, Optional, IO from mypy_extensions import TypedDict from pyannotate_tools.annotations.types import ARG_STAR, ARG_STARSTAR @@ -22,8 +22,8 @@ FunctionData = TypedDict('FunctionData', {'path': str, 'samples': int}) -def generate_annotations_json(source_path, target_path): - # type: (str, str) -> None +def generate_annotations_json(source_path, target_path, source_stream=None, target_stream=None): + # type: (str, str, Optional[IO[str]], Optional[IO[str]]) -> None """Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: @@ -31,7 +31,7 @@ def generate_annotations_json(source_path, target_path): * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The output JSON is a list of FunctionData items. """ - items = parse_json(source_path) + items = parse_json(source_path, source_stream) results = [] for item in items: arg_types, return_type = infer_annotation(item.type_comments) @@ -55,5 +55,8 @@ def generate_annotations_json(source_path, target_path): 'samples': item.samples } # type: FunctionData results.append(data) - with open(target_path, 'w') as f: - json.dump(results, f, sort_keys=True, indent=4) + if target_stream: + json.dump(results, target_stream, sort_keys=True, indent=4) + else: + with open(target_path, 'w') as f: + json.dump(results, f, sort_keys=True, indent=4) diff --git a/pyannotate_tools/annotations/parse.py b/pyannotate_tools/annotations/parse.py index 28a7851..bc9d3c1 100644 --- a/pyannotate_tools/annotations/parse.py +++ b/pyannotate_tools/annotations/parse.py @@ -9,7 +9,7 @@ import json import re import sys -from typing import Any, List, Mapping, Set, Tuple +from typing import Any, List, Mapping, Set, Tuple, Optional, IO from typing_extensions import Text from mypy_extensions import NoReturn, TypedDict @@ -86,14 +86,17 @@ class ParseError(Exception): self.comment = comment -def parse_json(path): - # type: (str) -> List[FunctionInfo] +def parse_json(path, stream=None): + # type: (str, Optional[IO[str]]) -> List[FunctionInfo] """Deserialize a JSON file containing runtime collected types. The input JSON is expected to to have a list of RawEntry items. """ - with open(path) as f: - data = json.load(f) # type: List[RawEntry] + if stream: + data = json.load(stream) # type: List[RawEntry] + else: + with open(path) as f: + data = json.load(f) result = [] def assert_type(value, typ):
dropbox/pyannotate
ba80fabf4d9bb9888e8b46bbd47affc5766470f8
diff --git a/pyannotate_tools/annotations/tests/main_test.py b/pyannotate_tools/annotations/tests/main_test.py index 9609a7d..6c27a20 100644 --- a/pyannotate_tools/annotations/tests/main_test.py +++ b/pyannotate_tools/annotations/tests/main_test.py @@ -3,7 +3,7 @@ import tempfile import textwrap import unittest -from typing import Iterator +from typing import Iterator, Tuple, IO from pyannotate_tools.annotations.infer import InferError from pyannotate_tools.annotations.main import generate_annotations_json @@ -25,10 +25,12 @@ class TestMain(unittest.TestCase): } ] """ - target = tempfile.NamedTemporaryFile(mode='r') - with self.temporary_json_file(data) as source_path: - generate_annotations_json(source_path, target.name) + target = tempfile.NamedTemporaryFile(mode='w+') + with self.temporary_json_file(data) as source: + generate_annotations_json(source.name, target.name, source_stream=source, target_stream=target) + target.flush() + target.seek(0) actual = target.read() actual = actual.replace(' \n', '\n') expected = textwrap.dedent("""\ @@ -66,8 +68,8 @@ class TestMain(unittest.TestCase): ] """ with self.assertRaises(InferError) as e: - with self.temporary_json_file(data) as source_path: - generate_annotations_json(source_path, '/dummy') + with self.temporary_json_file(data) as source: + generate_annotations_json(source.name, '/dummy', source_stream=source) assert str(e.exception) == textwrap.dedent("""\ Ambiguous argument kinds: (List[int], str) -> None @@ -75,8 +77,9 @@ class TestMain(unittest.TestCase): @contextlib.contextmanager def temporary_json_file(self, data): - # type: (str) -> Iterator[str] - with tempfile.NamedTemporaryFile(mode='w') as source: + # type: (str) -> Iterator[IO[str]] + with tempfile.NamedTemporaryFile(mode='w+') as source: source.write(data) source.flush() - yield source.name + source.seek(0) + yield source diff --git a/pyannotate_tools/annotations/tests/parse_test.py b/pyannotate_tools/annotations/tests/parse_test.py index c0daeb2..78650fb 100644 --- a/pyannotate_tools/annotations/tests/parse_test.py +++ b/pyannotate_tools/annotations/tests/parse_test.py @@ -40,11 +40,12 @@ class TestParseJson(unittest.TestCase): } ] """ - with tempfile.NamedTemporaryFile(mode='w') as f: + with tempfile.NamedTemporaryFile(mode='w+') as f: f.write(data) f.flush() + f.seek(0) - result = parse_json(f.name) + result = parse_json(f.name, f) assert len(result) == 1 item = result[0] assert item.path == 'pkg/thing.py'
Permission denied for Temp file on Windows When I run "pyannotate --type-info ./annotate.json ." with on Windows (both 2.7.14 and 3.6.3, probably others) , I get the following error: Traceback (most recent call last): File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\Scripts\pyannotate.exe\__main__.py", line 9, in <module> File "c:\python27\lib\site-packages\pyannotate_tools\annotations\__main__.py", line 45, in main generate_annotations_json(infile, tf.name) File "c:\python27\lib\site-packages\pyannotate_tools\annotations\main.py", line 58, in generate_annotations_json with open(target_path, 'w') as f: IOError: [Errno 13] Permission denied: 'c:\\temp\\tmp2ui1ku' A little bit of googling suggests this might be the problem [Permission Denied To Write To My Temporary File](https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file)
0.0
ba80fabf4d9bb9888e8b46bbd47affc5766470f8
[ "pyannotate_tools/annotations/tests/main_test.py::TestMain::test_ambiguous_kind", "pyannotate_tools/annotations/tests/main_test.py::TestMain::test_generation", "pyannotate_tools/annotations/tests/parse_test.py::TestParseJson::test_parse_json" ]
[ "pyannotate_tools/annotations/tests/parse_test.py::TestParseError::test_str_conversion", "pyannotate_tools/annotations/tests/parse_test.py::TestTokenize::test_special_cases", "pyannotate_tools/annotations/tests/parse_test.py::TestTokenize::test_tokenize", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_any_and_unknown", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_bad_annotation", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_empty", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_function", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_generic", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_optional", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_simple_args", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_star_args", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_star_star_args", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_tuple", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_unicode", "pyannotate_tools/annotations/tests/parse_test.py::TestParseTypeComment::test_union" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2017-11-21 09:56:07+00:00
apache-2.0
2,001
dropbox__pyannotate-64
diff --git a/pyannotate_runtime/collect_types.py b/pyannotate_runtime/collect_types.py index ca88866..72d5bbf 100644 --- a/pyannotate_runtime/collect_types.py +++ b/pyannotate_runtime/collect_types.py @@ -41,11 +41,13 @@ from typing import ( Any, Callable, Dict, + Iterable, Iterator, List, NamedTuple, Optional, Set, + Sized, Tuple, TypeVar, Union, @@ -54,6 +56,8 @@ from contextlib import contextmanager # pylint: disable=invalid-name +CO_GENERATOR = inspect.CO_GENERATOR # type: ignore + def _my_hash(arg_list): # type: (List[Any]) -> int @@ -84,8 +88,30 @@ class TypeWasIncomparable(object): pass +class FakeIterator(Iterable[Any], Sized): + """ + Container for iterator values. + + Note that FakeIterator([a, b, c]) is akin to list([a, b, c]); this + is turned into IteratorType by resolve_type(). + """ + + def __init__(self, values): + # type: (List[Any]) -> None + self.values = values + + def __iter__(self): + # type: () -> Iterator[Any] + for v in self.values: + yield v + + def __len__(self): + # type: () -> int + return len(self.values) + + _NONE_TYPE = type(None) -InternalType = Union['DictType', 'ListType', 'TupleType', 'SetType', 'type'] +InternalType = Union['DictType', 'ListType', 'TupleType', 'SetType', 'IteratorType', 'type'] class DictType(object): @@ -188,6 +214,39 @@ class SetType(object): return not self.__eq__(other) +class IteratorType(object): + """ + Internal representation of Iterator type. + """ + + def __init__(self, val_type): + # type: (TentativeType) -> None + self.val_type = val_type + + def __repr__(self): + # type: () -> str + if repr(self.val_type) == 'None': + # We didn't see any values, so we don't know what's inside + return 'Iterator' + else: + return 'Iterator[%s]' % (repr(self.val_type)) + + def __hash__(self): + # type: () -> int + return hash(self.val_type) if self.val_type else 0 + + def __eq__(self, other): + # type: (object) -> bool + if not isinstance(other, IteratorType): + return False + + return self.val_type == other.val_type + + def __ne__(self, other): + # type: (object) -> bool + return not self.__eq__(other) + + class TupleType(object): """ Internal representation of Tuple type. @@ -279,6 +338,9 @@ class TentativeType(object): elif isinstance(type, ListType): if EMPTY_LIST_TYPE in self.types_hashable: self.types_hashable.remove(EMPTY_LIST_TYPE) + elif isinstance(type, IteratorType): + if EMPTY_ITERATOR_TYPE in self.types_hashable: + self.types_hashable.remove(EMPTY_ITERATOR_TYPE) elif isinstance(type, DictType): if EMPTY_DICT_TYPE in self.types_hashable: self.types_hashable.remove(EMPTY_DICT_TYPE) @@ -350,7 +412,7 @@ def name_from_type(type_): """ Helper function to get PEP-484 compatible string representation of our internal types. """ - if isinstance(type_, (DictType, ListType, TupleType, SetType)): + if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)): return repr(type_) else: if type_.__name__ != 'NoneType': @@ -369,6 +431,7 @@ def name_from_type(type_): EMPTY_DICT_TYPE = DictType(TentativeType(), TentativeType()) EMPTY_LIST_TYPE = ListType(TentativeType()) EMPTY_SET_TYPE = SetType(TentativeType()) +EMPTY_ITERATOR_TYPE = IteratorType(TentativeType()) # TODO: Make this faster @@ -450,6 +513,16 @@ def resolve_type(arg): for sample_item in sample: tentative_type.add(resolve_type(sample_item)) return SetType(tentative_type) + elif arg_type == FakeIterator: + assert isinstance(arg, FakeIterator) # this line helps mypy figure out types + sample = [] + iterator = iter(arg) + for i in range(0, min(4, len(arg))): + sample.append(next(iterator)) + tentative_type = TentativeType() + for sample_item in sample: + tentative_type.add(resolve_type(sample_item)) + return IteratorType(tentative_type) elif arg_type == tuple: assert isinstance(arg, tuple) # this line helps mypy figure out types sample = list(arg[:min(10, len(arg))]) @@ -715,8 +788,10 @@ _filter_filename = default_filter_filename # type: Callable[[Optional[str]], Op if sys.version_info[0] == 2: RETURN_VALUE_OPCODE = chr(opcode.opmap['RETURN_VALUE']) + YIELD_VALUE_OPCODE = chr(opcode.opmap['YIELD_VALUE']) else: RETURN_VALUE_OPCODE = opcode.opmap['RETURN_VALUE'] + YIELD_VALUE_OPCODE = opcode.opmap['YIELD_VALUE'] def _trace_dispatch(frame, event, arg): @@ -777,14 +852,29 @@ def _trace_dispatch(frame, event, arg): resolved_types = prep_args(arg_info) _task_queue.put(KeyAndTypes(function_key, resolved_types)) elif event == 'return': - # This event is also triggered if a function raises an exception. + # This event is also triggered if a function yields or raises an exception. # We can tell the difference by looking at the bytecode. # (We don't get here for C functions so the bytecode always exists.) - # TODO: Also recognize YIELD_VALUE opcode. last_opcode = code.co_code[frame.f_lasti] - if last_opcode != RETURN_VALUE_OPCODE: - arg = NoReturnType() - _task_queue.put(KeyAndReturn(function_key, resolve_type(arg))) + if last_opcode == RETURN_VALUE_OPCODE: + if code.co_flags & CO_GENERATOR: + # Return from a generator. + t = resolve_type(FakeIterator([])) + else: + t = resolve_type(arg) + elif last_opcode == YIELD_VALUE_OPCODE: + # Yield from a generator. + # TODO: Unify generators -- currently each YIELD is turned into + # a separate call, so a function yielding ints and strs will be + # typed as Union[Iterator[int], Iterator[str]] -- this should be + # Iterator[Union[int, str]]. + t = resolve_type(FakeIterator([arg])) + else: + # This branch is also taken when returning from a generator. + # TODO: returning non-trivial values from generators, per PEP 380; + # and async def / await stuff. + t = NoReturnType + _task_queue.put(KeyAndReturn(function_key, t)) else: sampling_counters[key] = None # We're not interested in this function.
dropbox/pyannotate
b02080a3b340f5b5aa464007510e211ecd0529a3
diff --git a/pyannotate_runtime/tests/test_collect_types.py b/pyannotate_runtime/tests/test_collect_types.py index 06ca1b2..9d98085 100644 --- a/pyannotate_runtime/tests/test_collect_types.py +++ b/pyannotate_runtime/tests/test_collect_types.py @@ -594,6 +594,43 @@ class TestCollectTypes(TestBaseClass): self.assert_type_comments('func_with_unknown_module_types', ['(C) -> C']) + def test_yield_basic(self): + # type: () -> None + def gen(n, a): + for i in range(n): + yield a + + with self.collecting_types(): + list(gen(10, 'x')) + + self.assert_type_comments('gen', ['(int, str) -> Iterator[str]']) + + def test_yield_various(self): + # type: () -> None + def gen(n, a, b): + for i in range(n): + yield a + yield b + + with self.collecting_types(): + list(gen(10, 'x', 1)) + list(gen(0, 0, 0)) + + # TODO: This should really return Iterator[Union[int, str]] + self.assert_type_comments('gen', ['(int, str, int) -> Iterator[int]', + '(int, str, int) -> Iterator[str]']) + + def test_yield_empty(self): + # type: () -> None + def gen(): + if False: + yield + + with self.collecting_types(): + list(gen()) + + self.assert_type_comments('gen', ['() -> Iterator']) + def foo(arg): # type: (Any) -> Any
Detect yield and return opcodes There are some [hacks in MonkeyType](https://github.com/Instagram/MonkeyType/blob/0119311745449560e30ef554ba449a99c1b6679d/monkeytype/tracing.py#L226) that detect yield and return opcodes -- the former to generate Generator/Iterator return annotations, the latter to distinguish between return and exceptions.
0.0
b02080a3b340f5b5aa464007510e211ecd0529a3
[ "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_yield_basic", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_yield_empty", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_yield_various" ]
[ "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_callee_star_args", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_caller_star_args", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_default_args", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_fully_qualified_type_name_with_sub_package", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_ignoring_c_calls", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_keyword_args", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_many_signatures", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_no_crash_on_nested_dict_comps", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_no_return", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_only_return", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_recursive_function", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_recursive_function_2", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_run_a_bunch_of_tests", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_skip_lambda", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_star_star_args", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_two_signatures", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_type_collection_on_another_thread", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_type_collection_on_main_thread", "pyannotate_runtime/tests/test_collect_types.py::TestCollectTypes::test_unknown_module_types", "pyannotate_runtime/tests/test_collect_types.py::TestInitWithFilter::test_init_with_filter", "pyannotate_runtime/tests/test_collect_types.py::TestInitWithFilter::test_init_with_none_filter" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-02-07 22:58:52+00:00
apache-2.0
2,002
dropbox__pyannotate-83
diff --git a/pyannotate_tools/fixes/fix_annotate_json.py b/pyannotate_tools/fixes/fix_annotate_json.py index 5d2c9cd..3fed7f2 100644 --- a/pyannotate_tools/fixes/fix_annotate_json.py +++ b/pyannotate_tools/fixes/fix_annotate_json.py @@ -202,10 +202,12 @@ class FixAnnotateJson(FixAnnotate): self.init_stub_json() data = self.__class__.stub_json # We are using relative paths in the JSON. - items = [it for it in data - if it['func_name'] == funcname and - (os.path.join(self.__class__.top_dir, it['path']) == - os.path.abspath(self.filename))] + items = [ + it for it in data + if it['func_name'] == funcname and + (it['path'] == self.filename or + os.path.join(self.__class__.top_dir, it['path']) == os.path.abspath(self.filename)) + ] if len(items) > 1: # this can happen, because of # 1) nested functions
dropbox/pyannotate
40edbfeed62a78cd683cd3eb56a7412ae40dd124
diff --git a/tests/integration_test.py b/tests/integration_test.py index e672dab..033cbf6 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -88,7 +88,6 @@ class IntegrationTest(unittest.TestCase): assert b'+ # type: () -> None' in lines assert b'+ # type: (int, int) -> int' in lines - @unittest.skip("Doesn't work yet") def test_subdir(self): os.makedirs('foo') with open('foo/gcd.py', 'w') as f: @@ -99,7 +98,9 @@ class IntegrationTest(unittest.TestCase): f.write('from gcd import main\n') f.write(driver) subprocess.check_call([sys.executable, 'driver.py']) - output = subprocess.check_output([sys.executable, '-m', 'pyannotate_tools.annotations', 'foo/gcd.py']) + output = subprocess.check_output([sys.executable, '-m', 'pyannotate_tools.annotations', + # Construct platform-correct pathname: + os.path.join('foo', 'gcd.py')]) lines = output.splitlines() assert b'+ # type: () -> None' in lines assert b'+ # type: (int, int) -> int' in lines
Fail to apply typeinfo to a python module in a subdirectory The following will fail : ``` > python toto\toto.py ( this generates a type_info.json in current directory ) ``` ``` >dir [...] 25/07/2018 06:22 <DIR> toto 25/07/2018 06:21 784 type_info.json ``` ``` >pyannotate -3 toto\toto.py --type-info type_info.json No files need to be modified. NOTE: this was a dry run; use -w to write files ``` strange, there are type annotations in type_info.json with the correct path ``` >type type_info.json [ { "path": "toto\\toto.py", "line": 2, "func_name": "add", "type_comments": [ "(*int) -> int", "(*List[int]) -> List[int]", "(*Tuple[int, int]) -> Tuple[int, int]" ], "samples": 3 }, { "path": "toto\\toto.py", "line": 8, "func_name": "add2", "type_comments": [ "(Tuple[int, int], Tuple[int, int]) -> Tuple[int, int, int, int]", "(List[int], List[int]) -> List[int]", "(int, int) -> int" ], "samples": 3 }, { "path": "toto\\toto.py", "line": 11, "func_name": "main", "type_comments": [ "() -> None" ], "samples": 1 } ] ``` edit the type_info.json to remove the "toto\\" ``` >type type_info.json [ { "path": "toto.py", "line": 2, "func_name": "add", "type_comments": [ "(*int) -> int", "(*List[int]) -> List[int]", "(*Tuple[int, int]) -> Tuple[int, int]" ], "samples": 3 }, { "path": "toto.py", "line": 8, "func_name": "add2", "type_comments": [ "(Tuple[int, int], Tuple[int, int]) -> Tuple[int, int, int, int]", "(List[int], List[int]) -> List[int]", "(int, int) -> int" ], "samples": 3 }, { "path": "toto.py", "line": 11, "func_name": "main", "type_comments": [ "() -> None" ], "samples": 1 } ] ``` try again ``` >pyannotate -3 toto\toto.py --type-info type_info.json Refactored toto\toto.py --- toto\toto.py (original) +++ toto\toto.py (refactored) @@ -1,14 +1,18 @@ +from typing import Any +from typing import List +from typing import Tuple +from typing import Union -def add(*args): +def add(*args: Any) -> Union[List[int], Tuple[int, int], int]: ret = args[0] for v in args: ret += v return v -def add2(v1, v2): +def add2(v1: Union[List[int], Tuple[int, int], int], v2: Union[List[int], Tuple[int, int], int]) -> Union[List[int], Tuple[int, int, int, int], int]: return v1+v2 -def main(): +def main() -> None: print( add(1,2,3) ) print( add([1,2], [3,4]) ) print( add((1,2), (3,4)) ) Files that need to be modified: toto\toto.py NOTE: this was a dry run; use -w to write files ``` it worked... It looks like pyannotate is trimming directories from type_info.json too agressively.
0.0
40edbfeed62a78cd683cd3eb56a7412ae40dd124
[ "tests/integration_test.py::IntegrationTest::test_subdir" ]
[ "tests/integration_test.py::IntegrationTest::test_auto_any", "tests/integration_test.py::IntegrationTest::test_no_type_info", "tests/integration_test.py::IntegrationTest::test_package", "tests/integration_test.py::IntegrationTest::test_simple" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-04-06 00:55:21+00:00
apache-2.0
2,003
dropbox__stone-117
diff --git a/stone/backends/python_helpers.py b/stone/backends/python_helpers.py index a3c4385..fa58f91 100644 --- a/stone/backends/python_helpers.py +++ b/stone/backends/python_helpers.py @@ -37,12 +37,12 @@ _type_table = { Float32: 'float', Float64: 'float', Int32: 'int', - Int64: 'long', + Int64: 'int', List: 'list', String: 'str', Timestamp: 'datetime', - UInt32: 'long', - UInt64: 'long', + UInt32: 'int', + UInt64: 'int', } _reserved_keywords = { diff --git a/stone/backends/python_type_mapping.py b/stone/backends/python_type_mapping.py index d28fae0..10b6358 100644 --- a/stone/backends/python_type_mapping.py +++ b/stone/backends/python_type_mapping.py @@ -60,7 +60,7 @@ def map_stone_type_to_python_type(ns, data_type, override_dict=None): elif is_float_type(data_type): return 'float' elif is_integer_type(data_type): - return 'long' + return 'int' elif is_void_type(data_type): return 'None' elif is_timestamp_type(data_type):
dropbox/stone
1a5cb6d9eab6383dccd12678c3b8723e2a9317d5
diff --git a/test/test_python_type_stubs.py b/test/test_python_type_stubs.py index 2e6e42e..ec85dea 100644 --- a/test/test_python_type_stubs.py +++ b/test/test_python_type_stubs.py @@ -276,15 +276,15 @@ class TestPythonTypeStubs(unittest.TestCase): class Struct2(object): def __init__(self, - f2: List[long] = ..., + f2: List[int] = ..., f3: datetime.datetime = ..., - f4: Dict[Text, long] = ...) -> None: ... + f4: Dict[Text, int] = ...) -> None: ... @property - def f2(self) -> List[long]: ... + def f2(self) -> List[int]: ... @f2.setter - def f2(self, val: List[long]) -> None: ... + def f2(self, val: List[int]) -> None: ... @f2.deleter def f2(self) -> None: ... @@ -301,10 +301,10 @@ class TestPythonTypeStubs(unittest.TestCase): @property - def f4(self) -> Dict[Text, long]: ... + def f4(self) -> Dict[Text, int]: ... @f4.setter - def f4(self, val: Dict[Text, long]) -> None: ... + def f4(self, val: Dict[Text, int]) -> None: ... @f4.deleter def f4(self) -> None: ... @@ -340,24 +340,24 @@ class TestPythonTypeStubs(unittest.TestCase): class NestedTypes(object): def __init__(self, - list_of_nullables: List[Optional[long]] = ..., - nullable_list: Optional[List[long]] = ...) -> None: ... + list_of_nullables: List[Optional[int]] = ..., + nullable_list: Optional[List[int]] = ...) -> None: ... @property - def list_of_nullables(self) -> List[Optional[long]]: ... + def list_of_nullables(self) -> List[Optional[int]]: ... @list_of_nullables.setter - def list_of_nullables(self, val: List[Optional[long]]) -> None: ... + def list_of_nullables(self, val: List[Optional[int]]) -> None: ... @list_of_nullables.deleter def list_of_nullables(self) -> None: ... @property - def nullable_list(self) -> Optional[List[long]]: ... + def nullable_list(self) -> Optional[List[int]]: ... @nullable_list.setter - def nullable_list(self, val: Optional[List[long]]) -> None: ... + def nullable_list(self, val: Optional[List[int]]) -> None: ... @nullable_list.deleter def nullable_list(self) -> None: ... diff --git a/test/test_python_types.py b/test/test_python_types.py index 0f84f49..5c00cc2 100644 --- a/test/test_python_types.py +++ b/test/test_python_types.py @@ -165,7 +165,7 @@ class TestGeneratedPythonTypes(unittest.TestCase): @property def annotated_field(self): """ - :rtype: long + :rtype: int """ if self._annotated_field_present: return self._annotated_field_value @@ -186,7 +186,7 @@ class TestGeneratedPythonTypes(unittest.TestCase): @property def unannotated_field(self): """ - :rtype: long + :rtype: int """ if self._unannotated_field_present: return self._unannotated_field_value @@ -268,14 +268,14 @@ class TestGeneratedPythonTypes(unittest.TestCase): """ test parameter - :rtype: long + :rtype: int """ return self._test_param @property def test_default_param(self): """ - :rtype: long + :rtype: int """ return self._test_default_param
Generated .pyi files reference 'long', which is not Python 3 compatible I can think of two ways to fix this: 1. The easy way: replace `'long'` with `'int'` [here](https://github.com/dropbox/stone/blob/master/stone/backends/python_type_mapping.py#L63) 2. Do something with the override_dict A potential problem for (1) would be that it will not only change the generated .pyi files but also the generated .py files. I do think that even in Python 2 the distinction between int and long is rarely useful though, so perhaps this is acceptable. The problem with (2) is that it's a lot more code, since the architecture for the override_dict doesn't really map cleanly to the way is_integer_type() is used. (In order to allow separate mappings for Int32, UIint32, Int64 and UInt64, we'd need 4 isinstance checks.)
0.0
1a5cb6d9eab6383dccd12678c3b8723e2a9317d5
[ "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_many_structs", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_nested_types", "test/test_python_types.py::TestGeneratedPythonTypes::test_annotation_type_class", "test/test_python_types.py::TestGeneratedPythonTypes::test_struct_with_custom_annotations" ]
[ "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_alias", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_empty_union", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_union__generates_stuff", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_routes", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_routes_name_conflict", "test/test_python_types.py::TestGeneratedPythonTypes::test_route_with_version_number", "test/test_python_types.py::TestGeneratedPythonTypes::test_route_with_version_number_name_conflict" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-10-15 20:44:41+00:00
mit
2,004
dropbox__stone-131
diff --git a/stone/backends/python_type_stubs.py b/stone/backends/python_type_stubs.py index f29058b..6f38967 100644 --- a/stone/backends/python_type_stubs.py +++ b/stone/backends/python_type_stubs.py @@ -363,12 +363,7 @@ class PythonTypeStubsBackend(CodeBackend): for field in struct.all_fields: field_name_reserved_check = fmt_func(field.name, check_reserved=True) setter_field_type = self.map_stone_type_to_pep484_type(ns, field.data_type) - - # The field might not have been set since it is optional in the constructor. getter_field_type = setter_field_type - if not is_nullable_type(field.data_type) and not is_void_type(field.data_type): - self.import_tracker._register_typing_import('Optional') - getter_field_type = 'Optional[{}]'.format(setter_field_type) to_emit.extend( self.property_template.format(
dropbox/stone
e695746e0836dd54d942d6b8a9271d2d3fd8a429
diff --git a/test/test_python_client.py b/test/test_python_client.py index a706112..41a020b 100644 --- a/test/test_python_client.py +++ b/test/test_python_client.py @@ -162,7 +162,7 @@ class TestGeneratedPythonClient(unittest.TestCase): self.assertEqual(result, expected) def test_route_with_auth_mode3(self): - # type: () -> None + # type: () -> None route1 = ApiRoute('get_metadata', 1, None) route1.set_attributes(None, ':route:`get_metadata:2`', Void(), Void(), Void(), diff --git a/test/test_python_type_stubs.py b/test/test_python_type_stubs.py index 82d5af7..57525e6 100644 --- a/test/test_python_type_stubs.py +++ b/test/test_python_type_stubs.py @@ -258,7 +258,7 @@ class TestPythonTypeStubs(unittest.TestCase): f1: Optional[bool] = ...) -> None: ... @property - def f1(self) -> Optional[bool]: ... + def f1(self) -> bool: ... @f1.setter def f1(self, val: bool) -> None: ... @@ -281,7 +281,7 @@ class TestPythonTypeStubs(unittest.TestCase): f4: Optional[Dict[Text, int]] = ...) -> None: ... @property - def f2(self) -> Optional[List[int]]: ... + def f2(self) -> List[int]: ... @f2.setter def f2(self, val: List[int]) -> None: ... @@ -291,7 +291,7 @@ class TestPythonTypeStubs(unittest.TestCase): @property - def f3(self) -> Optional[datetime.datetime]: ... + def f3(self) -> datetime.datetime: ... @f3.setter def f3(self, val: datetime.datetime) -> None: ... @@ -301,7 +301,7 @@ class TestPythonTypeStubs(unittest.TestCase): @property - def f4(self) -> Optional[Dict[Text, int]]: ... + def f4(self) -> Dict[Text, int]: ... @f4.setter def f4(self, val: Dict[Text, int]) -> None: ... @@ -345,7 +345,7 @@ class TestPythonTypeStubs(unittest.TestCase): nullable_list: Optional[List[int]] = ...) -> None: ... @property - def list_of_nullables(self) -> Optional[List[Optional[int]]]: ... + def list_of_nullables(self) -> List[Optional[int]]: ... @list_of_nullables.setter def list_of_nullables(self, val: List[Optional[int]]) -> None: ... @@ -498,7 +498,7 @@ class TestPythonTypeStubs(unittest.TestCase): f1: Optional[bool] = ...) -> None: ... @property - def f1(self) -> Optional[bool]: ... + def f1(self) -> bool: ... @f1.setter def f1(self, val: bool) -> None: ...
Properties are not always optional Hey Stone team! We found an issue with the typing stub code generated for properties. I believe this block of code should be deleted: https://github.com/dropbox/stone/blob/e695746e0836dd54d942d6b8a9271d2d3fd8a429/stone/backends/python_type_stubs.py#L369-L371 The effect of this block is to always add `Optional[]` around the return type of a property getter. (The logic looks backwards, but for nullable and void types there *already* is an `Optional[]`.) But if you look at the runtime code generated, you'll see that for a non-nullable default-less property, `None` is never returned, it raises an exception if the value isn't set: https://github.com/dropbox/stone/blob/e695746e0836dd54d942d6b8a9271d2d3fd8a429/stone/backends/python_types.py#L625-L634 I will propose a PR to fix this. I have tested the PR in the Dropbox server repo, and it caused only two errors, and those look genuine. CC: @ilevkivskyi
0.0
e695746e0836dd54d942d6b8a9271d2d3fd8a429
[ "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_alias", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_many_structs", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_nested_types" ]
[ "test/test_python_client.py::TestGeneratedPythonClient::test_route_with_auth_mode1", "test/test_python_client.py::TestGeneratedPythonClient::test_route_with_auth_mode2", "test/test_python_client.py::TestGeneratedPythonClient::test_route_with_auth_mode3", "test/test_python_client.py::TestGeneratedPythonClient::test_route_with_version_number", "test/test_python_client.py::TestGeneratedPythonClient::test_route_with_version_number_name_conflict", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_empty_union", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_union__generates_stuff", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_routes", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_routes_name_conflict" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-03-08 19:18:54+00:00
mit
2,005
dropbox__stone-72
diff --git a/stone/backends/python_type_stubs.py b/stone/backends/python_type_stubs.py index 6a0c6f0..c087c79 100644 --- a/stone/backends/python_type_stubs.py +++ b/stone/backends/python_type_stubs.py @@ -45,6 +45,7 @@ def emit_pass_if_nothing_emitted(codegen): ending_lineno = codegen.lineno if starting_lineno == ending_lineno: codegen.emit("pass") + codegen.emit() class ImportTracker(object): def __init__(self): @@ -135,6 +136,7 @@ class PythonTypeStubsBackend(CodeBackend): for alias in namespace.linearize_aliases(): self._generate_alias_definition(namespace, alias) + self._generate_routes(namespace) self._generate_imports_needed_for_typing() def _generate_imports_for_referenced_namespaces(self, namespace): @@ -152,8 +154,17 @@ class PythonTypeStubsBackend(CodeBackend): with self.indent(): self._generate_struct_class_init(ns, data_type) self._generate_struct_class_properties(ns, data_type) + + self._generate_validator_for(data_type) self.emit() + def _generate_validator_for(self, data_type): + # type: (DataType) -> None + cls_name = class_name_for_data_type(data_type) + self.emit("{}_validator = ... # type: stone_validators.Validator".format( + cls_name + )) + def _generate_union_class(self, ns, data_type): # type: (ApiNamespace, Union) -> None self.emit(self._class_declaration_for_type(ns, data_type)) @@ -162,6 +173,8 @@ class PythonTypeStubsBackend(CodeBackend): self._generate_union_class_is_set(data_type) self._generate_union_class_variant_creators(ns, data_type) self._generate_union_class_get_helpers(ns, data_type) + + self._generate_validator_for(data_type) self.emit() def _generate_union_class_vars(self, ns, data_type): @@ -356,6 +369,22 @@ class PythonTypeStubsBackend(CodeBackend): return map_stone_type_to_python_type(ns, data_type, override_dict=self._pep_484_type_mapping_callbacks) + def _generate_routes( + self, + namespace, # type: ApiNamespace + ): + # type: (...) -> None + for route in namespace.routes: + var_name = fmt_func(route.name) + self.emit( + "{var_name} = ... # type: bb.Route".format( + var_name=var_name + ) + ) + + if namespace.routes: + self.emit() + def _generate_imports_needed_for_typing(self): # type: () -> None if self.import_tracker.cur_namespace_typing_imports: diff --git a/stone/ir/api.py b/stone/ir/api.py index 2ee40e6..703961e 100644 --- a/stone/ir/api.py +++ b/stone/ir/api.py @@ -104,7 +104,7 @@ class ApiNamespace(object): self.name = name self.doc = None # type: typing.Optional[six.text_type] self.routes = [] # type: typing.List[ApiRoute] - self.route_by_name = {} # type: typing.Dict[str, ApiRoute] + self.route_by_name = {} # type: typing.Dict[typing.Text, ApiRoute] self.data_types = [] # type: typing.List[UserDefined] self.data_type_by_name = {} # type: typing.Dict[str, UserDefined] self.aliases = [] # type: typing.List[Alias] @@ -315,7 +315,7 @@ class ApiRoute(object): def __init__(self, name, ast_node): - # type: (str, AstRouteDef) -> None + # type: (typing.Text, AstRouteDef) -> None """ :param str name: Designated name of the endpoint. :param ast_node: Raw route definition from the parser.
dropbox/stone
aee647260f103dcb78a3b6af43d6000a9cbd8eaa
diff --git a/test/test_python_type_stubs.py b/test/test_python_type_stubs.py index dd64bc5..e4423fb 100644 --- a/test/test_python_type_stubs.py +++ b/test/test_python_type_stubs.py @@ -1,6 +1,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals import textwrap + MYPY = False if MYPY: import typing # noqa: F401 # pylint: disable=import-error,unused-import,useless-suppression @@ -30,6 +31,7 @@ from stone.ir import ( UnionField, Void, Float64) +from stone.ir.api import ApiRoute from stone.backends.python_type_stubs import PythonTypeStubsBackend from test.backend_test_util import _mock_emit @@ -167,6 +169,22 @@ def _make_namespace_with_empty_union(): return ns +def _make_namespace_with_route(): + # type: (...) -> ApiNamespace + ns = ApiNamespace("_make_namespace_with_route()") + mock_ast_node = Mock() + route_one = ApiRoute( + name="route_one", + ast_node=mock_ast_node, + ) + route_two = ApiRoute( + name="route_two", + ast_node=mock_ast_node, + ) + ns.add_route(route_one) + ns.add_route(route_two) + return ns + def _api(): api = Api(version="1.0") return api @@ -219,7 +237,8 @@ class TestPythonTypeStubs(unittest.TestCase): @f1.deleter def f1(self) -> None: ... - + + Struct1_validator = ... # type: stone_validators.Validator class Struct2(object): def __init__(self, @@ -256,6 +275,7 @@ class TestPythonTypeStubs(unittest.TestCase): @f4.deleter def f4(self) -> None: ... + Struct2_validator = ... # type: stone_validators.Validator from typing import ( @@ -298,6 +318,7 @@ class TestPythonTypeStubs(unittest.TestCase): @nullable_list.deleter def nullable_list(self) -> None: ... + NestedTypes_validator = ... # type: stone_validators.Validator from typing import ( @@ -322,6 +343,7 @@ class TestPythonTypeStubs(unittest.TestCase): def is_last(self) -> bool: ... + Union_validator = ... # type: stone_validators.Validator class Shape(bb.Union): point = ... # type: Shape @@ -335,7 +357,8 @@ class TestPythonTypeStubs(unittest.TestCase): def get_circle(self) -> float: ... - + Shape_validator = ... # type: stone_validators.Validator + """).format(headers=_headers) self.assertEqual(result, expected) @@ -348,6 +371,21 @@ class TestPythonTypeStubs(unittest.TestCase): class EmptyUnion(bb.Union): pass + + EmptyUnion_validator = ... # type: stone_validators.Validator + + """).format(headers=_headers) + self.assertEqual(result, expected) + + def test__generate_routes(self): + # type: () -> None + ns = _make_namespace_with_route() + result = self._evaluate_namespace(ns) + expected = textwrap.dedent("""\ + {headers} + + route_one = ... # type: bb.Route + route_two = ... # type: bb.Route """).format(headers=_headers) self.assertEqual(result, expected) @@ -372,6 +410,7 @@ class TestPythonTypeStubs(unittest.TestCase): @f1.deleter def f1(self) -> None: ... + Struct1_validator = ... # type: stone_validators.Validator AliasToStruct1 = Struct1 """).format(headers=_headers)
python_type_stubs generator should output _validator and route objects. This was an oversight on my original implementation of `python_type_stubs` - after integrating it into our codebase I've seen a few mypy errors along the lines of ``` has no attribute 'SomeStoneType_validator ``` and ``` Module has no attribute "name_of_a_route" ``` I might work on it this weekend, just wanted to track as an issue
0.0
aee647260f103dcb78a3b6af43d6000a9cbd8eaa
[ "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_alias", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_many_structs", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module__with_nested_types", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_empty_union__generates_pass", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_base_namespace_module_with_union__generates_stuff", "test/test_python_type_stubs.py::TestPythonTypeStubs::test__generate_routes" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-02-20 21:13:54+00:00
mit
2,006
druid-io__pydruid-58
diff --git a/pydruid/query.py b/pydruid/query.py index af246a0..cd7c1cf 100644 --- a/pydruid/query.py +++ b/pydruid/query.py @@ -24,12 +24,6 @@ from pydruid.utils.dimensions import build_dimension from pydruid.utils.postaggregator import Postaggregator from pydruid.utils.query_utils import UnicodeWriter -try: - import pandas -except ImportError: - print('Warning: unable to import Pandas. The export_pandas method will not work.') - pass - class Query(collections.MutableSequence): """ @@ -159,6 +153,8 @@ class Query(collections.MutableSequence): 0 7 2013-10-04T00:00:00.000Z user_1 1 6 2013-10-04T00:00:00.000Z user_2 """ + import pandas + if self.result: if self.query_type == "timeseries": nres = [list(v['result'].items()) + [('timestamp', v['timestamp'])] @@ -250,11 +246,11 @@ class QueryBuilder(object): query_dict['pagingSpec'] = val elif key == 'limit_spec': query_dict['limitSpec'] = val - elif key == "filter": + elif key == "filter" and val is not None: query_dict[key] = Filter.build_filter(val) - elif key == "having": + elif key == "having" and val is not None: query_dict[key] = Having.build_having(val) - elif key == 'dimension': + elif key == 'dimension' and val is not None: query_dict[key] = build_dimension(val) elif key == 'dimensions': query_dict[key] = [build_dimension(v) for v in val]
druid-io/pydruid
ce0982867d4bb3d809ba32c6563dadc8d8d6576f
diff --git a/tests/test_query.py b/tests/test_query.py index 64da17b..d84f35b 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -111,6 +111,44 @@ class TestQueryBuilder: # then assert query.query_dict == expected_query_dict + def test_build_query_none_type(self): + # given + expected_query_dict = { + 'queryType': None, + 'dataSource': 'things', + 'aggregations': [{'fieldName': 'thing', 'name': 'count', 'type': 'count'}], + 'filter': {'dimension': 'one', 'type': 'selector', 'value': 1}, + 'having': {'aggregation': 'sum', 'type': 'greaterThan', 'value': 1}, + 'dimension': 'dim1', + } + + builder = QueryBuilder() + + # when + builder_dict = { + 'datasource': 'things', + 'aggregations': { + 'count': aggregators.count('thing'), + }, + 'filter': filters.Dimension('one') == 1, + 'having': having.Aggregation('sum') > 1, + 'dimension': 'dim1', + } + query = builder.build_query(None, builder_dict) + + # then + assert query.query_dict == expected_query_dict + + # you should be able to pass `None` to dimension/having/filter + for v in ['dimension', 'having', 'filter']: + expected_query_dict[v] = None + builder_dict[v] = None + + query = builder.build_query(None, builder_dict) + + assert query.query_dict == expected_query_dict + + def test_validate_query(self): # given builder = QueryBuilder()
Exception when `filter=None` When building query if `filter=None` then an exception occurs: ``` File "/Users/se7entyse7en/Envs/viralize-web/lib/python2.7/site-packages/pydruid/utils/filters.py", line 61, in build_filter return filter_obj.filter['filter'] AttributeError: 'NoneType' object has no attribute 'filter' ```
0.0
ce0982867d4bb3d809ba32c6563dadc8d8d6576f
[ "tests/test_query.py::TestQueryBuilder::test_build_query_none_type" ]
[ "tests/test_query.py::TestQueryBuilder::test_build_query", "tests/test_query.py::TestQueryBuilder::test_validate_query", "tests/test_query.py::TestQuery::test_export_tsv", "tests/test_query.py::TestQuery::test_query_acts_as_a_wrapper_for_raw_result" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2016-06-29 09:06:59+00:00
apache-2.0
2,007
drvinceknight__nbchkr-14
diff --git a/src/nbchkr/utils/__init__.py b/src/nbchkr/utils/__init__.py index 67a65c1..9a8afba 100644 --- a/src/nbchkr/utils/__init__.py +++ b/src/nbchkr/utils/__init__.py @@ -27,7 +27,7 @@ def read(nb_path: pathlib.Path, as_version: int = 4) -> dict: def remove_cells( - nb_json, tags_regex_patterns_to_ignore=None, solution_regex=None + nb_node, tags_regex_patterns_to_ignore=None, solution_regex=None ): # TODO Add typing to this function """ Given a dictionary representation of a notebook, removes: @@ -42,7 +42,7 @@ def remove_cells( if solution_regex is None: solution_regex = SOLUTION_REGEX cells = [] - for cell in nb_json["cells"]: + for cell in nb_node["cells"]: if "tags" not in cell["metadata"] or all( not bool(re.match(pattern=pattern, string=tag)) for tag in cell["metadata"]["tags"] @@ -61,21 +61,21 @@ def remove_cells( except KeyError: # pragma: no cover pass # TODO Add test coverage for this statement cells.append(cell) - nb_json["cells"] = cells - return nb_json + nb_node["cells"] = cells + return nb_node -def write(output_path: pathlib.Path, nb_json): +def write(output_path: pathlib.Path, nb_node: dict): """ Write the python dict representation of a notebook to `output_path`. """ - output_path.write_text(json.dumps(nb_json)) + output_path.write_text(json.dumps(nb_node)) -def add_checks(nb_json: dict, source_nb_json: dict, answer_tag_regex=None) -> dict: +def add_checks(nb_node: dict, source_nb_node: dict, answer_tag_regex=None) -> dict: """ - Given a `nb_json` and a source `source_nb_json`, add the cells in - `source_nb` with tags matching `answer_tag_regex` to `source_nb_json` + Given a `nb_node` and a source `source_nb_node`, add the cells in + `source_nb` with tags matching `answer_tag_regex` to `source_nb_node` This is used to add a student's answers to the source notebook. """ @@ -83,15 +83,15 @@ def add_checks(nb_json: dict, source_nb_json: dict, answer_tag_regex=None) -> di answer_tag_regex = ANSWER_TAG_REGEX answers = { tag: cell - for cell in nb_json["cells"] + for cell in nb_node["cells"] for tag in cell["metadata"].get("tags", []) if bool(re.match(pattern=answer_tag_regex, string=tag)) } - for i, cell in enumerate(source_nb_json["cells"]): + for i, cell in enumerate(source_nb_node["cells"]): for tag in cell["metadata"].get("tags", []): if tag in answers: - source_nb_json["cells"][i] = answers[tag] - return source_nb_json + source_nb_node["cells"][i] = answers[tag] + return source_nb_node def get_tags(cell: dict, tag_seperator: str = "|") -> Optional[str]:
drvinceknight/nbchkr
7ac9e38498d7cc9118027495d939f849dae3270c
diff --git a/tests/test_check.py b/tests/test_check.py index 94c9006..ebef0b3 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -20,16 +20,16 @@ def test_read_nb_gives_dictionary(): def test_add_checks_creates_notebook_with_assertions(): - nb_json = nbchkr.utils.read(nb_path=NB_PATH / "submission.ipynb") - source_nb_json = nbchkr.utils.read(nb_path=NB_PATH / "test.ipynb") + nb_node = nbchkr.utils.read(nb_path=NB_PATH / "submission.ipynb") + source_nb_node = nbchkr.utils.read(nb_path=NB_PATH / "test.ipynb") nb_with_checks = nbchkr.utils.add_checks( - nb_json=nb_json, source_nb_json=source_nb_json + nb_node=nb_node, source_nb_node=source_nb_node ) assert "assert _ == 55" in str(nb_with_checks) assert "sum(i for i in range(10))" in str(nb_with_checks) output_path = NB_PATH / "feedback.ipynb" - nbchkr.utils.write(output_path=output_path, nb_json=nb_with_checks) + nbchkr.utils.write(output_path=output_path, nb_node=nb_with_checks) def test_check_with_no_errors_for_original_source(): @@ -65,7 +65,7 @@ Assertion passed: def test_check_with_no_errors_for_test_submission(): nb_node = nbchkr.utils.read(nb_path=NB_PATH / "submission.ipynb") source_nb_node = nbchkr.utils.read(nb_path=NB_PATH / "test.ipynb") - nb_node = nbchkr.utils.add_checks(nb_json=nb_node, source_nb_json=source_nb_node) + nb_node = nbchkr.utils.add_checks(nb_node=nb_node, source_nb_node=source_nb_node) score, maximum_score, feedback = nbchkr.utils.check(nb_node=nb_node) expected_score = 2 expected_maximum_score = 10 diff --git a/tests/test_release.py b/tests/test_release.py index bf5feb6..79b04d9 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -46,33 +46,33 @@ def test_read_nb_cells_gives_list(): def test_remove_cells(): nb_path = NB_PATH / "test.ipynb" - nb_json = nbchkr.utils.read(nb_path=nb_path) - student_nb = nbchkr.utils.remove_cells(nb_json=nb_json) + nb_node = nbchkr.utils.read(nb_path=nb_path) + student_nb = nbchkr.utils.remove_cells(nb_node=nb_node) expected_length = 4 assert type(student_nb["cells"]) is list assert len(student_nb["cells"]) == expected_length -def test_remove_solution_and_keep_original_nb_json_unchanged(): +def test_remove_solution_and_keep_original_nb_node_unchanged(): """ This checks that solutions text is not included. - Note that, as implemented both `nb_json` and `student_nb` are modified. This + Note that, as implemented both `nb_node` and `student_nb` are modified. This should be fixed. TODO When fixed remove this line of documentation. """ nb_path = NB_PATH / "test.ipynb" - nb_json = nbchkr.utils.read(nb_path=nb_path) - assert "sum(i for i in range(11))" in str(nb_json) - assert "sum(i for i in range(n + 1))" in str(nb_json) - assert "55" in str(nb_json) + nb_node = nbchkr.utils.read(nb_path=nb_path) + assert "sum(i for i in range(11))" in str(nb_node) + assert "sum(i for i in range(n + 1))" in str(nb_node) + assert "55" in str(nb_node) - student_nb = nbchkr.utils.remove_cells(nb_json=nb_json) + student_nb = nbchkr.utils.remove_cells(nb_node=nb_node) assert "sum(i for i in range(11))" not in str(student_nb) assert "sum(i for i in range(n + 1))" not in str(student_nb) assert "55" not in str(student_nb) # TODO Add test that shows wrong behaviour of changing the imported JSON # and document. - assert "sum(i for i in range(n + 1))" not in str(nb_json) + assert "sum(i for i in range(n + 1))" not in str(nb_node) def test_write_nb(): @@ -83,9 +83,9 @@ def test_write_nb(): except FileNotFoundError: # TODO Ensure py3.8 is used so that can pass # `missing_ok=True` to `path.unlink`. pass - nb_json = nbchkr.utils.read(nb_path=nb_path) - student_nb = nbchkr.utils.remove_cells(nb_json=nb_json) - nbchkr.utils.write(output_path=output_path, nb_json=student_nb) + nb_node = nbchkr.utils.read(nb_path=nb_path) + student_nb = nbchkr.utils.remove_cells(nb_node=nb_node) + nbchkr.utils.write(output_path=output_path, nb_node=student_nb) student_nb = nbchkr.utils.read(nb_path=output_path) assert "sum(i for i in range(11))" not in str(student_nb)
Clear up variable naming In particular the following two conventions are currently being used: - `nb_json` - `nb_node` Aim for `nb_node`.
0.0
7ac9e38498d7cc9118027495d939f849dae3270c
[ "tests/test_check.py::test_add_checks_creates_notebook_with_assertions", "tests/test_check.py::test_check_with_no_errors_for_test_submission", "tests/test_release.py::test_remove_cells", "tests/test_release.py::test_remove_solution_and_keep_original_nb_node_unchanged", "tests/test_release.py::test_write_nb" ]
[ "tests/test_check.py::test_read_nb_gives_dictionary", "tests/test_check.py::test_check_with_no_errors_for_original_source", "tests/test_release.py::test_read_nb_gives_dictionary", "tests/test_release.py::test_read_nb_gives_expected_keys", "tests/test_release.py::test_read_nb_cells_gives_list" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-07 14:51:51+00:00
mit
2,008
drvinceknight__nbchkr-19
diff --git a/.github/workflows/config.yml b/.github/workflows/config.yml index bc1675a..4209e6e 100644 --- a/.github/workflows/config.yml +++ b/.github/workflows/config.yml @@ -21,30 +21,42 @@ jobs: - name: Update pip run: | python -m pip install --upgrade pip - - name: Check format (only on py3.8 and ubuntu) + - name: Install black (only on py3.8 and ubuntu) if: matrix.python-version == 3.8 && matrix.os == 'ubuntu-latest' run: | python -m pip install black + - name: Check format (only on py3.8 and ubuntu) + if: matrix.python-version == 3.8 && matrix.os == 'ubuntu-latest' + run: | python -m black . --check - - name: Check format of imports (only on py3.8 and ubuntu) + - name: Install isort (only on py3.8 and ubuntu) if: matrix.python-version == 3.8 && matrix.os == 'ubuntu-latest' run: | python -m pip install isort + - name: Check format of imports (only on py3.8 and ubuntu) + if: matrix.python-version == 3.8 && matrix.os == 'ubuntu-latest' + run: | python -m isort --check-only src/nbchkr/. - - name: Test with pytest + - name: Installing testing dependencies run: | - python setup.py develop python -m pip install pytest python -m pip install pytest-cov python -m pip install pytest-flake8 python -m pip install pytest-randomly python -m pip install pytest-sugar + - name: Test with pytest + run: | + python setup.py develop python -m pytest -v --cov=nbchkr --cov-fail-under=100 --flake8 - - name: Interrogate docstrings to check docstring coverage + - name: Install interrogate run: | python -m pip install interrogate + - name: Interrogate docstrings to check docstring coverage + run: | interrogate -e setup.py -e tests/ -M -i -v -f 100 . - - name: Check static typing + - name: Install mypy run: | python -m pip install mypy + - name: Check static typing + run: | python -m mypy src/ --pretty diff --git a/src/nbchkr/utils/__init__.py b/src/nbchkr/utils/__init__.py index 691ded3..d191c2c 100644 --- a/src/nbchkr/utils/__init__.py +++ b/src/nbchkr/utils/__init__.py @@ -11,6 +11,10 @@ TAGS_REGEX_PATTERNS_TO_IGNORE = ["hide", r"score:\d"] SOLUTION_REGEX = re.compile( r"### BEGIN SOLUTION[\s\S](.*?)[\s\S]### END SOLUTION", re.DOTALL ) +SOLUTION_REPL = """### BEGIN SOLUTION + + +### END SOLUTION""" UNIVERSAL_REGEX = re.compile(r".", re.DOTALL) ANSWER_TAG_REGEX = r"answer:*" SCORE_REGEX = re.compile(r"score:(\d+)") @@ -28,7 +32,7 @@ def read(nb_path: pathlib.Path, as_version: int = 4) -> dict: def remove_cells( - nb_node, tags_regex_patterns_to_ignore=None, solution_regex=None + nb_node, tags_regex_patterns_to_ignore=None, solution_regex=None, solution_repl=None ): # TODO Add typing to this function """ Given a dictionary representation of a notebook, removes: @@ -42,6 +46,8 @@ def remove_cells( tags_regex_patterns_to_ignore = TAGS_REGEX_PATTERNS_TO_IGNORE if solution_regex is None: solution_regex = SOLUTION_REGEX + if solution_repl is None: + solution_repl = SOLUTION_REPL cells = [] for cell in nb_node["cells"]: if "tags" not in cell["metadata"] or all( @@ -51,7 +57,9 @@ def remove_cells( ): try: source = "".join(cell["source"]) - new_source = re.sub(pattern=solution_regex, repl="", string=source) + new_source = re.sub( + pattern=solution_regex, repl=solution_repl, string=source + ) cell["source"] = new_source if bool(re.match(pattern=solution_regex, string=source)) is True:
drvinceknight/nbchkr
450c5ac0dee7ccbb2d13ca905459d708727b7e69
diff --git a/tests/test_release.py b/tests/test_release.py index 79b04d9..7f080f2 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -65,11 +65,15 @@ def test_remove_solution_and_keep_original_nb_node_unchanged(): assert "sum(i for i in range(11))" in str(nb_node) assert "sum(i for i in range(n + 1))" in str(nb_node) assert "55" in str(nb_node) + assert "### BEGIN SOLUTION" in str(nb_node) + assert "### END SOLUTION" in str(nb_node) student_nb = nbchkr.utils.remove_cells(nb_node=nb_node) assert "sum(i for i in range(11))" not in str(student_nb) assert "sum(i for i in range(n + 1))" not in str(student_nb) assert "55" not in str(student_nb) + assert "BEGIN SOLUTION" in str(student_nb) + assert "END SOLUTION" in str(student_nb) # TODO Add test that shows wrong behaviour of changing the imported JSON # and document. assert "sum(i for i in range(n + 1))" not in str(nb_node)
Fix the regex for solutions here. Currently the default is to have: ``` ### BEGIN SOLUTION ### END SOLUTION ``` The regex finds that but removes the markers which would be nicer to leave in.
0.0
450c5ac0dee7ccbb2d13ca905459d708727b7e69
[ "tests/test_release.py::test_remove_solution_and_keep_original_nb_node_unchanged" ]
[ "tests/test_release.py::test_read_nb_gives_dictionary", "tests/test_release.py::test_read_nb_gives_expected_keys", "tests/test_release.py::test_read_nb_cells_gives_list", "tests/test_release.py::test_remove_cells", "tests/test_release.py::test_write_nb" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-12 16:21:19+00:00
mit
2,009
dstl__Stone-Soup-215
diff --git a/stonesoup/metricgenerator/tracktotruthmetrics.py b/stonesoup/metricgenerator/tracktotruthmetrics.py index d076e4d2..0ac1edca 100644 --- a/stonesoup/metricgenerator/tracktotruthmetrics.py +++ b/stonesoup/metricgenerator/tracktotruthmetrics.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import datetime +import warnings from operator import attrgetter import numpy as np @@ -48,6 +49,16 @@ class SIAPMetrics(MetricGenerator): self.LS(manager)] return metrics + @staticmethod + def _warn_no_truth(manager): + if len(manager.groundtruth_paths) == 0: + warnings.warn("No truth to generate SIAP Metric", stacklevel=2) + + @staticmethod + def _warn_no_tracks(manager): + if len(manager.tracks) == 0: + warnings.warn("No tracks to generate SIAP Metric", stacklevel=2) + def C_single_time(self, manager, timestamp): r"""SIAP metric C at a specific time @@ -126,8 +137,12 @@ class SIAPMetrics(MetricGenerator): """ timestamps = manager.list_timestamps() - C = self._jt_sum(manager, timestamps) / self._j_sum( - manager, timestamps) + try: + C = self._jt_sum(manager, timestamps) / self._j_sum( + manager, timestamps) + except ZeroDivisionError: + self._warn_no_truth(manager) + C = 0 return TimeRangeMetric( title="SIAP C", value=C, @@ -165,8 +180,12 @@ class SIAPMetrics(MetricGenerator): """ timestamps = manager.list_timestamps() - A = self._na_sum(manager, timestamps) / self._jt_sum( - manager, timestamps) + try: + A = self._na_sum(manager, timestamps) / self._jt_sum(manager, timestamps) + except ZeroDivisionError: + self._warn_no_truth(manager) + self._warn_no_tracks(manager) + A = 0 return TimeRangeMetric( title="SIAP A", value=A, @@ -207,7 +226,11 @@ class SIAPMetrics(MetricGenerator): self._n_t(manager, timestamp) - self._na_t(manager, timestamp) for timestamp in timestamps) - S = numerator / self._n_sum(manager, timestamps) + try: + S = numerator / self._n_sum(manager, timestamps) + except ZeroDivisionError: + self._warn_no_tracks(manager) + S = 0 return TimeRangeMetric( title="SIAP S", value=S, @@ -234,6 +257,8 @@ class SIAPMetrics(MetricGenerator): r = self._r(manager) if r == 0: value = np.inf + self._warn_no_truth(manager) + self._warn_no_tracks(manager) else: value = 1 / r @@ -277,9 +302,14 @@ class SIAPMetrics(MetricGenerator): for truth in manager.groundtruth_paths) timestamps = manager.list_timestamps() + try: + LS = numerator / denominator + except ZeroDivisionError: + self._warn_no_truth(manager) + LS = 0 return TimeRangeMetric( title="SIAP LS", - value=numerator / denominator, + value=LS, time_range=TimeRange(min(timestamps), max(timestamps)), generator=self) @@ -571,7 +601,11 @@ class SIAPMetrics(MetricGenerator): for truth in manager.groundtruth_paths) denominator = sum(self._tt_j(manager, truth).total_seconds() for truth in manager.groundtruth_paths) - return numerator / denominator + try: + return numerator / denominator + except ZeroDivisionError: + # No truth or tracks + return 0 def _t_j(self, truth): """Total time truth exists for
dstl/Stone-Soup
1bf38717a65d21044480c1da4625be243c7d1b5a
diff --git a/stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py b/stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py index e7a3df90..6fc0c9ea 100644 --- a/stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py +++ b/stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py @@ -1,5 +1,7 @@ import datetime +import pytest + from ..tracktotruthmetrics import SIAPMetrics from ...types.association import TimeRangeAssociation, AssociationSet from ...types.track import Track @@ -271,7 +273,6 @@ def test_compute_metric(): track9 = Track( states=[State([[9]], timestamp=tstart + datetime.timedelta(seconds=i)) for i in range(35, 40)]) - manager.groundtruth_paths = truth manager.tracks = {track1, track2, track3, track4, track5, track6, track7, track8, track9} manager.groundtruth_paths = {truth} @@ -330,3 +331,77 @@ def test_compute_metric(): assert ls.time_range.start_timestamp == tstart assert ls.time_range.end_timestamp == tend assert ls.generator == generator + + +def test_no_truth_divide_by_zero(): + manager = SimpleManager() + generator = SIAPMetrics() + # Create truth, tracks and associations, same as test_nu_j + tstart = datetime.datetime.now() + track1 = Track( + states=[State([[1]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(3)]) + track2 = Track( + states=[State([[2]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(5, 10)]) + track3 = Track( + states=[State([[3]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(7, 15)]) + track4 = Track( + states=[State([[4]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(13, 20)]) + track5 = Track( + states=[State([[5]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(18, 28)]) + track6 = Track( + states=[State([[6]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(22, 26)]) + track7 = Track( + states=[State([[7]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(30, 40)]) + track8 = Track( + states=[State([[8]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(30, 35)]) + track9 = Track( + states=[State([[9]], timestamp=tstart + datetime.timedelta(seconds=i)) + for i in range(35, 40)]) + manager.tracks = {track1, track2, track3, track4, track5, track6, track7, + track8, track9} + manager.groundtruth_paths = set() + associations = {TimeRangeAssociation({track}, time_range=TimeRange( + start_timestamp=min([state.timestamp for state in track.states]), + end_timestamp=max([state.timestamp for state in track.states]))) + for track in manager.tracks} + manager.association_set = AssociationSet(associations) + + with pytest.warns(UserWarning) as warning: + metrics = generator.compute_metric(manager) + + assert warning[0].message.args[0] == "No truth to generate SIAP Metric" + + assert len(metrics) == 5 + + +def test_no_track_divide_by_zero(): + manager = SimpleManager() + generator = SIAPMetrics() + # Create truth, tracks and associations, same as test_nu_j + tstart = datetime.datetime.now() + truth = GroundTruthPath(states=[ + GroundTruthState([[1]], timestamp=tstart + datetime.timedelta( + seconds=i)) + for i in range(40)]) + manager.tracks = set() + manager.groundtruth_paths = {truth} + associations = {TimeRangeAssociation({truth}, time_range=TimeRange( + start_timestamp=min([state.timestamp for state in track.states]), + end_timestamp=max([state.timestamp for state in track.states]))) + for track in manager.tracks} + manager.association_set = AssociationSet(associations) + + with pytest.warns(UserWarning) as warning: + metrics = generator.compute_metric(manager) + + assert warning[0].message.args[0] == "No tracks to generate SIAP Metric" + + assert len(metrics) == 5
self.metric_manager.generate_metrics() : ZeroDivisionError: division by zero Probably my data, however FYI. ``` File "lib\_mot\mot.py", line 302, in run self.metrics_generate() File "lib\_mot\mot.py", line 253, in metrics_generate self.metrics = self.metric_manager.generate_metrics() File "C:\g\testapp\lib\lib\site-packages\stonesoup\metricgenerator\manager.py", line 87, in generate_metrics metric = generator.compute_metric(self) File "C:\g\testapp\lib\lib\site-packages\stonesoup\metricgenerator\tracktotruthmetrics.py", line 45, in compute_metric self.A_time_range(manager), File "C:\g\testapp\lib\lib\site-packages\stonesoup\metricgenerator\tracktotruthmetrics.py", line 169, in A_time_range manager, timestamps) ZeroDivisionError: division by zero ```
0.0
1bf38717a65d21044480c1da4625be243c7d1b5a
[ "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_no_truth_divide_by_zero", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_no_track_divide_by_zero" ]
[ "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_j_t", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_j_sum", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_jt", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test__na", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_n", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_tt_j", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_nu_j", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_t_j", "stonesoup/metricgenerator/tests/test_tracktotruthmetrics.py::test_compute_metric" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-05-06 10:02:57+00:00
mit
2,010
duartegroup__autodE-105
diff --git a/autode/calculation.py b/autode/calculation.py index b1a7931..a0accc4 100644 --- a/autode/calculation.py +++ b/autode/calculation.py @@ -3,6 +3,7 @@ import os import hashlib import base64 from typing import Optional, List +from functools import wraps import autode.wrappers.keywords as kws import autode.exceptions as ex from autode.utils import cached_property @@ -23,6 +24,22 @@ def execute_calc(calc): return calc.execute_calculation() +def _requires_set_output_filename(func): + """Calculation method requiring the output filename to be set""" + + @wraps(func) + def wrapped_function(*args, **kwargs): + calc = args[0] + + if calc.output.filename is None: + raise ex.CouldNotGetProperty( + f'Could not get property from {calc.name}. ' + f'Has .run() been called?') + return func(*args, **kwargs) + + return wrapped_function + + class Calculation: def __init__(self, @@ -238,28 +255,29 @@ class Calculation: methods.add(f'{string}.\n') return None - def get_energy(self) -> Optional[PotentialEnergy]: + @_requires_set_output_filename + def get_energy(self) -> PotentialEnergy: """ - Total electronic potential energy + Total electronic potential energy from the final structure in the + calculation + ----------------------------------------------------------------------- Returns: (autode.values.PotentialEnergy | None): + + Raises: + (autode.exceptions.CouldNotGetProperty): """ logger.info(f'Getting energy from {self.output.filename}') if not self.terminated_normally: - logger.error('Calculation did not terminate normally. ' - 'Energy = None') - return None + logger.error(f'Calculation of {self.molecule} did not terminate ' + f'normally') + raise ex.CouldNotGetProperty(name='energy') - try: - return PotentialEnergy(self.method.get_energy(self), - method=self.method, - keywords=self.input.keywords) - - except ex.CouldNotGetProperty: - logger.warning('Could not get energy. Energy = None') - return None + return PotentialEnergy(self.method.get_energy(self), + method=self.method, + keywords=self.input.keywords) def optimisation_converged(self) -> bool: """ @@ -289,6 +307,7 @@ class Calculation: return self.method.optimisation_nearly_converged(self) + @_requires_set_output_filename def get_final_atoms(self) -> Atoms: """ Get the atoms from the final step of a geometry optimisation @@ -317,6 +336,7 @@ class Calculation: return atoms + @_requires_set_output_filename def get_atomic_charges(self) -> List[float]: """ Get the partial atomic charges from a calculation. The method used to @@ -338,6 +358,7 @@ class Calculation: return charges + @_requires_set_output_filename def get_gradients(self) -> Gradient: """ Get the gradient (dE/dr) with respect to atomic displacement from a @@ -357,6 +378,7 @@ class Calculation: return gradients + @_requires_set_output_filename def get_hessian(self) -> Hessian: """ Get the Hessian matrix (d^2E/dr^2) i.e. the matrix of second @@ -628,3 +650,7 @@ class CalculationInput: return self.additional_filenames return [self.filename] + self.additional_filenames + + + + diff --git a/autode/species/species.py b/autode/species/species.py index b8aa2bb..63d009c 100644 --- a/autode/species/species.py +++ b/autode/species/species.py @@ -1014,9 +1014,16 @@ class Species(AtomCollection): if calc is not None and calc.output.exists: self.atoms = calc.get_final_atoms() - self.energy = calc.get_energy() self.hessian = calc.get_hessian() + try: + self.energy = calc.get_energy() + + except CalculationException: + logger.warning(f'Failed to get the potential energy from ' + f'{calc.name} but not essential for thermo' + f'chemical calculation') + elif self.hessian is None or (calc is not None and not calc.output.exists): logger.info('Calculation did not exist or Hessian was None - ' 'calculating the Hessian') @@ -1074,13 +1081,7 @@ class Species(AtomCollection): keywords=keywords, n_cores=Config.n_cores if n_cores is None else n_cores) sp.run() - energy = sp.get_energy() - - if energy is None: - raise CalculationException("Failed to calculate a single point " - f"energy for {self}") - - self.energy = energy + self.energy = sp.get_energy() return None @work_in('conformers') diff --git a/autode/transition_states/base.py b/autode/transition_states/base.py index 51b943c..4956b08 100644 --- a/autode/transition_states/base.py +++ b/autode/transition_states/base.py @@ -295,7 +295,7 @@ class TSbase(Species, ABC): keywords=method.keywords.low_opt, reset_graph=True) - except ex.AtomsNotFound: + except ex.CalculationException: logger.error(f'Failed to optimise {mol.name} with ' f'{method}. Assuming no link') return False diff --git a/doc/changelog.rst b/doc/changelog.rst index 23ca780..a577f35 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -28,6 +28,8 @@ Usability improvements/Changes - Removes :code:`autode.KcalMol` and :code:`KjMol` and enables a reaction to be plotted using a string representation of the units. - Allows for keywords to be set using just a list or a string, rather than requiring a specific type - Changes :code:`autode.wrappers.keywords.Keyword.has_only_name` to a property +- Modifies :code:`autode.calculation.Calculation.get_energy` to raise an exception if the energy cannot be extracted +- Adds a runtime error if e.g. :code:`autode.calculation.Calculation.get_energy` is called on a calculation that has not been run Functionality improvements
duartegroup/autodE
421ceaad5d424055d4dbf5986ee213e505e0a615
diff --git a/tests/test_calculation.py b/tests/test_calculation.py index d115145..4bec1e7 100644 --- a/tests/test_calculation.py +++ b/tests/test_calculation.py @@ -28,12 +28,13 @@ def test_calc_class(): assert calc.method.name == 'xtb' assert len(calc.input.filenames) == 0 - assert calc.get_energy() is None + with pytest.raises(ex.CouldNotGetProperty): + _ = calc.get_energy() assert not calc.optimisation_converged() assert not calc.optimisation_nearly_converged() - with pytest.raises(ex.AtomsNotFound): + with pytest.raises(ex.CouldNotGetProperty): _ = calc.get_final_atoms() with pytest.raises(ex.CouldNotGetProperty): diff --git a/tests/test_gaussian_calc.py b/tests/test_gaussian_calc.py index 34729e1..bf64cea 100644 --- a/tests/test_gaussian_calc.py +++ b/tests/test_gaussian_calc.py @@ -10,8 +10,7 @@ from autode.wrappers import keywords as kwds from autode.wrappers.basis_sets import def2tzecp, def2tzvp from autode.wrappers.functionals import pbe0 from autode.wrappers.keywords import OptKeywords, SinglePointKeywords -from autode.exceptions import AtomsNotFound -from autode.exceptions import NoInputError +from autode.exceptions import AtomsNotFound, NoInputError, CalculationException from autode.point_charges import PointCharge from autode.atoms import Atom from . import testutils @@ -185,8 +184,10 @@ def test_bad_gauss_output(): calc.output_file_lines = [] calc.rev_output_file_lines = [] - assert calc.get_energy() is None - with pytest.raises(AtomsNotFound): + with pytest.raises(CalculationException): + _ = calc.get_energy() + + with pytest.raises(CalculationException): calc.get_final_atoms() with pytest.raises(NoInputError): diff --git a/tests/test_mopac_calc.py b/tests/test_mopac_calc.py index effa78c..0d97689 100644 --- a/tests/test_mopac_calc.py +++ b/tests/test_mopac_calc.py @@ -129,7 +129,10 @@ def test_bad_geometry(): calc.output.filename = 'h2_overlap_opt_mopac.out' assert not calc.terminated_normally - assert calc.get_energy() is None + + with pytest.raises(CouldNotGetProperty): + _ = calc.get_energy() + assert not calc.optimisation_converged() diff --git a/tests/test_orca_calc.py b/tests/test_orca_calc.py index f698071..4b0e162 100644 --- a/tests/test_orca_calc.py +++ b/tests/test_orca_calc.py @@ -9,6 +9,7 @@ from autode.species.molecule import Molecule from autode.input_output import xyz_file_to_atoms from autode.wrappers.keywords import SinglePointKeywords, OptKeywords from autode.wrappers.keywords import Functional, WFMethod, BasisSet +from autode.exceptions import CouldNotGetProperty from autode.solvent.solvents import ImplicitSolvent from autode.transition_states.transition_state import TransitionState from autode.transition_states.ts_guess import TSguess @@ -137,9 +138,11 @@ def test_bad_orca_output(): calc = Calculation(name='no_output', molecule=test_mol, method=method, keywords=opt_keywords) - assert calc.get_energy() is None - with pytest.raises(ex.AtomsNotFound): - calc.get_final_atoms() + with pytest.raises(CouldNotGetProperty): + _ = calc.get_energy() + + with pytest.raises(ex.CouldNotGetProperty): + _ = calc.get_final_atoms() with pytest.raises(ex.NoInputError): calc.execute_calculation() diff --git a/tests/test_xtb_calc.py b/tests/test_xtb_calc.py index 2974ac8..8e814fa 100644 --- a/tests/test_xtb_calc.py +++ b/tests/test_xtb_calc.py @@ -6,7 +6,7 @@ from autode.wrappers.XTB import XTB from autode.calculation import Calculation from autode.species.molecule import Molecule from autode.point_charges import PointCharge -from autode.exceptions import AtomsNotFound +from autode.exceptions import AtomsNotFound, CalculationException from autode.config import Config from . import testutils @@ -75,7 +75,9 @@ def test_energy_extract_no_energy(): calc.output.filename = 'h2_sp_xtb_no_energy.out' assert calc.terminated_normally - assert calc.get_energy() is None + + with pytest.raises(CalculationException): + _ = calc.get_energy() @testutils.work_in_zipped_dir(os.path.join(here, 'data', 'xtb.zip'))
Inconsistent Calculation behaviour **Possible API Improvement** Currently with a [Calculation](https://github.com/duartegroup/autodE/blob/6505d5bbbd1906f57e4102e13f177510f166bbed/autode/calculation.py#L61) `calc.get_energy()` returns None if a calculation failed but raises a `CalculationError` for e.g. `calc.get_gradients()`; this is not particularly consistent or user friendly. Having talked it over with @tristan-j-wood having properties (e.g. `calc.energy`) that are set after `calc.run()`, and may be None (after throwing a logging error), would be easier and more consistent with the rest of the API. Also having access to the calc.molecule properties directly e.g. ```python class Molecule: def __init__(self, x): self.x = x class Calculation: def __getattr__(self, item): if item in self.molecule.__dict__: return self.molecule.__dict__[item] return self.__dict__[item] def __init__(self, molecule): self.molecule = molecule if __name__ == '__main__': calc = Calculation(molecule=Molecule(x=1)) print(calc.x) # -> 1 calc.x = 2 print(calc.x) # -> 2 ``` would be more readable. Also should throw more useful exceptions if calculations are initialised but not run before getting a property.
0.0
421ceaad5d424055d4dbf5986ee213e505e0a615
[ "tests/test_calculation.py::test_calc_class", "tests/test_gaussian_calc.py::test_bad_gauss_output", "tests/test_mopac_calc.py::test_bad_geometry", "tests/test_orca_calc.py::test_bad_orca_output", "tests/test_xtb_calc.py::test_energy_extract_no_energy" ]
[ "tests/test_calculation.py::test_calc_copy", "tests/test_calculation.py::test_clear_output", "tests/test_calculation.py::test_distance_const_check", "tests/test_calculation.py::test_calc_string", "tests/test_calculation.py::test_fix_unique", "tests/test_calculation.py::test_solvent_get", "tests/test_calculation.py::test_input_gen", "tests/test_calculation.py::test_exec_not_avail_method", "tests/test_gaussian_calc.py::test_printing_ecp", "tests/test_gaussian_calc.py::test_add_opt_option", "tests/test_gaussian_calc.py::test_input_print_max_opt", "tests/test_gaussian_calc.py::test_get_gradients", "tests/test_gaussian_calc.py::test_gauss_opt_calc", "tests/test_gaussian_calc.py::test_gauss_optts_calc", "tests/test_gaussian_calc.py::test_fix_angle_error", "tests/test_gaussian_calc.py::test_constraints", "tests/test_gaussian_calc.py::test_single_atom_opt", "tests/test_gaussian_calc.py::test_point_charge_calc", "tests/test_gaussian_calc.py::test_external_basis_set_file", "tests/test_gaussian_calc.py::test_xtb_optts", "tests/test_mopac_calc.py::test_mopac_opt_calculation", "tests/test_mopac_calc.py::test_mopac_with_pc", "tests/test_mopac_calc.py::test_other_spin_states", "tests/test_mopac_calc.py::test_constrained_opt", "tests/test_mopac_calc.py::test_grad", "tests/test_mopac_calc.py::test_termination_short", "tests/test_mopac_calc.py::test_mopac_keywords", "tests/test_mopac_calc.py::test_get_version_no_output", "tests/test_mopac_calc.py::test_mopac_solvent_no_dielectric", "tests/test_orca_calc.py::test_orca_opt_calculation", "tests/test_orca_calc.py::test_calc_bad_mol", "tests/test_orca_calc.py::test_orca_optts_calculation", "tests/test_orca_calc.py::test_solvation", "tests/test_orca_calc.py::test_gradients", "tests/test_orca_calc.py::test_mp2_numerical_gradients", "tests/test_orca_calc.py::test_keyword_setting", "tests/test_orca_calc.py::test_hessian_extraction", "tests/test_orca_calc.py::test_other_input_block", "tests/test_xtb_calc.py::test_xtb_calculation", "tests/test_xtb_calc.py::test_point_charge", "tests/test_xtb_calc.py::test_gradients", "tests/test_xtb_calc.py::test_xtb_6_3_2", "tests/test_xtb_calc.py::test_xtb_6_1_old" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-19 09:22:10+00:00
mit
2,011
duartegroup__autodE-140
diff --git a/autode/__init__.py b/autode/__init__.py index cb84893..e18739b 100644 --- a/autode/__init__.py +++ b/autode/__init__.py @@ -33,7 +33,7 @@ So, you want to bump the version.. make sure the following steps are followed - Merge when tests pass """ -__version__ = '1.2.2' +__version__ = '1.2.3' __all__ = [ diff --git a/autode/reactions/reaction.py b/autode/reactions/reaction.py index 9cc605f..63a0d99 100644 --- a/autode/reactions/reaction.py +++ b/autode/reactions/reaction.py @@ -75,6 +75,7 @@ class Reaction: self._check_solvent() self._check_balance() + self._check_names() def __str__(self): """Return a very short 6 character hash of the reaction, not guaranteed @@ -147,7 +148,7 @@ class Reaction: enthalpy=enthalpy) return None - def _check_balance(self): + def _check_balance(self) -> None: """Check that the number of atoms and charge balances between reactants and products. If they don't then raise excpetions """ @@ -170,7 +171,7 @@ class Reaction: self.charge = total(self.reacs, 'charge') return None - def _check_solvent(self): + def _check_solvent(self) -> None: """ Check that all the solvents are the same for reactants and products. If self.solvent is set then override the reactants and products @@ -207,7 +208,28 @@ class Reaction: f'{self.solvent.name}') return None - def _init_from_smiles(self, reaction_smiles): + def _check_names(self) -> None: + """ + Ensure there is no clashing names of reactants and products, which will + cause problems when conformers are generated and output is printed + """ + all_names = [mol.name for mol in self.reacs + self.prods] + + if len(set(all_names)) == len(all_names): # Everything is unique + return + + logger.warning('Names in reactants and products are not unique. ' + 'Adding prefixes') + + for i, reac in enumerate(self.reacs): + reac.name = f'r{i}_{reac.name}' + + for i, prod in enumerate(self.prods): + prod.name = f'p{i}_{prod.name}' + + return None + + def _init_from_smiles(self, reaction_smiles) -> None: """ Initialise from a SMILES string of the whole reaction e.g.:: @@ -237,7 +259,7 @@ class Reaction: return None - def _init_from_molecules(self, molecules): + def _init_from_molecules(self, molecules) -> None: """Set the reactants and products from a set of molecules""" self.reacs = [mol for mol in molecules @@ -248,7 +270,7 @@ class Reaction: return None - def _reasonable_components_with_energy(self): + def _reasonable_components_with_energy(self) -> None: """Generator for components of a reaction that have sensible geometries and also energies""" diff --git a/doc/changelog.rst b/doc/changelog.rst index ec75310..3449692 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -2,6 +2,18 @@ Changelog ========= +1.2.3 +-------- +---------- + +Bugfix release. + + +Bug Fixes +********* +- Fixes clashing names for a reaction initialised explicitly from molecules without defined names + + 1.2.2 -------- ---------- diff --git a/setup.py b/setup.py index 9c0e649..70729e8 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ extensions = [Extension('cconf_gen', ['autode/conformers/cconf_gen.pyx']), extra_link_args=["-std=c++11"])] setup(name='autode', - version='1.2.2', + version='1.2.3', packages=['autode', 'autode.conformers', 'autode.pes', @@ -44,5 +44,4 @@ setup(name='autode', url='https://github.com/duartegroup/autodE', license='MIT', author='Tom Young', - author_email='[email protected]', - description='Automated Reaction Profile Generation') + description='Automated reaction profile generation')
duartegroup/autodE
239d9fb8f18e9c2ad988757c4ebd0ea982d0e36f
diff --git a/tests/test_reaction_class.py b/tests/test_reaction_class.py index 2d2c023..5c10f57 100644 --- a/tests/test_reaction_class.py +++ b/tests/test_reaction_class.py @@ -464,3 +464,11 @@ def test_same_composition(): r3 = reaction.Reaction(Reactant(name='h2', atoms=[Atom('H', 1.0, 0.0, 0.0)]), Product(name='h2', atoms=[Atom('H', 1.0, 0.0, 0.0)])) assert not r1.has_identical_composition_as(r3) + + +def test_name_uniqueness(): + + rxn = reaction.Reaction(Reactant(smiles='CC[C]([H])[H]'), + Product(smiles='C[C]([H])C')) + + assert rxn.reacs[0].name != rxn.prods[0].name
Sum formulas as filenames lead to overwritten structures in isomerizations **Describe the bug** Hi there. In the output folder, file names are given as sum formulas. This creates issues as soon as we look into isomerizations. In the csv file there is no way of telling which of the identically labelled line is what. But much more problematic: both in "reactants_and_products" and in "output" only one set of calculations/one structure will get saved. A quick hotfix would be to check initally if several molecules of the same sum formula exist and add a "b" or a "_1" or something to all filenames. **To Reproduce** This will happen also in the example that is given in the Github manual. ``` import autode as ade ade.Config.n_cores = 8 r = ade.Reactant(name='reactant', smiles='CC[C]([H])[H]') p = ade.Product(name='product', smiles='C[C]([H])C') reaction = ade.Reaction(r, p, name='1-2_shift') reaction.calculate_reaction_profile() # creates 1-2_shift/ and saves profile ``` Expected behavior Saving all calculations and structures, ideally in a distinguishable fashion. Environment Operating System: CentOS-7 Python version: 3.9.10 autodE version: 1.2.1
0.0
239d9fb8f18e9c2ad988757c4ebd0ea982d0e36f
[ "tests/test_reaction_class.py::test_name_uniqueness" ]
[ "tests/test_reaction_class.py::test_reaction_class", "tests/test_reaction_class.py::test_reactant_product_complexes", "tests/test_reaction_class.py::test_invalid_with_complexes", "tests/test_reaction_class.py::test_check_rearrangement", "tests/test_reaction_class.py::test_check_solvent", "tests/test_reaction_class.py::test_reaction_identical_reac_prods", "tests/test_reaction_class.py::test_swap_reacs_prods", "tests/test_reaction_class.py::test_bad_balance", "tests/test_reaction_class.py::test_calc_delta_e", "tests/test_reaction_class.py::test_from_smiles", "tests/test_reaction_class.py::test_single_points", "tests/test_reaction_class.py::test_free_energy_profile", "tests/test_reaction_class.py::test_barrierless_rearrangment", "tests/test_reaction_class.py::test_doc_example", "tests/test_reaction_class.py::test_barrierless_h_g", "tests/test_reaction_class.py::test_same_composition" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-05-18 14:39:11+00:00
mit
2,012
duartegroup__autodE-185
diff --git a/autode/transition_states/ts_guess.py b/autode/transition_states/ts_guess.py index 97df5f5..3516d20 100644 --- a/autode/transition_states/ts_guess.py +++ b/autode/transition_states/ts_guess.py @@ -136,10 +136,13 @@ class TSguess(TSbase): (autode.transition_states.ts_guess.TSguess): TS guess """ - ts_guess = cls(atoms=species.atoms, - charge=species.charge, - mult=species.mult, - name=f'ts_guess_{species.name}') + ts_guess = cls( + atoms=species.atoms, + charge=species.charge, + mult=species.mult, + name=f'ts_guess_{species.name}', + solvent_name=None if species.solvent is None else species.solvent.name + ) return ts_guess
duartegroup/autodE
88a5fc08246de5c8034fedfb9d8a9376a2c8cea2
diff --git a/tests/test_ts/test_ts_guess.py b/tests/test_ts/test_ts_guess.py new file mode 100644 index 0000000..9f90d45 --- /dev/null +++ b/tests/test_ts/test_ts_guess.py @@ -0,0 +1,12 @@ +from autode.atoms import Atom +from autode.species.molecule import Molecule +from autode.transition_states.ts_guess import TSguess + + +def test_that_a_molecules_solvent_is_inherited(): + + mol = Molecule(atoms=[Atom("H")], mult=2, solvent_name="water") + assert mol.solvent.smiles == "O" + + ts_guess = TSguess.from_species(mol) + assert ts_guess.solvent.smiles == "O"
TSguess.from_species does not inherit solvent
0.0
88a5fc08246de5c8034fedfb9d8a9376a2c8cea2
[ "tests/test_ts/test_ts_guess.py::test_that_a_molecules_solvent_is_inherited" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-10-17 17:44:05+00:00
mit
2,013
duartegroup__autodE-213
diff --git a/autode/__init__.py b/autode/__init__.py index eff4ba3..0a1dd63 100644 --- a/autode/__init__.py +++ b/autode/__init__.py @@ -38,7 +38,7 @@ Bumping the version number requires following the release proceedure: - Merge when tests pass """ -__version__ = "1.3.3" +__version__ = "1.3.4" __all__ = [ diff --git a/autode/transition_states/templates.py b/autode/transition_states/templates.py index 3bea0e8..5bb77e1 100644 --- a/autode/transition_states/templates.py +++ b/autode/transition_states/templates.py @@ -38,6 +38,11 @@ def get_ts_template_folder_path(folder_path): logger.info("Folder path is not set – TS templates in the default path") + if Config.ts_template_folder_path == "": + raise ValueError( + "Cannot set ts_template_folder_path to an empty string" + ) + if Config.ts_template_folder_path is not None: logger.info("Configuration ts_template_folder_path is set") return Config.ts_template_folder_path diff --git a/doc/changelog.rst b/doc/changelog.rst index 8376c45..3097412 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,26 @@ Changelog ========= +1.3.4 +-------- +---------- + +Feature additions. + +Usability improvements/Changes +****************************** +* Throw useful exception for invalid :code:`ade.Config.ts_template_folder_path` + + +Functionality improvements +************************** +- + +Bug Fixes +********* +- + + 1.3.3 -------- ---------- diff --git a/setup.py b/setup.py index b8206c6..ddfe8d1 100644 --- a/setup.py +++ b/setup.py @@ -24,7 +24,7 @@ extensions = [ setup( name="autode", - version="1.3.3", + version="1.3.4", python_requires=">3.7", packages=[ "autode",
duartegroup/autodE
e2b90c0750b2913f2a0df4d274ce58f232894bac
diff --git a/tests/test_config.py b/tests/test_config.py index a0791d2..338a22a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,6 +5,7 @@ from autode.config import Config from autode.values import Allocation, Distance from autode.wrappers.keywords import KeywordsSet from autode.wrappers.keywords import Keywords +from autode.transition_states.templates import get_ts_template_folder_path def test_config(): @@ -76,3 +77,13 @@ def test_step_size_setter(): # Setting in Bohr should convert to angstroms _config.max_step_size = Distance(0.2, units="a0") assert np.isclose(_config.max_step_size.to("ang"), 0.1, atol=0.02) + + +def test_invalid_get_ts_template_folder_path(): + + Config.ts_template_folder_path = "" + + with pytest.raises(ValueError): + _ = get_ts_template_folder_path(None) + + Config.ts_template_folder_path = None
Throw useful exception if `ade.Config.ts_template_folder_path = ""`
0.0
e2b90c0750b2913f2a0df4d274ce58f232894bac
[ "tests/test_config.py::test_invalid_get_ts_template_folder_path" ]
[ "tests/test_config.py::test_config", "tests/test_config.py::test_maxcore_setter", "tests/test_config.py::test_invalid_freq_scale_factor[-0.1]", "tests/test_config.py::test_invalid_freq_scale_factor[1.1]", "tests/test_config.py::test_invalid_freq_scale_factor[a", "tests/test_config.py::test_unknown_attr", "tests/test_config.py::test_step_size_setter" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-10 19:44:06+00:00
mit
2,014
duartegroup__autodE-214
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5ca80c4..5ed79b8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,4 +4,3 @@ repos: hooks: - id: black language_version: python3.9 - diff --git a/autode/__init__.py b/autode/__init__.py index 0a1dd63..5789c25 100644 --- a/autode/__init__.py +++ b/autode/__init__.py @@ -7,6 +7,7 @@ from autode import mol_graphs from autode import hessians from autode.reactions.reaction import Reaction from autode.reactions.multistep import MultiStepReaction +from autode.transition_states.transition_state import TransitionState from autode.atoms import Atom from autode.species.molecule import Reactant, Product, Molecule, Species from autode.species.complex import NCIComplex @@ -55,6 +56,7 @@ __all__ = [ "Reactant", "Product", "Molecule", + "TransitionState", "NCIComplex", "Config", "Calculation", diff --git a/autode/transition_states/base.py b/autode/transition_states/base.py index 6ce9b99..7011a6d 100644 --- a/autode/transition_states/base.py +++ b/autode/transition_states/base.py @@ -4,6 +4,7 @@ from typing import Optional import autode.exceptions as ex from autode.atoms import metals from autode.config import Config +from autode.geom import calc_rmsd from autode.constraints import DistanceConstraints from autode.log import logger from autode.methods import get_hmethod, get_lmethod @@ -74,8 +75,11 @@ class TSbase(Species, ABC): def __eq__(self, other): """Equality of this TS base to another""" - logger.warning("TSs types are not equal to any others") - return False + return ( + isinstance(other, TSbase) + and calc_rmsd(self.coordinates, other.coordinates) < 1e-6, + super().__eq__(other), + ) def _init_graph(self) -> None: """Set the molecular graph for this TS object from the reactant""" diff --git a/autode/transition_states/transition_state.py b/autode/transition_states/transition_state.py index 80a17fc..e42d844 100644 --- a/autode/transition_states/transition_state.py +++ b/autode/transition_states/transition_state.py @@ -3,6 +3,7 @@ from multiprocessing import Pool from autode.values import Frequency from autode.transition_states.base import displaced_species_along_mode from autode.transition_states.base import TSbase +from autode.transition_states.ts_guess import TSguess from autode.transition_states.templates import TStemplate from autode.input_output import atoms_to_xyz_file from autode.calculations import Calculation @@ -358,3 +359,20 @@ class TransitionState(TSbase): logger.info("Saved TS template") return None + + @classmethod + def from_species( + cls, species: "autode.species.Species" + ) -> "TransitionState": + """ + Generate a TS from a species. Note this does not set the bond rearrangement + thus mode checking will not work from this species. + + ----------------------------------------------------------------------- + Arguments: + species: + + Returns: + (autode.transition_states.transition_state.TransitionState): TS + """ + return cls(ts_guess=TSguess.from_species(species), bond_rearr=None) diff --git a/doc/changelog.rst b/doc/changelog.rst index 3097412..a56aa8f 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -14,7 +14,8 @@ Usability improvements/Changes Functionality improvements ************************** -- +- Adds :code:`ade.transition_states.TransitionState.from_species` method to construct transition states from a species or molecule + Bug Fixes *********
duartegroup/autodE
af3daeed187203b7f037d2c818d39d65b1c513a1
diff --git a/tests/test_ts/test_ts_template.py b/tests/test_ts/test_ts_template.py index ede99ad..f0443c6 100644 --- a/tests/test_ts/test_ts_template.py +++ b/tests/test_ts/test_ts_template.py @@ -5,6 +5,7 @@ from .. import testutils import pytest from autode.exceptions import TemplateLoadingFailed from autode.config import Config +from autode.species.molecule import Molecule from autode.bond_rearrangement import BondRearrangement from autode.species.complex import ReactantComplex, ProductComplex from autode.species.molecule import Reactant, Product @@ -238,3 +239,13 @@ def test_inactive_graph(): template.graph = ch3f.graph.copy() assert not template.graph_has_correct_structure() + + [email protected]_in_zipped_dir(os.path.join(here, "data", "ts_template.zip")) +def test_ts_from_species_is_same_as_from_ts_guess(): + + ts = TransitionState( + TSguess(atoms=xyz_file_to_atoms("vaskas_TS.xyz"), charge=0, mult=1) + ) + + assert TransitionState.from_species(Molecule("vaskas_TS.xyz")) == ts
Implement `ade.TransitionState.from_species()`
0.0
af3daeed187203b7f037d2c818d39d65b1c513a1
[ "tests/test_ts/test_ts_template.py::test_ts_from_species_is_same_as_from_ts_guess" ]
[ "tests/test_ts/test_ts_template.py::test_ts_template_save", "tests/test_ts/test_ts_template.py::test_ts_template", "tests/test_ts/test_ts_template.py::test_ts_template_with_scan", "tests/test_ts/test_ts_template.py::test_truncated_mol_graph_atom_types", "tests/test_ts/test_ts_template.py::test_ts_template_parse", "tests/test_ts/test_ts_template.py::test_ts_templates_find", "tests/test_ts/test_ts_template.py::test_inactive_graph" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-11 17:29:16+00:00
mit
2,015
duartegroup__autodE-242
diff --git a/autode/values.py b/autode/values.py index dcf4c09..295444d 100644 --- a/autode/values.py +++ b/autode/values.py @@ -62,7 +62,7 @@ def _to(value: Union["Value", "ValueArray"], units: Union[Unit, str]): except StopIteration: raise TypeError( - f"No viable unit conversion from {value.units} " f"-> {units}" + f"No viable unit conversion from {value.units} -> {units}" ) # Convert to the base unit, then to the new units @@ -214,16 +214,22 @@ class Value(ABC, float): float(self) + self._other_same_units(other), units=self.units ) - def __mul__(self, other) -> "Value": + def __mul__(self, other) -> Union[float, "Value"]: """Multiply this value with another""" if isinstance(other, np.ndarray): return other * float(self) + if isinstance(other, Value): + logger.warning( + "Multiplying autode.Value returns a float with no units" + ) + return float(self) * self._other_same_units(other) + return self.__class__( float(self) * self._other_same_units(other), units=self.units ) - def __rmul__(self, other) -> "Value": + def __rmul__(self, other) -> Union[float, "Value"]: return self.__mul__(other) def __radd__(self, other) -> "Value": @@ -232,16 +238,19 @@ class Value(ABC, float): def __sub__(self, other) -> "Value": return self.__add__(-other) - def __floordiv__(self, other): - raise NotImplementedError( - "Integer division is not supported by " "autode.values.Value" - ) + def __floordiv__(self, other) -> Union[float, "Value"]: + x = float(self) // self._other_same_units(other) + if isinstance(other, Value): + return x - def __truediv__(self, other) -> "Value": - return self.__class__( - float(self) / float(self._other_same_units(other)), - units=self.units, - ) + return self.__class__(x, units=self.units) + + def __truediv__(self, other) -> Union[float, "Value"]: + x = float(self) / self._other_same_units(other) + if isinstance(other, Value): + return x + + return self.__class__(x, units=self.units) def __abs__(self) -> "Value": """Absolute value""" diff --git a/doc/changelog.rst b/doc/changelog.rst index ab9c69a..8303c13 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -19,6 +19,8 @@ Functionality improvements Bug Fixes ********* - Fixes :code:`ERROR` logging level being ignored from environment variable :code:`AUTODE_LOG_LEVEL` +- Fixes :code:`autode.values.Value` instances generating items with units on division, and throw a warning if multiplying + 1.3.4 --------
duartegroup/autodE
c37322ca5aafee0297c7aed3238d1dbad996f564
diff --git a/tests/test_value.py b/tests/test_value.py index 924939e..d2d23a0 100644 --- a/tests/test_value.py +++ b/tests/test_value.py @@ -266,3 +266,15 @@ def test_to_wrong_type(): with pytest.raises(Exception): _to(Tmp(), units="Å") + + +def test_div_mul_generate_floats(): + + e = PotentialEnergy(1.0) + assert isinstance(e / e, float) + assert isinstance(e // e, float) + + assert e // e == 1 + + # Note: this behaviour is not ideal. But it is better than having the wrong units + assert isinstance(e * e, float)
Division and multiplication of `autode.values.Value` creates wrong units **Describe the bug** <!-- A clear and concise description of what the bug is. --> Multiplication and division do not generate autode.values with the correct units. As a simple fix multiplication could return a float, given it's (potentially) an uncommon occurrence. **To Reproduce** <!-- Steps to reproduce the behaviour: code with output --> ```python >>> import autode as ade >>> e = ade.values.PotentialEnergy(1) >>> e Energy(1.0 Ha) >>> e * e Energy(1.0 Ha) >>> e / e Energy(1.0 Ha) >>> # Addition and subtraction are okay >>> e + e Energy(2.0 Ha) >>> e - e Energy(0.0 Ha) ``` **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> Division results in no units and multiplication Ha^2 **Environment** <!-- please complete the following information. --> - autodE version: 1.3.4
0.0
c37322ca5aafee0297c7aed3238d1dbad996f564
[ "tests/test_value.py::test_div_mul_generate_floats" ]
[ "tests/test_value.py::test_base_value", "tests/test_value.py::test_base_value_numpy_add", "tests/test_value.py::test_energy", "tests/test_value.py::test_energy_equality", "tests/test_value.py::test_enthalpy", "tests/test_value.py::test_free_energy", "tests/test_value.py::test_distance", "tests/test_value.py::test_angle", "tests/test_value.py::test_energies", "tests/test_value.py::test_freqs", "tests/test_value.py::test_mass", "tests/test_value.py::test_contrib_guidelines", "tests/test_value.py::test_gradient_norm", "tests/test_value.py::test_to_wrong_type" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-29 15:26:48+00:00
mit
2,016
duartegroup__autodE-243
diff --git a/autode/hessians.py b/autode/hessians.py index b3f6149..4b8cc76 100644 --- a/autode/hessians.py +++ b/autode/hessians.py @@ -234,9 +234,9 @@ class Hessian(ValueArray): axis=np.newaxis, ) - return Hessian( - H / np.sqrt(np.outer(mass_array, mass_array)), units="J m^-2 kg^-1" - ) + return np.array( + H / np.sqrt(np.outer(mass_array, mass_array)) + ) # J Å^-2 kg^-1 @cached_property def _proj_mass_weighted(self) -> np.ndarray: diff --git a/autode/units.py b/autode/units.py index 8f18818..4b30a1d 100644 --- a/autode/units.py +++ b/autode/units.py @@ -211,15 +211,15 @@ kg_m_sq = CompositeUnit(kg, m, m, name="kg m^2") ha_per_ang = CompositeUnit( - ha, per=[ang], aliases=["ha Å-1", "ha Å^-1", "ha/ang"] + ha, per=[ang], aliases=["ha / Å", "ha Å-1", "ha Å^-1", "ha/ang"] ) ha_per_a0 = CompositeUnit( - ha, per=[a0], aliases=["ha a0-1", "ha a0^-1", "ha/bohr"] + ha, per=[a0], aliases=["ha / a0", "ha a0-1", "ha a0^-1", "ha/bohr"] ) ev_per_ang = CompositeUnit( - ev, per=[ang], aliases=["ha a0-1", "ev Å^-1", "ev/ang"] + ev, per=[ang], aliases=["ev / Å", "ev Å^-1", "ev/ang"] ) kcalmol_per_ang = CompositeUnit( diff --git a/autode/values.py b/autode/values.py index 295444d..77fc41c 100644 --- a/autode/values.py +++ b/autode/values.py @@ -37,9 +37,12 @@ from autode.units import ( ) -def _to(value: Union["Value", "ValueArray"], units: Union[Unit, str]): +def _to( + value: Union["Value", "ValueArray"], units: Union[Unit, str], inplace: bool +) -> Any: """ - Convert a value or value array to a new unit and return a copy + Convert a value or value array to a new unit and return a copy if + inplace=False --------------------------------------------------------------------------- Arguments: @@ -65,23 +68,26 @@ def _to(value: Union["Value", "ValueArray"], units: Union[Unit, str]): f"No viable unit conversion from {value.units} -> {units}" ) - # Convert to the base unit, then to the new units - c = float(units.conversion / value.units.conversion) - - if isinstance(value, Value): - return value.__class__(float(value) * c, units=units) - - elif isinstance(value, ValueArray): - value[:] = np.array(value, copy=True) * c - value.units = units - return value - - else: + if not (isinstance(value, Value) or isinstance(value, ValueArray)): raise ValueError( f"Cannot convert {value} to new units. Must be one of" f" Value of ValueArray" ) + if isinstance(value, Value) and inplace: + raise ValueError( + "Cannot modify a value inplace as floats are immutable" + ) + + # Convert to the base unit, then to the new units + c = float(units.conversion / value.units.conversion) + + new_value = value if inplace else value.copy() + new_value *= c + new_value.units = units + + return None if inplace else new_value + def _units_init(value, units: Union[Unit, str, None]): """Initialise the units of this value @@ -171,6 +177,11 @@ class Value(ABC, float): return other.to(self.units) + def _like_self_from_float(self, value: float) -> "Value": + new_value = self.__class__(value, units=self.units) + new_value.__dict__.update(self.__dict__) + return new_value + def __eq__(self, other) -> bool: """Equality of two values, which may be in different units""" @@ -210,8 +221,8 @@ class Value(ABC, float): if isinstance(other, np.ndarray): return other + float(self) - return self.__class__( - float(self) + self._other_same_units(other), units=self.units + return self._like_self_from_float( + float(self) + self._other_same_units(other) ) def __mul__(self, other) -> Union[float, "Value"]: @@ -225,8 +236,8 @@ class Value(ABC, float): ) return float(self) * self._other_same_units(other) - return self.__class__( - float(self) * self._other_same_units(other), units=self.units + return self._like_self_from_float( + float(self) * self._other_same_units(other) ) def __rmul__(self, other) -> Union[float, "Value"]: @@ -240,17 +251,11 @@ class Value(ABC, float): def __floordiv__(self, other) -> Union[float, "Value"]: x = float(self) // self._other_same_units(other) - if isinstance(other, Value): - return x - - return self.__class__(x, units=self.units) + return x if isinstance(other, Value) else self._like_self_from_float(x) def __truediv__(self, other) -> Union[float, "Value"]: x = float(self) / self._other_same_units(other) - if isinstance(other, Value): - return x - - return self.__class__(x, units=self.units) + return x if isinstance(other, Value) else self._like_self_from_float(x) def __abs__(self) -> "Value": """Absolute value""" @@ -269,7 +274,7 @@ class Value(ABC, float): Raises: (TypeError): """ - return _to(self, units) + return _to(self, units, inplace=False) class Energy(Value): @@ -652,7 +657,21 @@ class ValueArray(ABC, np.ndarray): Raises: (TypeError): """ - return _to(self, units) + return _to(self, units, inplace=False) + + def to_(self, units) -> None: + """ + Convert this array into a set of new units, inplace. This will not copy + the array + + ----------------------------------------------------------------------- + Returns: + (None) + + Raises: + (TypeError): + """ + _to(self, units, inplace=True) def __array_finalize__(self, obj): """See https://numpy.org/doc/stable/user/basics.subclassing.html""" diff --git a/doc/changelog.rst b/doc/changelog.rst index d6144a7..23be882 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -8,12 +8,12 @@ Changelog Usability improvements/Changes ****************************** -* +- :code:`autode.value.ValueArray.to()` now defaults to copying the object rather than inplace modification Functionality improvements ************************** -- +- Adds a :code:`to_` method to :code:`autode.value.ValueArray` for explicit inplace modification of the array Bug Fixes @@ -21,6 +21,8 @@ Bug Fixes - Fixes :code:`ERROR` logging level being ignored from environment variable :code:`AUTODE_LOG_LEVEL` - Fixes :code:`autode.values.Value` instances generating items with units on division, and throw a warning if multiplying - Fixes the printing of cartesian constraints in XTB input files, meaning they are no longer ignored +- Fixes :code:`Hessian` instances changing units when normal modes are calculated +- Fixes an incorrect alias for :code:`ev_per_ang` 1.3.4 @@ -32,7 +34,6 @@ Feature additions. Usability improvements/Changes ****************************** * Throw useful exception for invalid :code:`ade.Config.ts_template_folder_path` -* Adds the reaction temperature to the unique reaction hash Functionality improvements @@ -44,7 +45,7 @@ Functionality improvements Bug Fixes ********* -- +- Fixes calculation :code:`clean_up()` failing with a null filename 1.3.3
duartegroup/autodE
4276cabb57a7d8fddace6f95de43217c9a9fda3e
diff --git a/tests/test_hessian.py b/tests/test_hessian.py index c611c22..554a4c2 100644 --- a/tests/test_hessian.py +++ b/tests/test_hessian.py @@ -13,7 +13,7 @@ from autode.calculations import Calculation from autode.species import Molecule from autode.values import Frequency from autode.geom import calc_rmsd -from autode.units import wavenumber +from autode.units import wavenumber, ha_per_ang_sq from autode.exceptions import CalculationException from autode.wrappers.keywords import pbe0 from autode.transition_states.base import displaced_species_along_mode @@ -243,6 +243,7 @@ def assert_correct_co2_frequencies(hessian, expected=(666, 1415, 2517)): """Ensure the projected frequencies of CO2 are roughly right""" nu_1, nu_2, nu_3 = expected + print(hessian.frequencies_proj) assert sum(freq == 0.0 for freq in hessian.frequencies_proj) == 5 # Should have a degenerate bending mode for CO2 with ν = 666 cm-1 @@ -419,6 +420,7 @@ def test_hessian_modes(): h2o = Molecule("H2O_hess_orca.xyz") h2o.hessian = h2o_hessian_arr + assert h2o.hessian.units == ha_per_ang_sq # The structure is a minimum, thus there should be no imaginary frequencies assert h2o.imaginary_frequencies is None @@ -441,6 +443,9 @@ def test_hessian_modes(): vib_mode, h2o.hessian.normal_modes[6 + i], atol=0.1 ) or np.allclose(vib_mode, -h2o.hessian.normal_modes[6 + i], atol=0.1) + # Hessian units should be retained + assert h2o.hessian.units == ha_per_ang_sq + @testutils.work_in_zipped_dir(os.path.join(here, "data", "hessians.zip")) def test_proj_modes(): @@ -595,6 +600,8 @@ def test_nwchem_hessian_co2(): keywords=ade.HessianKeywords(), ) calc.set_output_filename("CO2_hess_nwchem.out") + print(co2.hessian) + print(co2.hessian._mass_weighted) assert_correct_co2_frequencies( hessian=co2.hessian, expected=(659.76, 1406.83, 2495.73) ) diff --git a/tests/test_value.py b/tests/test_value.py index d2d23a0..cf115e9 100644 --- a/tests/test_value.py +++ b/tests/test_value.py @@ -3,6 +3,7 @@ import numpy as np from autode.constants import Constants from autode.units import ha, kjmol, kcalmol, ev, ang, a0, nm, pm, m, rad, deg from autode.values import ( + _to, Value, Distance, MWDistance, @@ -278,3 +279,25 @@ def test_div_mul_generate_floats(): # Note: this behaviour is not ideal. But it is better than having the wrong units assert isinstance(e * e, float) + + +def test_operations_maintain_other_attrs(): + + e = Energy(1, estimated=True, units="eV") + assert e.is_estimated and e.units == ev + + e *= 2 + assert e.is_estimated and e.units == ev + + e /= 2 + assert e.is_estimated and e.units == ev + + a = e * 2 + assert a.is_estimated and e.units == ev + + +def test_inplace_value_modification_raises(): + + e = Energy(1, units="Ha") + with pytest.raises(ValueError): # floats are immutable + _to(e, units="eV", inplace=True) diff --git a/tests/test_values.py b/tests/test_values.py index cac6882..dd80591 100644 --- a/tests/test_values.py +++ b/tests/test_values.py @@ -106,4 +106,22 @@ class InvalidValue(float): def test_to_unsupported(): with pytest.raises(ValueError): - _ = _to(InvalidValue(), Unit()) + _ = _to(InvalidValue(), Unit(), inplace=True) + + +def test_inplace_modification(): + + x = Gradient([[1.0, 1.0, 1.0]], units="Ha / Å") + return_value = x.to_("eV / Å") + assert return_value is None + + assert not np.allclose(x, np.ones(shape=(1, 3))) + + +def test_copy_conversion(): + + x = Gradient([[1.0, 1.0, 1.0]], units="Ha / Å") + y = x.to("eV / Å") + + assert not np.allclose(x, y) + assert np.allclose(x, np.ones(shape=(1, 3)))
Using autodE in Interactive python shell causes unusual change in units Only seen from interactive python shell. ```python >>> import autode as ade >>> mol = ade.Molecule(smiles='CCO') >>> mol.calc_hessian(method=ade.methods.XTB(),n_cores=6) >>> mol.hessian.units Unit(Ha Å^-2) >>> mol.hessian. # pressing tab twice to get all visible attributes mol.hessian.T mol.hessian.min( mol.hessian.all( mol.hessian.n_tr mol.hessian.any( mol.hessian.n_v mol.hessian.argmax( mol.hessian.nbytes mol.hessian.argmin( mol.hessian.ndim ... # wall of text hidden >>> mol.hessian.units # units changed magically from Ha/ang^2 to Joule/ang^2? Unit(J ang^-2) ``` I have looked at the values in the Hessian and the units really do change. (i.e. the numbers change as well) I am not quite sure why this is happening. But it would be problematic if the units changed randomly in the middle of calculations. **Environment** - Operating System: MacOS 12.6 - Python version: Python 3.10 - autodE version: 1.3.4
0.0
4276cabb57a7d8fddace6f95de43217c9a9fda3e
[ "tests/test_hessian.py::test_hessian_modes", "tests/test_value.py::test_operations_maintain_other_attrs", "tests/test_value.py::test_inplace_value_modification_raises", "tests/test_values.py::test_to_unsupported", "tests/test_values.py::test_inplace_modification", "tests/test_values.py::test_copy_conversion" ]
[ "tests/test_hessian.py::test_hessian_class", "tests/test_hessian.py::test_hessian_set", "tests/test_hessian.py::test_hessian_freqs", "tests/test_hessian.py::test_hessian_scaled_freqs", "tests/test_hessian.py::test_hessian_scale_factor", "tests/test_hessian.py::test_proj_modes", "tests/test_hessian.py::test_hessian_linear_freqs", "tests/test_hessian.py::test_gaussian_hessian_extract_h2", "tests/test_hessian.py::test_gaussian_hessian_extract_co2", "tests/test_hessian.py::test_nwchem_hessian_extract_h2o", "tests/test_hessian.py::test_nwchem_hessian_co2", "tests/test_hessian.py::test_imag_mode", "tests/test_hessian.py::test_extract_wrong_molecule_hessian", "tests/test_hessian.py::test_num_hess_invalid_input", "tests/test_hessian.py::test_h2_hessian", "tests/test_hessian.py::test_h2_c_diff_hessian", "tests/test_hessian.py::test_h2_xtb_vs_orca_hessian", "tests/test_hessian.py::test_ind_num_hess_row", "tests/test_hessian.py::test_partial_num_hess_init", "tests/test_hessian.py::test_partial_water_num_hess", "tests/test_hessian.py::test_numerical_hessian_in_daemon", "tests/test_hessian.py::test_serial_calculation_matches_parallel", "tests/test_hessian.py::test_hessian_pickle_and_unpickle", "tests/test_value.py::test_base_value", "tests/test_value.py::test_base_value_numpy_add", "tests/test_value.py::test_energy", "tests/test_value.py::test_energy_equality", "tests/test_value.py::test_enthalpy", "tests/test_value.py::test_free_energy", "tests/test_value.py::test_distance", "tests/test_value.py::test_angle", "tests/test_value.py::test_energies", "tests/test_value.py::test_freqs", "tests/test_value.py::test_mass", "tests/test_value.py::test_contrib_guidelines", "tests/test_value.py::test_gradient_norm", "tests/test_value.py::test_to_wrong_type", "tests/test_value.py::test_div_mul_generate_floats", "tests/test_values.py::test_base_arr", "tests/test_values.py::test_unit_retention", "tests/test_values.py::test_coordinate", "tests/test_values.py::test_coordinates", "tests/test_values.py::test_moi", "tests/test_values.py::test_gradients" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-29 15:42:53+00:00
mit
2,017
duartegroup__autodE-44
diff --git a/autode/smiles/angles.py b/autode/smiles/angles.py index ffec3bc..0695230 100644 --- a/autode/smiles/angles.py +++ b/autode/smiles/angles.py @@ -250,9 +250,10 @@ class Dihedral(Angle): graph (nx.Graph): atoms (list(autode.atoms.Atom)): """ - return self._find_rot_idxs_from_pair(graph, atoms, pair=self.mid_idxs) + return self._find_rot_idxs_from_pair(graph, atoms, pair=self.mid_idxs, + max_bond_distance=1.5*self.mid_dist) - def __init__(self, idxs, rot_idxs=None, phi0=None): + def __init__(self, idxs, rot_idxs=None, phi0=None, mid_dist=2.0): """ A dihedral constructed from atom indexes and possibly indexes that should be rotated, if this dihedral is altered:: @@ -272,9 +273,13 @@ class Dihedral(Angle): should be rotated else 0 phi0 (float | None): Ideal angle for this dihedral (radians) + + mid_dist (float): Optimum distance between X-Y """ super().__init__(idxs=idxs, rot_idxs=rot_idxs, phi0=phi0) # Atom indexes of the central two atoms (X, Y) _, idx_x, idx_y, _ = idxs + self.mid_idxs = (idx_x, idx_y) + self.mid_dist = mid_dist diff --git a/autode/smiles/builder.py b/autode/smiles/builder.py index baad827..4aa2593 100644 --- a/autode/smiles/builder.py +++ b/autode/smiles/builder.py @@ -300,6 +300,10 @@ class Builder(AtomCollection): dihedral = Dihedral(dihedral_idxs) + # Optimum distance between the two middle atoms, used for + # determining if a bond exists thus a dihedral can be rotated + dihedral.mid_dist = self.bonds.first_involving(*dihedral.mid_idxs).r0 + # If both atoms either side of this one are 'pi' atoms e.g. in a # benzene ring, then the ideal angle must be 0 to close the ring if all(self.atoms[idx].is_pi for idx in dihedral.mid_idxs): diff --git a/autode/smiles/parser.py b/autode/smiles/parser.py index 7a55d71..4eded90 100644 --- a/autode/smiles/parser.py +++ b/autode/smiles/parser.py @@ -40,9 +40,13 @@ class Parser: """Approximate spin multiplicity (2S+1). For multiple unpaired electrons will default to a singlet""" - n_electrons = (sum([atom.atomic_number for atom in self.atoms]) + n_electrons = (sum([at.atomic_number for at in self.atoms]) - self.charge) + # Atoms have implicit hydrogens, so add them + n_electrons += sum(at.n_hydrogens if at.n_hydrogens is not None else 0 + for at in self.atoms) + return (n_electrons % 2) + 1 @property diff --git a/autode/smiles/smiles.py b/autode/smiles/smiles.py index 63d07c2..895e40b 100644 --- a/autode/smiles/smiles.py +++ b/autode/smiles/smiles.py @@ -70,6 +70,8 @@ def init_organic_smiles(molecule, smiles): except RuntimeError: raise RDKitFailed + logger.info('Using RDKit to initialise') + molecule.charge = Chem.GetFormalCharge(rdkit_mol) molecule.mult = calc_multiplicity(molecule, NumRadicalElectrons(rdkit_mol))
duartegroup/autodE
43c7a39be9728b76db6c8a7463413010950e7339
diff --git a/tests/test_smiles_parser.py b/tests/test_smiles_parser.py index 4abdf09..4b5abf9 100644 --- a/tests/test_smiles_parser.py +++ b/tests/test_smiles_parser.py @@ -400,3 +400,11 @@ def test_ring_connectivity(): # and has two carbon-sulfur bonds assert n_c_s_bonds == 2 + + +def test_multiplicity_metals(): + + parser = Parser() + + parser.parse(smiles='[Na]C1=CC=CC=C1') + assert parser.mult == 1
Wrong Multiplicity **Describe the bug** SMILES parser generates the wrong Multiplicity **To Reproduce** import autode as ade ade.Config.n_cores = 28 ade.Config.hcode = 'g16' ade.Config.G16.keywords.set_opt_basis_set('6-31+G(d)') ade.Config.G16.keywords.sp.basis_set = '6-311+G(d,p)' ade.Config.G16.keywords.set_opt_functional('B3LYP') ade.Config.G16.keywords.set_functional('B3LYP') test = ade.Molecule(name='test',smiles='CCC1=CC=C(C=C1)C[Na]') test.print_xyz_file() **Expected behavior** The expected results are as follows INFO Initialisation with SMILES successful. Charge=0, Multiplicity=1, Num. Atoms=21 **Environment** - OS: Unix - Version: 1.0.3 **Additional context** INFO Generating a Molecule object for test INFO Parsing CCC1=CC=C(C=C1)C[Na] INFO Inverting stereochemistry INFO Parsed SMILES in: 0.42 ms INFO Setting 21 atom types INFO Have 1 ring(s) INFO Queue: [1] INFO Queue: [2] INFO Queue: [7, 3] INFO Queue: [3, 6] INFO Queuing Dihedral(idxs=[1, 2, 3, 4], φ0=3.14) INFO Have 1 dihedral(s) to rotate INFO Resetting sites on atom 4 INFO Rotating 3 sites onto 1 points INFO Resetting sites on atom 6 INFO Rotating 3 sites onto 1 points INFO Queue: [6, 4] INFO Queuing Dihedral(idxs=[5, 6, 7, 2], φ0=0) INFO Have 1 dihedral(s) to rotate WARNING Could not apply rotation Dihedral(idxs=[5, 6, 7, 2], φ0=0) INFO Queue: [4, 5] INFO Closing ring on: SMILESBond([4, 5], order=2) and adjusting atoms INFO Adjusting ring dihedrals to close the ring INFO Closed ring in: 1.66 ms INFO A ring was poorly closed - adjusting angles WARNING Closing large rings not implemented WARNING Failed to close a ring, minimising on all atoms INFO Double bond - adding constraint INFO Double bond - adding constraint INFO Double bond - adding constraint INFO Resetting sites on atom 4 INFO Rotating 3 sites onto 2 points INFO Resetting sites on atom 5 INFO Rotating 3 sites onto 2 points INFO Queue: [5] INFO Queuing Dihedral(idxs=[3, 4, 5, 6], φ0=0) INFO Have 1 dihedral(s) to rotate WARNING Could not apply rotation Dihedral(idxs=[3, 4, 5, 6], φ0=0) INFO Queue: [8] INFO Queue: [] INFO Minimising non-bonded repulsion by dihedral rotation INFO Have 1 dihedrals to rotate INFO Performed final dihedral rotation in: 9.02 ms INFO Built 3D in: 63.47 ms INFO Generating molecular graph with NetworkX INFO Generating molecular graph with NetworkX INFO Setting the π bonds in a species INFO Setting the stereocentres in a species WARNING Could not find a valid valance for Na. Guessing at 6 INFO Initialisation with SMILES successful. Charge=0, Multiplicity=2, Num. Atoms=21
0.0
43c7a39be9728b76db6c8a7463413010950e7339
[ "tests/test_smiles_parser.py::test_multiplicity_metals" ]
[ "tests/test_smiles_parser.py::test_base_properties", "tests/test_smiles_parser.py::test_sq_brackets_parser", "tests/test_smiles_parser.py::test_multiple_atoms", "tests/test_smiles_parser.py::test_branches", "tests/test_smiles_parser.py::test_rings", "tests/test_smiles_parser.py::test_aromatic", "tests/test_smiles_parser.py::test_hydrogens", "tests/test_smiles_parser.py::test_cis_trans", "tests/test_smiles_parser.py::test_is_pi_atom", "tests/test_smiles_parser.py::test_implicit_hydrogens", "tests/test_smiles_parser.py::test_multiplicity", "tests/test_smiles_parser.py::test_double_bond_stereo_branch", "tests/test_smiles_parser.py::test_alt_ring_branch", "tests/test_smiles_parser.py::test_ring_connectivity" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-07 09:20:45+00:00
mit
2,018
duartegroup__autodE-77
diff --git a/autode/conformers/conformers.py b/autode/conformers/conformers.py index ef46de0..cda456e 100644 --- a/autode/conformers/conformers.py +++ b/autode/conformers/conformers.py @@ -147,7 +147,7 @@ class Conformers(list): if any(calc_heavy_atom_rmsd(conf.atoms, other.atoms) < rmsd_tol for o_idx, other in enumerate(self) if o_idx != idx): - logger.info(f'Conformer {idx} was close in geometry to at' + logger.info(f'Conformer {idx} was close in geometry to at ' f'least one other - removing') del self[idx] diff --git a/autode/species/complex.py b/autode/species/complex.py index a67efc8..31f7a66 100644 --- a/autode/species/complex.py +++ b/autode/species/complex.py @@ -166,7 +166,7 @@ class Complex(Species): for points in iterprod(points_on_sphere, repeat=n-1): - conf = Conformer(species=self, name=f'{self.name}_conf{n}') + conf = Conformer(species=self, name=f'{self.name}_conf{m}') conf.atoms = get_complex_conformer_atoms(self._molecules, rotations, points) diff --git a/doc/common/water_trimer.py b/doc/common/water_trimer.py index 728b945..22aaea9 100644 --- a/doc/common/water_trimer.py +++ b/doc/common/water_trimer.py @@ -1,12 +1,12 @@ -from autode import Molecule, Config +import autode as ade from autode.species import NCIComplex -from autode.wrappers.XTB import xtb -Config.num_complex_sphere_points = 5 -Config.num_complex_random_rotations = 3 +ade.Config.num_complex_sphere_points = 5 +ade.Config.num_complex_random_rotations = 3 +xtb = ade.methods.XTB() # Make a water molecule and optimise at the XTB level -water = Molecule(name='water', smiles='O') +water = ade.Molecule(name='water', smiles='O') water.optimise(method=xtb) # Make the NCI complex and find the lowest energy structure
duartegroup/autodE
445e96f8477eb41e9a42a7e00c6eedfb24118a86
diff --git a/tests/test_conformers.py b/tests/test_conformers.py index 6f4581e..0a8f4e1 100644 --- a/tests/test_conformers.py +++ b/tests/test_conformers.py @@ -1,5 +1,5 @@ from autode.atoms import Atom -from autode.species import Molecule +from autode.species import Molecule, NCIComplex from autode.conformers import Conformer, Conformers from autode.wrappers.ORCA import ORCA from autode.wrappers.XTB import XTB @@ -14,6 +14,7 @@ from . import testutils import numpy as np import pytest import os +import shutil here = os.path.dirname(os.path.abspath(__file__)) orca = ORCA() @@ -270,3 +271,17 @@ def test_calculation_over_no_conformers(): # Should not raise an exception assert len(confs) == 0 + + +def test_complex_conformers_diff_names(): + + Config.num_complex_sphere_points = 2 + Config.num_complex_random_rotations = 2 + + water = Molecule(smiles='O') + h2o_dimer = NCIComplex(water, water, name='dimer') + h2o_dimer._generate_conformers() + assert len(set(conf.name for conf in h2o_dimer.conformers)) > 1 + + if os.path.exists('conformers'): + shutil.rmtree('conformers')
NCIComplex conformers are not generated correctly **Describe the bug** <!-- A clear and concise description of what the bug is. --> NCI complex conformers are all generated with the same name, which means optimisations skip over all but the first one. The documentation water trimer works, but for other more complex surfaces this is not expected to. **To Reproduce** <!-- Steps to reproduce the behaviour: code with output --> ``` import autode as ade from autode.species import NCIComplex ade.Config.num_complex_sphere_points = 5 ade.Config.num_complex_random_rotations = 3 water = ade.Molecule(name='water', smiles='O') trimer = NCIComplex(water, water, water, name='water_trimer') trimer.find_lowest_energy_conformer(lmethod=ade.methods.XTB()) trimer.print_xyz_file() ``` The conformers directory only contains a single XTB output file **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Environment** <!-- please complete the following information. --> - OS: CentOS - Version: v. 1.1.0
0.0
445e96f8477eb41e9a42a7e00c6eedfb24118a86
[ "tests/test_conformers.py::test_complex_conformers_diff_names" ]
[ "tests/test_conformers.py::test_conf_class", "tests/test_conformers.py::test_rdkit_atoms", "tests/test_conformers.py::test_confs_energy_pruning1", "tests/test_conformers.py::test_confs_energy_pruning2", "tests/test_conformers.py::test_confs_energy_pruning3", "tests/test_conformers.py::test_confs_no_energy_pruning", "tests/test_conformers.py::test_confs_rmsd_pruning1", "tests/test_conformers.py::test_confs_rmsd_pruning2", "tests/test_conformers.py::test_confs_rmsd_puning3", "tests/test_conformers.py::test_sp_hmethod", "tests/test_conformers.py::test_sp_hmethod_ranking", "tests/test_conformers.py::test_calculation_over_no_conformers" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-10-04 10:49:40+00:00
mit
2,019
duecredit__duecredit-86
diff --git a/duecredit/collector.py b/duecredit/collector.py index b7ee6db..e81055a 100644 --- a/duecredit/collector.py +++ b/duecredit/collector.py @@ -160,9 +160,10 @@ class Citation(object): else: return entry.path.startswith(self.path + '.') + @property def key(self): - return CitationKey(self.path, self.entry.get_key()) + return CitationKey(self.path, self.entry.key) @staticmethod def get_key(path, entry_key): diff --git a/duecredit/entries.py b/duecredit/entries.py index eef2081..97a67bf 100644 --- a/duecredit/entries.py +++ b/duecredit/entries.py @@ -18,6 +18,10 @@ class DueCreditEntry(object): def get_key(self): return self._key + @property + def key(self): + return self.get_key() + @property def rawentry(self): if PY2: diff --git a/duecredit/io.py b/duecredit/io.py index 9ed6740..5c09af8 100644 --- a/duecredit/io.py +++ b/duecredit/io.py @@ -75,151 +75,141 @@ def import_doi(doi, sleep=0.5, retries=10): return bibtex -class EnumeratedEntries(Iterator): - """A container of entries enumerated referenced by their entry_key""" - def __init__(self): - self._keys2refnr = {} - self._refnr2keys = {} - self._refnr = 1 - - def add(self, entry_key): - """Add entry_key and update refnr""" - if entry_key not in self._keys2refnr: - self._keys2refnr[entry_key] = self._refnr - self._refnr2keys[self._refnr] = entry_key - self._refnr += 1 - - def __getitem__(self, item): - if item not in self._keys2refnr: - raise KeyError('{0} not present'.format(item)) - return self._keys2refnr[item] - - def fromrefnr(self, refnr): - if refnr not in self._refnr2keys: - raise KeyError('{0} not present'.format(refnr)) - return self._refnr2keys[refnr] - - def __iter__(self): - return iteritems(self._keys2refnr) - - # Python 3 - def __next__(self): - return self.next() - - def next(self): - yield next(self.__iter__()) - - def __len__(self): - return len(self._keys2refnr) +def _is_contained(toppath, subpath): + if ':' not in toppath: + return ((toppath == subpath) or + (subpath.startswith(toppath + '.')) or + (subpath.startswith(toppath + ':'))) + else: + return subpath.startswith(toppath + '.') -class TextOutput(object): # TODO some parent class to do what...? - def __init__(self, fd, collector, style=None): +class Output(object): + """A generic class for setting up citations that then will be outputted + differently (e.g., Bibtex, Text, etc.)""" + def __init__(self, fd, collector): self.fd = fd self.collector = collector - # TODO: check that CLS style actually exists - self.style = style - if 'DUECREDIT_STYLE' in os.environ.keys(): - self.style = os.environ['DUECREDIT_STYLE'] - else: - self.style = 'harvard1' - # TODO: refactor name to sth more intuitive - def _model_citations(self, tags=None): + def _filter_citations(self, tags=None): + """Given all the citations, filter only those that the user wants and + those that were actually used""" if not tags: tags = os.environ.get('DUECREDIT_REPORT_TAGS', 'reference-implementation,implementation').split(',') tags = set(tags) citations = self.collector.citations if tags != {'*'}: - # Filter out citations + # Filter out citations based on tags citations = dict((k, c) for k, c in iteritems(citations) if tags.intersection(c.tags)) - packages = {} - modules = {} - objects = {} - - for key in ('citations', 'entry_keys'): - packages[key] = defaultdict(list) - modules[key] = defaultdict(list) - objects[key] = defaultdict(list) + packages = defaultdict(list) + modules = defaultdict(list) + objects = defaultdict(list) - # for each path store both a list of entry keys and of citations + # store the citations according to their path and divide them into + # the right level for (path, entry_key), citation in iteritems(citations): if ':' in path: - target_dict = objects + objects[path].append(citation) elif '.' in path: - target_dict = modules + modules[path].append(citation) else: - target_dict = packages - target_dict['citations'][path].append(citation) - target_dict['entry_keys'][path].append(entry_key) + packages[path].append(citation) + + # now we need to filter out the packages that don't have modules + # or objects cited, or are specifically requested + cited_packages = list(packages) + cited_modobj = list(modules) + list(objects) + for package in cited_packages: + package_citations = packages[package] + if list(filter(lambda x: x.cite_module, package_citations)) or \ + list(filter(lambda x: _is_contained(package, x), cited_modobj)): + continue + else: + # we don't need it + del packages[package] + return packages, modules, objects + def dump(self, tags=None): + raise NotImplementedError + + + +class TextOutput(Output): + def __init__(self, fd, collector, style=None): + super(TextOutput, self).__init__(fd, collector) + self.style = style + if 'DUECREDIT_STYLE' in os.environ.keys(): + self.style = os.environ['DUECREDIT_STYLE'] + else: + self.style = 'harvard1' + + + @staticmethod + def _format_citations(citations, citation_nr): + descriptions = map(str, set(str(r.description) for r in citations)) + versions = map(str, set(str(r.version) for r in citations)) + refnrs = map(str, [citation_nr[c.entry.key] for c in citations]) + path = citations[0].path + + return '- {0} / {1} (v {2}) [{3}]\n'.format( + ", ".join(descriptions), path, ', '.join(versions), ', '.join(refnrs)) + def dump(self, tags=None): # get 'model' of citations - packages, modules, objects = self._model_citations(tags) - # mapping key -> refnr - enum_entries = EnumeratedEntries() - - citations_ordered = [] - # set up view - - # package level - sublevels = [modules, objects] - for package in sorted(packages['entry_keys']): - for entry_key in packages['entry_keys'][package]: - enum_entries.add(entry_key) - citations_ordered.append(package) - # sublevels - for sublevel in sublevels: - for obj in sorted(filter(lambda x: package in x, sublevel['entry_keys'])): - for entry_key_obj in sublevel['entry_keys'][obj]: - enum_entries.add(entry_key_obj) - citations_ordered.append(obj) - - # Now we can "render" different views of our "model" - # Here for now just text BUT that is where we can "split" the logic and provide - # different renderings given the model -- text, rest, md, tex+latex, whatever - self.fd.write('\nDueCredit Report:\n') + packages, modules, objects = self._filter_citations(tags) + # put everything into a single dict + pmo = {} + pmo.update(packages) + pmo.update(modules) + pmo.update(objects) + + # get all the paths + paths = sorted(list(pmo)) + # get all the entry_keys in order + entry_keys = [c.entry.key for p in paths for c in pmo[p]] + # make a dictionary entry_key -> citation_nr + citation_nr = defaultdict(int) + refnr = 1 + for entry_key in entry_keys: + if entry_key not in citation_nr: + citation_nr[entry_key] = refnr + refnr += 1 - for path in citations_ordered: - if ':' in path: - self.fd.write(' ') - target_dict = objects - elif '.' in path: + self.fd.write('\nDueCredit Report:\n') + start_refnr = 1 + for path in paths: + # since they're lexicographically sorted by path, dependencies + # should be maintained + cit = pmo[path] + if ':' in path or '.' in path: self.fd.write(' ') - target_dict = modules - else: - target_dict = packages - # TODO: absorb common logic into a common function - citations = target_dict['citations'][path] - entry_keys = target_dict['entry_keys'][path] - descriptions = sorted(map(str, set(str(r.description) for r in citations))) - versions = sorted(map(str, set(str(r.version) for r in citations))) - refnrs = sorted([str(enum_entries[entry_key]) for entry_key in entry_keys]) - self.fd.write('- {0} / {1} (v {2}) [{3}]\n'.format( - ", ".join(descriptions), path, ', '.join(versions), ', '.join(refnrs))) + self.fd.write(self._format_citations(cit, citation_nr)) + start_refnr += len(cit) # Print out some stats - obj_names = ('packages', 'modules', 'functions') - n_citations = map(len, (packages['citations'], modules['citations'], objects['citations'])) - for citation_type, n in zip(obj_names, n_citations): - self.fd.write('\n{0} {1} cited'.format(n, citation_type)) - - if enum_entries: - citations_fromentrykey = self.collector._citations_fromentrykey() + stats = [(len(packages), 'package'), + (len(modules), 'module'), + (len(objects), 'function')] + for n, cit_type in stats: + self.fd.write('\n{0} {1} cited'.format(n, cit_type if n == 1 + else cit_type + 's')) + # now print out references + printed_keys = [] + if len(pmo) > 0: self.fd.write('\n\nReferences\n' + '-' * 10 + '\n') - # collect all the entries used - refnr_key = [(nr, enum_entries.fromrefnr(nr)) for nr in range(1, len(enum_entries)+1)] - for nr, key in refnr_key: - self.fd.write('\n[{0}] '.format(nr)) - citation_text = get_text_rendering(citations_fromentrykey[key], style=self.style) - if PY2: - citation_text = citation_text.encode(_PREFERRED_ENCODING) - self.fd.write(citation_text) + for path in paths: + for cit in pmo[path]: + ek = cit.entry.key + if ek not in printed_keys: + self.fd.write('\n[{0}] '.format(citation_nr[ek])) + self.fd.write(get_text_rendering(cit, + style=self.style)) + printed_keys.append(ek) self.fd.write('\n') @@ -312,17 +302,32 @@ class PickleOutput(object): with open(filename, 'rb') as f: return pickle.load(f) -class BibTeXOutput(object): # TODO some parent class to do what...? +class BibTeXOutput(Output): def __init__(self, fd, collector): - self.fd = fd - self.collector = collector + super(BibTeXOutput, self).__init__(fd, collector) - def dump(self): - for citation in self.collector.citations.values(): + def dump(self, tags=None): + packages, modules, objects = self._filter_citations(tags) + # get all the citations in order + pmo = {} + pmo.update(packages) + pmo.update(modules) + pmo.update(objects) + + # get all the paths + paths = sorted(list(pmo)) + + entries = [] + for path in paths: + for c in pmo[path]: + if c.entry not in entries: + entries.append(c.entry) + + for entry in entries: try: - bibtex = get_bibtex_rendering(citation.entry) + bibtex = get_bibtex_rendering(entry) except: - lgr.warning("Failed to generate bibtex for %s" % citation.entry) + lgr.warning("Failed to generate bibtex for %s" % entry) continue self.fd.write(bibtex.rawentry + "\n")
duecredit/duecredit
033a5ef38bee10c95eb49bebfd46e575baf2044e
diff --git a/duecredit/tests/test_io.py b/duecredit/tests/test_io.py index b895115..b46eb71 100644 --- a/duecredit/tests/test_io.py +++ b/duecredit/tests/test_io.py @@ -21,8 +21,8 @@ from mock import patch from ..collector import DueCreditCollector, Citation from .test_collector import _sample_bibtex, _sample_doi from ..entries import BibTeX, DueCreditEntry, Doi -from ..io import TextOutput, PickleOutput, import_doi, EnumeratedEntries, \ - get_text_rendering, format_bibtex +from ..io import TextOutput, PickleOutput, import_doi, \ + get_text_rendering, format_bibtex, _is_contained, Output, BibTeXOutput from ..utils import with_tempfile from nose.tools import assert_equal, assert_is_instance, assert_raises, \ @@ -85,18 +85,174 @@ def test_pickleoutput(fn): collector_loaded._entries.keys()) os.unlink(fn) + +def test_output(): + entry = BibTeX(_sample_bibtex) + entry2 = BibTeX(_sample_bibtex2) + + # normal use + collector = DueCreditCollector() + collector.cite(entry, path='package') + collector.cite(entry, path='package.module') + + output = Output(None, collector) + + packages, modules, objects = output._filter_citations(tags=['*']) + + assert_equal(len(packages), 1) + assert_equal(len(modules), 1) + assert_equal(len(objects), 0) + + assert_equal(packages['package'][0], + collector.citations[('package', entry.get_key())]) + assert_equal(modules['package.module'][0], + collector.citations[('package.module', entry.get_key())]) + + # no toppackage + collector = DueCreditCollector() + collector.cite(entry, path='package') + collector.cite(entry, path='package2.module') + + output = Output(None, collector) + + packages, modules, objects = output._filter_citations(tags=['*']) + + assert_equal(len(packages), 0) + assert_equal(len(modules), 1) + assert_equal(len(objects), 0) + + assert_equal(modules['package2.module'][0], + collector.citations[('package2.module', entry.get_key())]) + + + # toppackage because required + collector = DueCreditCollector() + collector.cite(entry, path='package', cite_module=True) + collector.cite(entry, path='package2.module') + + output = Output(None, collector) + + packages, modules, objects = output._filter_citations(tags=['*']) + + assert_equal(len(packages), 1) + assert_equal(len(modules), 1) + assert_equal(len(objects), 0) + + assert_equal(packages['package'][0], + collector.citations[('package', entry.get_key())]) + assert_equal(modules['package2.module'][0], + collector.citations[('package2.module', entry.get_key())]) + + + # check it returns multiple entries + collector = DueCreditCollector() + collector.cite(entry, path='package') + collector.cite(entry2, path='package') + collector.cite(entry, path='package.module') + + output = Output(None, collector) + + packages, modules, objects = output._filter_citations(tags=['*']) + + assert_equal(len(packages), 1) + assert_equal(len(packages['package']), 2) + assert_equal(len(modules), 1) + assert_equal(len(objects), 0) + + # sort them in order so we know who is who + # entry2 key is Atk... + # entry key is XX.. + packs = sorted(packages['package'], key=lambda x: x.entry.key) + + assert_equal(packs[0], + collector.citations[('package', entry2.get_key())]) + assert_equal(packs[1], + collector.citations[('package', entry.get_key())]) + assert_equal(modules['package.module'][0], + collector.citations[('package.module', entry.get_key())]) + + + # check that filtering works + collector = DueCreditCollector() + collector.cite(entry, path='package', tags=['edu']) + collector.cite(entry2, path='package') + collector.cite(entry, path='package.module', tags=['edu']) + + output = Output(None, collector) + + packages, modules, objects = output._filter_citations(tags=['edu']) + + assert_equal(len(packages), 1) + assert_equal(len(packages['package']), 1) + assert_equal(len(modules), 1) + assert_equal(len(objects), 0) + + assert_equal(packages['package'][0], + collector.citations[('package', entry.get_key())]) + assert_equal(modules['package.module'][0], + collector.citations[('package.module', entry.get_key())]) + def test_text_output(): entry = BibTeX(_sample_bibtex) + entry2 = BibTeX(_sample_bibtex2) + + # in this case, since we're not citing any module or method, we shouldn't + # output anything collector = DueCreditCollector() - collector.cite(entry, path='module') + collector.cite(entry, path='package') strio = StringIO() TextOutput(strio, collector).dump(tags=['*']) value = strio.getvalue() + assert_true("0 packages cited" in value, msg="value was %s" % value) + assert_true("0 modules cited" in value, msg="value was %s" % value) + assert_true("0 functions cited" in value, msg="value was %s" % value) + + # but it should be cited if cite_module=True + collector = DueCreditCollector() + collector.cite(entry, path='package', cite_module=True) + + strio = StringIO() + TextOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_true("1 package cited" in value, msg="value was %s" % value) + assert_true("0 modules cited" in value, msg="value was %s" % value) + assert_true("0 functions cited" in value, msg="value was %s" % value) + + # in this case, we should be citing the package since we are also citing a + # submodule + collector = DueCreditCollector() + collector.cite(entry, path='package') + collector.cite(entry, path='package.module') + + strio = StringIO() + TextOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_true("1 package cited" in value, msg="value was %s" % value) + assert_true("1 module cited" in value, msg="value was %s" % value) + assert_true("0 functions cited" in value, msg="value was %s" % value) assert_true("Halchenko, Y.O." in value, msg="value was %s" % value) assert_true(value.strip().endswith("Frontiers in Neuroinformatics, 6(22).")) + # in this case, we should be citing the package since we are also citing a + # submodule + collector = DueCreditCollector() + collector.cite(entry, path='package') + collector.cite(entry2, path='package') + collector.cite(entry, path='package.module') + + strio = StringIO() + TextOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_true("1 package cited" in value, msg="value was %s" % value) + assert_true("1 module cited" in value, msg="value was %s" % value) + assert_true("0 functions cited" in value, msg="value was %s" % value) + assert_true("Halchenko, Y.O." in value, msg="value was %s" % value) + assert_true('[1, 2]' in value, msg="value was %s" %value) + assert_false('[3]' in value, msg="value was %s" %value) + + def test_text_output_dump_formatting(): due = DueCreditCollector() @@ -125,17 +281,18 @@ def test_text_output_dump_formatting(): msg='value was {0}'.format(value)) # now we call it -- check it prints stuff + strio = StringIO() mymodule('magical', kwarg2=1) TextOutput(strio, due).dump(tags=['*']) value = strio.getvalue() - assert_true('1 packages cited' in value, msg='value was {0}'.format(value)) - assert_true('1 functions cited' in value, msg='value was {0}'.format(value)) + assert_true('1 package cited' in value, msg='value was {0}'.format(value)) + assert_true('1 function cited' in value, msg='value was {0}'.format(value)) assert_true('(v 0.0.16)' in value, msg='value was {0}'.format(value)) - assert_equal(len(value.split('\n')), 21, msg='value was {0}'.format(value)) + assert_equal(len(value.split('\n')), 16, msg='value was {0}'.format(len(value.split('\n')))) # test we get the reference numbering right - samples_bibtex = [_generate_sample_bibtex() for x in range(5)] + samples_bibtex = [_generate_sample_bibtex() for x in range(6)] # this sucks but at the moment it's the only way to have multiple # references for a function @@ -154,7 +311,7 @@ def test_text_output_dump_formatting(): path='myothermodule:myotherfunction') @due.dcite(BibTeX(samples_bibtex[4]), description='solution to life', path='myothermodule:myotherfunction') - @due.dcite(BibTeX(_sample_bibtex2), description='solution to life', + @due.dcite(BibTeX(samples_bibtex[5]), description='solution to life', path='myothermodule:myotherfunction') def myotherfunction(arg42): pass @@ -187,6 +344,59 @@ def test_text_output_dump_formatting(): import warnings assert_true(('ignore', None, UserWarning, None, 0) not in warnings.filters) + +def test_bibtex_output(): + entry = BibTeX(_sample_bibtex) + entry2 = BibTeX(_sample_bibtex2) + + # in this case, since we're not citing any module or method, we shouldn't + # output anything + collector = DueCreditCollector() + collector.cite(entry, path='package') + + strio = StringIO() + BibTeXOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_equal(value, '', msg='Value was {0}'.format(value)) + + # impose citing + collector = DueCreditCollector() + collector.cite(entry, path='package', cite_module=True) + + strio = StringIO() + BibTeXOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_equal(value.strip(), _sample_bibtex.strip(), msg='Value was {0}'.format(value)) + + # impose filtering + collector = DueCreditCollector() + collector.cite(entry, path='package', cite_module=True, tags=['edu']) + collector.cite(entry2, path='package.module') + + strio = StringIO() + BibTeXOutput(strio, collector).dump(tags=['edu']) + value = strio.getvalue() + assert_equal(value.strip(), _sample_bibtex.strip(), msg='Value was {0}'.format(value)) + + # no filtering + strio = StringIO() + BibTeXOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + assert_equal(value.strip(), + _sample_bibtex.strip() + _sample_bibtex2.rstrip(), + msg='Value was {0}'.format(value)) + + # check the we output only unique bibtex entries + collector.cite(entry2, path='package') + strio = StringIO() + BibTeXOutput(strio, collector).dump(tags=['*']) + value = strio.getvalue() + value_ = sorted(value.strip().split('\n')) + bibtex = sorted((_sample_bibtex.strip() + _sample_bibtex2.rstrip()).split('\n')) + assert_equal(value_, bibtex, + msg='Value was {0}'.format(value_, bibtex)) + + def _generate_sample_bibtex(): """ Generate a random sample bibtex to test multiple references @@ -214,25 +424,6 @@ def _generate_sample_bibtex(): sample_bibtex += "}" return sample_bibtex -def test_enumeratedentries(): - enumentries = EnumeratedEntries() - assert_false(enumentries) - - # add some entries - entries = [('ciao', 1), ('miao', 2), ('bau', 3)] - for entry, _ in entries: - enumentries.add(entry) - - assert_equal(len(enumentries), 3) - - for entry, nr in entries: - assert_equal(nr, enumentries[entry]) - assert_equal(entry, enumentries.fromrefnr(nr)) - - assert_raises(KeyError, enumentries.__getitem__, 'boh') - assert_raises(KeyError, enumentries.fromrefnr, 666) - - assert_equal(entries, sorted(enumentries, key=lambda x: x[1])) @patch('duecredit.io.get_bibtex_rendering') @patch('duecredit.io.format_bibtex') @@ -278,3 +469,14 @@ def test_format_bibtex_zenodo_doi(): """ assert_equal(format_bibtex(BibTeX(bibtex_zenodo)), """Ghosh, S. et al., 2016. nipype: Release candidate 1 for version 0.12.0.""") + +def test_is_contained(): + toppath = 'package' + assert_true(_is_contained(toppath, 'package.module')) + assert_true(_is_contained(toppath, 'package.module.submodule')) + assert_true(_is_contained(toppath, 'package.module.submodule:object')) + assert_true(_is_contained(toppath, 'package:object')) + assert_true(_is_contained(toppath, toppath)) + assert_false(_is_contained(toppath, 'package2')) + assert_false(_is_contained(toppath, 'package2:anotherobject')) + assert_false(_is_contained(toppath, 'package2.module:anotherobject'))
Outputting to bibtex doesn't filter by used citations Probably linked to #19 Example output text ``` $duecredit summary --format text DueCredit Report: - Scientific tools library / numpy (v 1.10.4) [1] - Scientific tools library / scipy (v 0.17) [2] - Single linkage hierarchical clustering / scipy.cluster.hierarchy:linkage (v 0.17) [3] - Machine Learning library / sklearn (v 0.17) [4] 3 packages cited 0 modules cited 1 functions cited References ---------- [1] Van Der Walt, S., Colbert, S.C. & Varoquaux, G., 2011. The NumPy array: a structure for efficient numerical computation. Computing in Science & Engineering, 13(2), pp.22–30. [2] Jones, E. et al., 2001. SciPy: Open source scientific tools for Python. [3] Sibson, R., 1973. SLINK: an optimally efficient algorithm for the single-link cluster method. The Computer Journal, 16(1), pp.30–34. [4] Pedregosa, F. et al., 2011. Scikit-learn: Machine learning in Python. The Journal of Machine Learning Research, 12, pp.2825–2830. ``` Example output BibTeX ``` $duecredit summary --format bibtex @article{sneath1962numerical, title={Numerical taxonomy}, author={Sneath, Peter HA and Sokal, Robert R}, journal={Nature}, volume={193}, number={4818}, pages={855--860}, year={1962}, publisher={Nature Publishing Group} } @article{batagelj1995comparing, title={Comparing resemblance measures}, author={Batagelj, Vladimir and Bren, Matevz}, journal={Journal of classification}, volume={12}, number={1}, pages={73--90}, year={1995}, publisher={Springer} } @Misc{JOP+01, author = {Eric Jones and Travis Oliphant and Pearu Peterson and others}, title = {{SciPy}: Open source scientific tools for {Python}}, year = {2001--}, url = "http://www.scipy.org/", note = {[Online; accessed 2015-07-13]} } ... ```
0.0
033a5ef38bee10c95eb49bebfd46e575baf2044e
[ "duecredit/tests/test_io.py::test_import_doi", "duecredit/tests/test_io.py::test_output", "duecredit/tests/test_io.py::test_text_output", "duecredit/tests/test_io.py::test_text_output_dump_formatting", "duecredit/tests/test_io.py::test_bibtex_output", "duecredit/tests/test_io.py::test_get_text_rendering", "duecredit/tests/test_io.py::test_format_bibtex_zenodo_doi", "duecredit/tests/test_io.py::test_is_contained" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-05-21 17:17:30+00:00
bsd-2-clause
2,020
dunossauro__splitty-22
diff --git a/pylava.ini b/pylava.ini index 1c20fd4..a52bd1d 100644 --- a/pylava.ini +++ b/pylava.ini @@ -5,8 +5,5 @@ linters=pep8,pep257,pyflakes [pylava:pep8] max_line_length = 80 -[pylava:*/__init__.py] -ignore=D104 - [pylava:*/test_*] ignore=D100,D101,D102 diff --git a/splitty/__init__.py b/splitty/__init__.py index c200706..6355269 100644 --- a/splitty/__init__.py +++ b/splitty/__init__.py @@ -1,1 +1,24 @@ -from .splitty import * # NOQA +""" +Splitty. + +Functional approach to work with iterables in python +""" +from .splitty import ( + clear_list_strings, + list_by_list, + list_by_re_pattern, + find_elements, + make_intervals, + apply_intervals, + chunks, +) + +__all__ = [ + 'clear_list_strings', + 'list_by_list', + 'list_by_re_pattern', + 'find_elements', + 'make_intervals', + 'apply_intervals', + 'chunks', +] diff --git a/splitty/splitty.py b/splitty/splitty.py index 959eb91..c8dff52 100644 --- a/splitty/splitty.py +++ b/splitty/splitty.py @@ -4,6 +4,8 @@ Splitty. Functional approach to work with iterables in python """ from re import match +from functools import singledispatch +from numbers import Number def clear_list_strings(strings: list) -> list: @@ -41,6 +43,45 @@ def list_by_list(list_with_elements: list, list_with_intervals), start)) +@singledispatch +def nun_or_match(matcher, element): + r""" + Discover if matcher ir a Number or String and match then. + + >>> nun_or_match(7, 7) + True + + >>> nun_or_match('\w+', 'Hello') + <re.Match object; span=(0, 5), match='Hello'> + + >>> nun_or_match('spam', 'spam') + <re.Match object; span=(0, 4), match='spam'> + """ + ... + + +@nun_or_match.register(str) +def str_eq(matcher, element): + r""" + Match strings or regex using re.match, called by nun_or_match. + + >>> nun_or_match('\w+', 'Hello') + <re.Match object; span=(0, 5), match='Hello'> + """ + return match(matcher, str(element)) + + +@nun_or_match.register(Number) +def number_eq(matcher, element): + r""" + Match numbers , called by nun_or_match. + + >>> nun_or_match(7, 7) + True + """ + return matcher == element + + def find_elements(full_list: list, list_with_values: list) -> list: """ Find occurrences in a list and make a index related. @@ -50,7 +91,7 @@ def find_elements(full_list: list, list_with_values: list) -> list: """ return [(x, val) for x, val in enumerate(full_list) for y in list_with_values - if y == val] + if nun_or_match(y, val)] def list_by_re_pattern(list_to_be_splited: list,
dunossauro/splitty
8ddc399330416fdecbcbb3e9264f3d50f5f386a4
diff --git a/tests/test_splitty.py b/tests/test_splitty.py index 7e2c4f8..683f5bd 100644 --- a/tests/test_splitty.py +++ b/tests/test_splitty.py @@ -4,16 +4,65 @@ from unittest import TestCase, main from splitty import * # NOQA +class TestInit(TestCase): + def test_module_shouldnt_call_functions_out_all(self): + import splitty + with self.assertRaises(AttributeError): + splitty.nun_or_match() + + +class TestNunOrMatch(TestCase): + def setUp(self): + from splitty.splitty import nun_or_match + self.nom = nun_or_match + + def test_num_or_match_should_return_True_when_mach_same_number(self): + self.assertTrue(self.nom(7, 7)) + + def test_num_or_match_should_return_False_when_mach_different_number(self): + self.assertFalse(self.nom(7, 8)) + + def test_num_or_match_should_return_regex_match_when_compare_strings(self): + import re + self.assertIsInstance(self.nom('sa', 'sa'), re.Match) + + def test_num_or_match_should_return_regex_match_when_non_match_regex(self): + self.assertIsNone(self.nom('sa', 's1a')) + + class TestFindListElements(TestCase): - def test_find_list_elements(self): + def test_find_list_should_return_positions_and_strings(self): split_by = ['spam', 'eggs', 'foo'] - list_to_be_splited = ['spam', 1, 2, 3, - 'eggs', 1, 2, 3, - 'foo', 1, 2, 3] - + list_to_be_splited = [ + 'spam', 1, 2, 3, + 'eggs', 1, 2, 3, + 'foo', 1, 2, 3 + ] self.assertEqual(find_elements(list_to_be_splited, split_by), [(0, 'spam'), (4, 'eggs'), (8, 'foo')]) + def test_find_list_should_return_positions_and_strings_with_regex(self): + split_by = [r'spa\w', r'\wggs', r'f\wo', r'b.r'] + list_to_be_splited = [ + 'spam', 1, 2, 3, + 'eggs', 1, 2, 3, + 'foo', 1, 2, 3, + 'bar', 1, 2, 3 + ] + self.assertEqual(find_elements(list_to_be_splited, split_by), + [(0, 'spam'), (4, 'eggs'), (8, 'foo'), (12, 'bar')]) + + def test_find_list_should_return_positions_and_strings_with_mixin_regex_and_string(self): + split_by = [r'spa\w', 'eggs', r'f\wo', 'bar'] + list_to_be_splited = [ + 'spam', 1, 2, 3, + 'eggs', 1, 2, 3, + 'foo', 1, 2, 3, + 'bar', 1, 2, 3 + ] + self.assertEqual(find_elements(list_to_be_splited, split_by), + [(0, 'spam'), (4, 'eggs'), (8, 'foo'), (12, 'bar')]) + def test_should_be_blank_list_if_splited_by_blank_list(self): list_to_be_splited = ['spam', 1, 2, 3, 'eggs', 1, 2, 3, @@ -135,7 +184,3 @@ class TestClearListString(TestCase): _list = ['\r\nHello', 'how', '\r', 'r', 'u\n', '\r'] expected = ['Hello', 'how', 'r', 'u'] self.assertEqual(clear_list_strings(_list), expected) - - -if __name__ == '__main__': - main()
Regex support on find_elements `find_elements` function works only in full match case. ```Python >>> list_to_be_splited = ['spam', 1, 2, 3, 'eggs', 1, 2, 3, 'foo', 1, 2, 3] >>> split_by = ['spam', 'eggs', 'foo'] >>> splited = find_elements(list_to_be_splited, split_by) # [(0, 'spam'), (4, 'eggs'), (8, 'foo')] ``` And `list_by_re_pattern` matches one regex. In my opinion using splitty yesterday with @rg3915, we saw a dependency. Something like that: ``` root 1978 0.2 0.8 1534468 69680 ? Ssl 09:12 0:01 /usr/bin/dockerd -H fd:// root 2141 0.1 0.4 1244864 34892 ? Ssl 09:12 0:01 docker-containerd --config /var/run/docker/containerd/containerd.toml root 2706 0.0 0.0 379496 3832 ? Sl 09:12 0:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 5432 -container-ip 192.202.112.2 ... eduardo+ 6136 0.0 0.0 14440 1108 pts/0 S+ 09:24 0:00 grep --color=auto docker ``` If i need catch all docker process intervals, or we list all docker commands or create a biggest regex. in that case it would be simpler a basix expression in list_by_list: ```Python >>> list_to_be_splited = ''' root 1978 0.2 0.8 1534468 69680 ? Ssl 09:12 0:01 /usr/bin/dockerd -H fd:// root 2141 0.1 0.4 1244864 34892 ? Ssl 09:12 0:01 docker-containerd --config /var/run/docker/containerd/containerd.toml root 2706 0.0 0.0 379496 3832 ? Sl 09:12 0:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 5432 -container-ip 192.202.112.2 ... eduardo+ 6136 0.0 0.0 14440 1108 pts/0 S+ 09:24 0:00 grep --color=auto docker ''' >>> split_by = [r'/usr/bin/docker-\w+, r' /var/run/docker/.+\.toml', 'foo', 'bar'] ```
0.0
8ddc399330416fdecbcbb3e9264f3d50f5f386a4
[ "tests/test_splitty.py::TestNunOrMatch::test_num_or_match_should_return_False_when_mach_different_number", "tests/test_splitty.py::TestNunOrMatch::test_num_or_match_should_return_True_when_mach_same_number", "tests/test_splitty.py::TestNunOrMatch::test_num_or_match_should_return_regex_match_when_compare_strings", "tests/test_splitty.py::TestNunOrMatch::test_num_or_match_should_return_regex_match_when_non_match_regex", "tests/test_splitty.py::TestFindListElements::test_find_list_should_return_positions_and_strings_with_mixin_regex_and_string", "tests/test_splitty.py::TestFindListElements::test_find_list_should_return_positions_and_strings_with_regex" ]
[ "tests/test_splitty.py::TestInit::test_module_shouldnt_call_functions_out_all", "tests/test_splitty.py::TestFindListElements::test_find_list_should_return_positions_and_strings", "tests/test_splitty.py::TestFindListElements::test_should_be_blank_list_if_splited_by_blank_list", "tests/test_splitty.py::TestListByList::test_list_by_list", "tests/test_splitty.py::TestListByRePattern::test_dont_parse_if_has_non_string_value_in_iterable", "tests/test_splitty.py::TestListByRePattern::test_list_by_re_pattern", "tests/test_splitty.py::TestListByRePattern::test_parse_if_has_non_string_value_in_iterable_with_str_convert", "tests/test_splitty.py::TestMakeIntervals::test_make_intervals", "tests/test_splitty.py::TestMakeIntervals::test_make_intervals_has_element_zero", "tests/test_splitty.py::TestMakeIntervals::test_make_intervals_return_blank_if_input_blank", "tests/test_splitty.py::TestMakeIntervals::test_make_intervals_using_a_list_with_values", "tests/test_splitty.py::TestChunks::test_chunk_should_be_one_list_by_value", "tests/test_splitty.py::TestChunks::test_internal_lists_should_be_the_same_of_n", "tests/test_splitty.py::TestChunks::test_internals_should_be_less_than_n_if_n_is_greater_than_size", "tests/test_splitty.py::TestChunks::test_last_internal_lists_should_be_less_than_n", "tests/test_splitty.py::TestClearListString::test_should_remove_blank_lines" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-10-08 17:39:59+00:00
mit
2,021
duo-labs__parliament-177
diff --git a/parliament/__init__.py b/parliament/__init__.py index f9b5d48..91dd4b3 100644 --- a/parliament/__init__.py +++ b/parliament/__init__.py @@ -1,7 +1,7 @@ """ This library is a linter for AWS IAM policies. """ -__version__ = "1.3.1" +__version__ = "1.4.0" import fnmatch import functools @@ -147,6 +147,52 @@ def is_arn_match(resource_type, arn_format, resource): return is_glob_match(arn_id, resource_id) +def is_arn_strictly_valid(resource_type, arn_format, resource): + """ + Strictly validate the arn_format specified in the docs, with the resource + given in the IAM policy. These can each be strings with globbing. For example, we + want to match the following two strings: + - arn:*:s3:::*/* + - arn:aws:s3:::*personalize* + + That should return true because you could have "arn:aws:s3:::personalize/" which matches both. + + However when not using *, must include the resource type in the resource arn and wildcards + are not valid for the resource type portion (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namesspaces) + + Input: + - resource_type: Example "bucket", this is only used to identify special cases. + - arn_format: ARN regex from the docs + - resource: ARN regex from IAM policy + + """ + + if is_arn_match(resource_type, arn_format, resource): + # this would have already raised exception + arn_parts = arn_format.split(":") + resource_parts = resource.split(":") + arn_id = ":".join(arn_parts[5:]) + resource_id = ":".join(resource_parts[5:]) + + # Does the resource contain a resource type component + # regex looks for a resource type word like "user" or "cluster-endpoint" followed by a + # : or / and then anything else excluding the resource type string starting with a * + arn_id_resource_type = re.match(r"(^[^\*][\w-]+)[\/\:].+", arn_id) + + if arn_id_resource_type != None and resource_id != "*": + + # https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namesspaces + # The following is not allowed: arn:aws:iam::123456789012:u* + if not (resource_id.startswith(arn_id_resource_type[1])): + return False + + # replace aws variable and check for other colons + resource_id_no_vars = re.sub(r"\$\{aws.\w+\}", "", resource_id) + if ":" in resource_id_no_vars and not ":" in arn_id: + return False + + return True + return False def is_glob_match(s1, s2): # This comes from https://github.com/duo-labs/parliament/issues/36#issuecomment-574001764 diff --git a/parliament/cli.py b/parliament/cli.py index fee82e7..4905e82 100755 --- a/parliament/cli.py +++ b/parliament/cli.py @@ -233,7 +233,7 @@ def main(): contents = f.read() policy_file_json = jsoncfg.loads_config(contents) policy_string = json.dumps( - policy_file_json["PolicyVersion"]["Document"] + policy_file_json.PolicyVersion.Document() ) policy = analyze_policy_string( policy_string, @@ -248,55 +248,55 @@ def main(): with open(args.auth_details_file) as f: contents = f.read() auth_details_json = jsoncfg.loads_config(contents) - for policy in auth_details_json["Policies"]: + for policy in auth_details_json.Policies: # Ignore AWS defined policies - if "arn:aws:iam::aws:" in policy["Arn"]: + if "arn:aws:iam::aws:" in policy.Arn(): continue # Ignore AWS Service-linked roles if ( - policy["Path"] == "/service-role/" - or policy["Path"] == "/aws-service-role/" - or policy["PolicyName"].startswith("AWSServiceRoleFor") - or policy["PolicyName"].endswith("ServiceRolePolicy") - or policy["PolicyName"].endswith("ServiceLinkedRolePolicy") + policy.Path() == "/service-role/" + or policy.Path() == "/aws-service-role/" + or policy.PolicyName().startswith("AWSServiceRoleFor") + or policy.PolicyName().endswith("ServiceRolePolicy") + or policy.PolicyName().endswith("ServiceLinkedRolePolicy") ): continue - for version in policy["PolicyVersionList"]: - if not version["IsDefaultVersion"]: + for version in policy.PolicyVersionList: + if not version.IsDefaultVersion(): continue policy = analyze_policy_string( - json.dumps(version["Document"]), policy["Arn"], + json.dumps(version.Document()), policy.Arn(), ) findings.extend(policy.findings) # Review the inline policies on Users, Roles, and Groups - for user in auth_details_json["UserDetailList"]: - for policy in user.get("UserPolicyList", []): + for user in auth_details_json.UserDetailList: + for policy in user.UserPolicyList([]): policy = analyze_policy_string( - json.dumps(policy["PolicyDocument"]), - user["Arn"], + json.dumps(policy['PolicyDocument']), + user.Arn(), private_auditors_custom_path=args.private_auditors, include_community_auditors=args.include_community_auditors, config=config, ) findings.extend(policy.findings) - for role in auth_details_json["RoleDetailList"]: - for policy in role.get("RolePolicyList", []): + for role in auth_details_json.RoleDetailList: + for policy in role.RolePolicyList([]): policy = analyze_policy_string( - json.dumps(policy["PolicyDocument"]), - role["Arn"], + json.dumps(policy['PolicyDocument']), + role.Arn(), private_auditors_custom_path=args.private_auditors, include_community_auditors=args.include_community_auditors, config=config, ) findings.extend(policy.findings) - for group in auth_details_json["GroupDetailList"]: - for policy in group.get("GroupPolicyList", []): + for group in auth_details_json.GroupDetailList: + for policy in group.GroupPolicyList([]): policy = analyze_policy_string( - json.dumps(policy["PolicyDocument"]), - group["Arn"], + json.dumps(policy['PolicyDocument']), + group.Arn(), private_auditors_custom_path=args.private_auditors, include_community_auditors=args.include_community_auditors, config=config, diff --git a/parliament/statement.py b/parliament/statement.py index 805c27c..fc7db73 100644 --- a/parliament/statement.py +++ b/parliament/statement.py @@ -4,6 +4,7 @@ import re from . import ( iam_definition, is_arn_match, + is_arn_strictly_valid, expand_action, UnknownActionException, UnknownPrefixException, @@ -434,7 +435,7 @@ class Statement: for aws_principal in make_list(json_object[1]): text = aws_principal.value account_id_regex = re.compile("^\d{12}$") - arn_regex = re.compile("^arn:[-a-z\*]*:iam::(\d{12}|):.*$") + arn_regex = re.compile("^arn:[-a-z\*]*:iam::(\d{12}|cloudfront|):.*$") if text == "*": pass @@ -921,7 +922,7 @@ class Statement: self.resource_star[action_key] += 1 match_found = True continue - if is_arn_match(resource_type, arn_format, resource.value): + if is_arn_strictly_valid(resource_type, arn_format, resource.value): match_found = True continue
duo-labs/parliament
da69dfd77981d8ef87923261980caa6eea9ae9a5
diff --git a/tests/unit/test_principals.py b/tests/unit/test_principals.py index b4a2394..9a6fda1 100644 --- a/tests/unit/test_principals.py +++ b/tests/unit/test_principals.py @@ -104,6 +104,24 @@ class TestPrincipals(unittest.TestCase): policy.finding_ids, set(), "Federated access", ) + policy = analyze_policy_string( + """{ + "Version":"2012-10-17", + "Statement":[ + { + "Effect":"Allow", + "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity 00000000000000" }, + "Action":["s3:GetObject"], + "Resource":["arn:aws:s3:::examplebucket/*"] + } + ] +}""", + ignore_private_auditors=True, + ) + assert_equal( + policy.finding_ids, set(), "S3 bucket policy with CloudFront OAI access", + ) + def test_bad_principals(self): # Good principal policy = analyze_policy_string( diff --git a/tests/unit/test_resource_formatting.py b/tests/unit/test_resource_formatting.py index 2388faa..28a409c 100644 --- a/tests/unit/test_resource_formatting.py +++ b/tests/unit/test_resource_formatting.py @@ -2,7 +2,7 @@ import unittest from nose.tools import raises, assert_equal, assert_true, assert_false # import parliament -from parliament import analyze_policy_string, is_arn_match, is_glob_match +from parliament import analyze_policy_string, is_arn_match, is_arn_strictly_valid, is_glob_match from parliament.statement import is_valid_region, is_valid_account_id @@ -91,6 +91,51 @@ class TestResourceFormatting(unittest.TestCase): ) ) + def test_is_arn_strictly_valid(self): + assert_true( + is_arn_strictly_valid( + "user", "arn:*:iam::*:user/*", "arn:aws:iam::123456789012:user/Development/product_1234/*" + ) + ) + + assert_true( + is_arn_strictly_valid( + "user", "arn:*:iam::*:user/*", "arn:aws:iam::123456789012:*" + ) + ) + + assert_true( + is_arn_strictly_valid( + "ssm", "arn:*:ssm::*:resource-data-sync/*", "arn:aws:ssm::123456789012:resource-data-sync/*" + ) + ) + + assert_false( + is_arn_strictly_valid( + "ssm", "arn:*:ssm::*:resource-data-sync/*", "arn:aws:ssm::123456789012:resource-data-*/*" + ) + ) + + assert_false( + is_arn_strictly_valid( + "user", "arn:*:iam::*:user/*", "arn:aws:iam::123456789012:*/*" + ) + ) + + assert_false( + is_arn_strictly_valid( + "user", "arn:*:iam::*:user/*", "arn:aws:iam::123456789012:u*" + ) + ) + + assert_false( + is_arn_strictly_valid( + "dbuser", "arn:*:redshift:*:*:dbuser:*/*", "arn:aws:redshift:us-west-2:123456789012:db*:the_cluster/the_user" + ) + ) + + + def test_arn_match_cloudtrail_emptysegments(self): assert_false( is_arn_match(
parliament should catch invalid s3 bucket object resource arns I expected `parliament` to catch the following error: ```json { "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action":["s3:GetObject"], "Resource": ["arn:aws:s3:::bucket1:*"] } } ``` Which should have been `arn:aws:s3:::bucket1/*` instead of `:*` at the end of the ARN. Execution of `parliament` against that policy revealed no errors, warnings, or non-zero return code. Thanks!
0.0
da69dfd77981d8ef87923261980caa6eea9ae9a5
[ "tests/unit/test_principals.py::TestPrincipals::test_bad_principals", "tests/unit/test_principals.py::TestPrincipals::test_policy_with_principal", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_apigw_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_apigw_withaccount", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_cloudtrail_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_iam_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_iam_withregion", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withaccount", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withregion", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withregion_account", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_arn_strictly_valid", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_glob_match", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_valid_account_id", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_valid_region", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_resource_bad", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_resource_good" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-04 23:15:49+00:00
bsd-3-clause
2,022
duo-labs__parliament-185
diff --git a/parliament/__init__.py b/parliament/__init__.py index 91dd4b3..1596023 100644 --- a/parliament/__init__.py +++ b/parliament/__init__.py @@ -115,7 +115,8 @@ def is_arn_match(resource_type, arn_format, resource): if "bucket" in resource_type: # We have to do a special case here for S3 buckets - if "/" in resource: + # and since resources can use variables which contain / need to replace them + if "/" in strip_var_from_arn(resource, "theVar"): return False # The ARN has at least 6 parts, separated by a colon. Ensure these exist. @@ -144,7 +145,6 @@ def is_arn_match(resource_type, arn_format, resource): # Some of the arn_id's contain regexes of the form "[key]" so replace those with "*" resource_id = re.sub(r"\[.+?\]", "*", resource_id) - return is_glob_match(arn_id, resource_id) def is_arn_strictly_valid(resource_type, arn_format, resource): @@ -166,7 +166,6 @@ def is_arn_strictly_valid(resource_type, arn_format, resource): - resource: ARN regex from IAM policy """ - if is_arn_match(resource_type, arn_format, resource): # this would have already raised exception arn_parts = arn_format.split(":") @@ -187,13 +186,16 @@ def is_arn_strictly_valid(resource_type, arn_format, resource): return False # replace aws variable and check for other colons - resource_id_no_vars = re.sub(r"\$\{aws.\w+\}", "", resource_id) + resource_id_no_vars = strip_var_from_arn(resource_id) if ":" in resource_id_no_vars and not ":" in arn_id: return False return True return False +def strip_var_from_arn(arn, replace_with=""): + return re.sub(r"\$\{aws.[\w\/]+\}", replace_with, arn) + def is_glob_match(s1, s2): # This comes from https://github.com/duo-labs/parliament/issues/36#issuecomment-574001764 diff --git a/parliament/misc.py b/parliament/misc.py index 08f8dac..a08c9bd 100644 --- a/parliament/misc.py +++ b/parliament/misc.py @@ -14,9 +14,11 @@ def make_list(v): location = jsoncfg.node_location(v) line = location.line column = location.column - else: + elif jsoncfg.node_exists(v): line = v.line column = v.column + else: + return [] a = jsoncfg.config_classes.ConfigJSONArray(line, column) a._append(v)
duo-labs/parliament
1ea9f0b3890223fa9a47503be9f1b739610ac73e
diff --git a/tests/unit/test_resource_formatting.py b/tests/unit/test_resource_formatting.py index 28a409c..0b9e7a6 100644 --- a/tests/unit/test_resource_formatting.py +++ b/tests/unit/test_resource_formatting.py @@ -90,6 +90,11 @@ class TestResourceFormatting(unittest.TestCase): "arn:aws:logs:us-east-1:000000000000:/aws/cloudfront/test" ) ) + assert_true( + is_arn_match( + "bucket", "arn:*:s3:::*", "arn:aws:s3:::bucket-for-client-${aws:PrincipalTag/Namespace}-*" + ) + ) def test_is_arn_strictly_valid(self): assert_true(
Policy variables in the resource element not supported Hi, example policy: ```json { "Version": "2012-10-17", "Statement": [ { "Sid": "BucketAccess", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:GetBucketVersioning", "s3:GetEncryptionConfiguration", "s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions" ], "Resource": "arn:aws:s3::bucket-for-client-${aws:PrincipalTag/Namespace}-*" } ] } ``` Policy variable ${aws:PrincipalTag/Namespace} causes: ```json { "description": "", "detail": [ { "action": "s3:GetBucketLocation", "required_format": "arn:*:s3:::*" }, { "action": "s3:GetBucketVersioning", "required_format": "arn:*:s3:::*" }, { "action": "s3:GetEncryptionConfiguration", "required_format": "arn:*:s3:::*" }, { "action": "s3:ListBucket", "required_format": "arn:*:s3:::*" }, { "action": "s3:ListBucketMultipartUploads", "required_format": "arn:*:s3:::*" }, { "action": "s3:ListBucketVersions", "required_format": "arn:*:s3:::*" } ], "issue": "RESOURCE_MISMATCH", "location": { "column": 3, "filepath": "main.json", "line": 4 }, "match": true, "severity": "MEDIUM", "title": "No resources match for the given action" } ``` Maybe extending this condition https://github.com/duo-labs/parliament/blob/main/parliament/__init__.py#L118 by some regexp will be good enough for start ? ;) ( ex. (?P<Variable>\${aws:.*}) ) Take care!
0.0
1ea9f0b3890223fa9a47503be9f1b739610ac73e
[ "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match" ]
[ "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_apigw_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_apigw_withaccount", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_cloudtrail_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_iam_emptysegments", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_iam_withregion", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withaccount", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withregion", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_arn_match_s3_withregion_account", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_arn_strictly_valid", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_glob_match", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_valid_account_id", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_is_valid_region", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_resource_bad", "tests/unit/test_resource_formatting.py::TestResourceFormatting::test_resource_good" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-18 17:56:44+00:00
bsd-3-clause
2,023
duo-labs__parliament-37
diff --git a/parliament/__init__.py b/parliament/__init__.py index cfa5602..fee4d08 100644 --- a/parliament/__init__.py +++ b/parliament/__init__.py @@ -39,7 +39,7 @@ def enhance_finding(finding): finding.severity = config_settings["severity"] finding.title = config_settings["title"] finding.description = config_settings.get("description", "") - finding.ignore_locations = config_settings.get("ignore_locations", None) + finding.ignore_locations = config_settings.get("ignore_locations", None) return finding @@ -90,7 +90,7 @@ def is_arn_match(resource_type, arn_format, resource): The problem can be simplified because we only care about globbed strings, not full regexes, but there are no Python libraries, but here is one in Go: https://github.com/Pathgather/glob-intersection - We can some cheat because after the first sections of the arn match, meaning until the 5th colon (with some + We can cheat some because after the first sections of the arn match, meaning until the 5th colon (with some rules there to allow empty or asterisk sections), we only need to match the ID part. So the above is simplified to "*/*" and "*personalize*". @@ -110,12 +110,15 @@ def is_arn_match(resource_type, arn_format, resource): if "/" in resource: return False + # The ARN has at least 6 parts, separated by a colon. Ensure these exist. arn_parts = arn_format.split(":") if len(arn_parts) < 6: raise Exception("Unexpected format for ARN: {}".format(arn_format)) resource_parts = resource.split(":") if len(resource_parts) < 6: raise Exception("Unexpected format for resource: {}".format(resource)) + + # For the first 5 parts (ex. arn:aws:SERVICE:REGION:ACCOUNT:), ensure these match appropriately for position in range(0, 5): if arn_parts[position] == "*" or arn_parts[position] == "": continue @@ -126,13 +129,21 @@ def is_arn_match(resource_type, arn_format, resource): else: return False - arn_id = "".join(arn_parts[5:]) - resource_id = "".join(resource_parts[5:]) + # Everything up to and including the account ID section matches, so now try to match the remainder + + arn_id = ":".join(arn_parts[5:]) + resource_id = ":".join(resource_parts[5:]) + + print("Checking {} matches {}".format(arn_id, resource_id)) # TODO REMOVE # At this point we might have something like: # log-group:* for arn_id and # log-group:/aws/elasticbeanstalk* for resource_id + # Alternatively we might have multiple colon separated sections, such as: + # dbuser:*/* for arn_id and + # dbuser:the_cluster/the_user for resource_id + # Look for exact match # Examples: # "mybucket", "mybucket" -> True @@ -149,6 +160,25 @@ def is_arn_match(resource_type, arn_format, resource): if "*" not in arn_id and "*" not in resource_id: return False + # Remove the start of a string that matches. + # "dbuser:*/*", "dbuser:the_cluster/the_user" -> "*/*", "the_cluster/the_user" + # "layer:*:*", "layer:sol-*:*" -> "*:*", "sol-*:*" + + def get_starting_match(s1, s2): + match = "" + for i in range(len(s1)): + if i > len(s2) - 1: + break + if s1[i] == "*" or s2[i] == "*": + break + if s1[i] == s2[i]: + match += s1[i] + return match + + match_len = len(get_starting_match(arn_id, resource_id)) + arn_id = arn_id[match_len:] + resource_id = resource_id[match_len:] + # If either is an asterisk it matches # Examples: # "*", "mybucket" -> True @@ -165,7 +195,7 @@ def is_arn_match(resource_type, arn_format, resource): # If one begins with an asterisk and the other ends with one, it should match # Examples: - # "*/*" and "*personalize*" -> True + # "*/" and "personalize*" -> True if (arn_id[0] == "*" and resource_id[-1] == "*") or ( arn_id[-1] == "*" and resource_id[0] == "*" ): @@ -182,6 +212,7 @@ def is_arn_match(resource_type, arn_format, resource): # Check situation where it begins and ends with asterisks, such as "*/*" if arn_id[0] == "*" and arn_id[-1] == "*": + # Now only check the middle matches if arn_id[1:-1] in resource_id: return True if resource_id[0] == "*" and resource_id[-1] == "*":
duo-labs/parliament
6f510f110286fb5a5e7d9b578aee506e99041d40
diff --git a/tests/unit/test_formatting.py b/tests/unit/test_formatting.py index 748c5c1..fb434a8 100644 --- a/tests/unit/test_formatting.py +++ b/tests/unit/test_formatting.py @@ -267,7 +267,7 @@ class TestFormatting(unittest.TestCase): ) print(policy.findings) assert_equal(len(policy.findings), 0) - + def test_condition_with_null(self): policy = analyze_policy_string( """{ @@ -287,7 +287,7 @@ class TestFormatting(unittest.TestCase): ) print(policy.findings) assert_equal(len(policy.findings), 0) - + def test_condition_with_MultiFactorAuthAge(self): policy = analyze_policy_string( """{ @@ -305,4 +305,43 @@ class TestFormatting(unittest.TestCase): }""" ) print(policy.findings) - assert_equal(len(policy.findings), 0) \ No newline at end of file + assert_equal(len(policy.findings), 0) + + def test_redshift_GetClusterCredentials(self): + policy = analyze_policy_string( + """{ + "Version": "2012-10-17", + "Id": "123", + "Statement": [ + { + "Action": "redshift:GetClusterCredentials", + "Effect": "Allow", + "Resource": "arn:aws:redshift:us-west-2:123456789012:dbuser:the_cluster/the_user" + } + ] + }""" + ) + + # This privilege has a required format of arn:*:redshift:*:*:dbuser:*/* + print(policy.findings) + assert_equal(len(policy.findings), 0) + + def test_lambda_AddLayerVersionPermission(self): + policy = analyze_policy_string( + """{ + "Version": "2012-10-17", + "Id": "123", + "Statement": [ + { + "Sid": "TestPol", + "Effect": "Allow", + "Action": "lambda:AddLayerVersionPermission", + "Resource": "arn:aws:lambda:*:123456789012:layer:sol-*:*" + } + ] + }""" + ) + + # This privilege has a required format of arn:*:redshift:*:*:dbuser:*/* + print(policy.findings) + assert_equal(len(policy.findings), 0)
RESOURCE_MISMATCH not correct for redshift:GetClusterCredentials It seems like there is a problem with the logic in `is_arn_match`. I ran into an issue with `redshift:GetClusterCredentials`. Simple repro => ``` $ parliament --string ' { "Statement": [ { "Action": "redshift:GetClusterCredentials", "Effect": "Allow", "Resource": "arn:aws:redshift:us-west-2:123456789012:dbuser:the_cluster/the_user" } ], "Version": "2012-10-17" }' --json | jq . { "issue": "RESOURCE_MISMATCH", "title": "No resources match for the given action", "severity": "MEDIUM", "description": "Double check that the actions are valid for the specified resources (and vice versa). See https://iam.cloudonaut.io/reference/ or the AWS docs for details", "detail": [ { "action": "redshift:GetClusterCredentials", "required_format": "arn:*:redshift:*:*:dbuser:*/*" } ], "location": { "actions": [ "redshift:GetClusterCredentials" ], "filepath": null } } ``` The expected and actual pattern looks correct to me => ``` (Pdb) arn_parts ['arn', '*', 'redshift', '*', '*', 'dbuser', '*/*'] (Pdb) resource_parts ['arn', 'aws', 'redshift', 'us-west-2', '123456789012', 'dbuser', 'the_cluster/the_user'] ``` All the logic in `is_arn_match` confuses me. I feel like there could be a simple glob check at the top to circumvent all that custom logic for special things like s3 buckets. However, interestingly, that doesn't work either??? ``` >>> fnmatch.fnmatch('arn:*:redshift:*:*:dbuser:*/*', 'arn:aws:redshift:us-west-2:528741615426:dbuser:the_cluster/the_user') False ``` Which is weird, because translating to regex, then using that does work... ``` >>> import re >>> re.match(fnmatch.translate('arn:*:redshift:*:*:dbuser:*/*'), 'arn:aws:redshift:us-west-2:528741615426:dbuser:the_cluster/the_user').group() 'arn:aws:redshift:us-west-2:528741615426:dbuser:the_cluster/the_user' ```
0.0
6f510f110286fb5a5e7d9b578aee506e99041d40
[ "tests/unit/test_formatting.py::TestFormatting::test_lambda_AddLayerVersionPermission", "tests/unit/test_formatting.py::TestFormatting::test_redshift_GetClusterCredentials" ]
[ "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_multiple_statements_and_actions", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_simple", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_invalid_sid", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_multiple_statements_one_bad", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_action", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_statement", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_not_json", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_opposites", "tests/unit/test_formatting.py::TestFormatting::test_condition", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific_bad_type", "tests/unit/test_formatting.py::TestFormatting::test_condition_bad_key", "tests/unit/test_formatting.py::TestFormatting::test_condition_mismatch", "tests/unit/test_formatting.py::TestFormatting::test_condition_multiple", "tests/unit/test_formatting.py::TestFormatting::test_condition_operator", "tests/unit/test_formatting.py::TestFormatting::test_condition_type_unqoted_bool", "tests/unit/test_formatting.py::TestFormatting::test_condition_with_MultiFactorAuthAge", "tests/unit/test_formatting.py::TestFormatting::test_condition_with_null" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-07 22:15:23+00:00
bsd-3-clause
2,024
duo-labs__parliament-6
diff --git a/parliament/statement.py b/parliament/statement.py index bf663c9..cd9ab34 100644 --- a/parliament/statement.py +++ b/parliament/statement.py @@ -632,6 +632,15 @@ class Statement: else: self.effect_allow = False + # Check Sid + if "Sid" in self.stmt and not re.fullmatch("[0-9A-Za-z]*", self.stmt["Sid"]): + self.add_finding( + "Statement Sid does match regex [0-9A-Za-z]*", + severity.MALFORMED, + location={"string": self.stmt}, + ) + return False + # Check Action if "Action" in self.stmt and "NotAction" in self.stmt: self.add_finding( diff --git a/utils/update_iam_data.py b/utils/update_iam_data.py index d9e45f9..e8a7b6c 100644 --- a/utils/update_iam_data.py +++ b/utils/update_iam_data.py @@ -15,7 +15,7 @@ Setup pip install beautifulsoup4 # Download files -wget -r -np -k -A .html -nc https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html +wget -r -np -k --accept 'list_*.html' --reject 'feedbackno.html','feedbackyes.html' -nc https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html """
duo-labs/parliament
c06bcde102981010baa7a7fe70ab35a2595d6f9b
diff --git a/tests/unit/test_formatting.py b/tests/unit/test_formatting.py index 98233d9..9a395e1 100644 --- a/tests/unit/test_formatting.py +++ b/tests/unit/test_formatting.py @@ -41,6 +41,18 @@ class TestFormatting(unittest.TestCase): ) assert_false(len(policy.findings) == 0, "Policy has no Statement") + def test_analyze_policy_string_invalid_sid(self): + policy = analyze_policy_string( + """{ + "Version": "2012-10-17", + "Statement": { + "Sid": "Statement With Spaces And Special Chars!?", + "Effect": "Allow", + "Action": "s3:listallmybuckets", + "Resource": "*"}}""" + ) + assert_false(len(policy.findings) == 0, "Policy statement has invalid Sid") + def test_analyze_policy_string_correct_simple(self): policy = analyze_policy_string( """{
Command for wget'ing IAM docs Saw this: https://github.com/duo-labs/parliament/blob/master/utils/update_iam_data.py#L18 As you know, I take a similar approach with policy sentry. I suggest modifying the command to this: ```bash wget -r -np -k --accept 'list_*.html' --reject 'feedbackno.html','feedbackyes.html' -nc https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html ``` This will remove all of the extraneous docs that you don't care about :)
0.0
c06bcde102981010baa7a7fe70ab35a2595d6f9b
[ "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_invalid_sid" ]
[ "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_multiple_statements_and_actions", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_simple", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_multiple_statements_one_bad", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_action", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_statement", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_not_json", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_opposites", "tests/unit/test_formatting.py::TestFormatting::test_condition", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific_bad_type", "tests/unit/test_formatting.py::TestFormatting::test_condition_bad_key", "tests/unit/test_formatting.py::TestFormatting::test_condition_mismatch", "tests/unit/test_formatting.py::TestFormatting::test_condition_multiple", "tests/unit/test_formatting.py::TestFormatting::test_condition_operator" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-11-21 19:29:13+00:00
bsd-3-clause
2,025
duo-labs__parliament-8
diff --git a/parliament/statement.py b/parliament/statement.py index bf663c9..cd9ab34 100644 --- a/parliament/statement.py +++ b/parliament/statement.py @@ -632,6 +632,15 @@ class Statement: else: self.effect_allow = False + # Check Sid + if "Sid" in self.stmt and not re.fullmatch("[0-9A-Za-z]*", self.stmt["Sid"]): + self.add_finding( + "Statement Sid does match regex [0-9A-Za-z]*", + severity.MALFORMED, + location={"string": self.stmt}, + ) + return False + # Check Action if "Action" in self.stmt and "NotAction" in self.stmt: self.add_finding(
duo-labs/parliament
c06bcde102981010baa7a7fe70ab35a2595d6f9b
diff --git a/tests/unit/test_formatting.py b/tests/unit/test_formatting.py index 98233d9..9a395e1 100644 --- a/tests/unit/test_formatting.py +++ b/tests/unit/test_formatting.py @@ -41,6 +41,18 @@ class TestFormatting(unittest.TestCase): ) assert_false(len(policy.findings) == 0, "Policy has no Statement") + def test_analyze_policy_string_invalid_sid(self): + policy = analyze_policy_string( + """{ + "Version": "2012-10-17", + "Statement": { + "Sid": "Statement With Spaces And Special Chars!?", + "Effect": "Allow", + "Action": "s3:listallmybuckets", + "Resource": "*"}}""" + ) + assert_false(len(policy.findings) == 0, "Policy statement has invalid Sid") + def test_analyze_policy_string_correct_simple(self): policy = analyze_policy_string( """{
Validate Statement Id values If set, the `Sid` field in IAM policies may only contain characters from `(A-Z,a-z,0-9)`. `parliament` should declare a finding if `Sid` has spaces or other invalid characters.
0.0
c06bcde102981010baa7a7fe70ab35a2595d6f9b
[ "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_invalid_sid" ]
[ "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_multiple_statements_and_actions", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_correct_simple", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_multiple_statements_one_bad", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_action", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_no_statement", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_not_json", "tests/unit/test_formatting.py::TestFormatting::test_analyze_policy_string_opposites", "tests/unit/test_formatting.py::TestFormatting::test_condition", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific", "tests/unit/test_formatting.py::TestFormatting::test_condition_action_specific_bad_type", "tests/unit/test_formatting.py::TestFormatting::test_condition_bad_key", "tests/unit/test_formatting.py::TestFormatting::test_condition_mismatch", "tests/unit/test_formatting.py::TestFormatting::test_condition_multiple", "tests/unit/test_formatting.py::TestFormatting::test_condition_operator" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-11-22 02:51:41+00:00
bsd-3-clause
2,026
duo-labs__py_webauthn-167
diff --git a/webauthn/helpers/parse_authenticator_data.py b/webauthn/helpers/parse_authenticator_data.py index c9d12ea..5792def 100644 --- a/webauthn/helpers/parse_authenticator_data.py +++ b/webauthn/helpers/parse_authenticator_data.py @@ -57,6 +57,23 @@ def parse_authenticator_data(val: bytes) -> AuthenticatorData: credential_id = val[pointer : pointer + credential_id_len] pointer += credential_id_len + """ + Some authenticators incorrectly compose authData when using EdDSA for their public keys. + A CBOR "Map of 3 items" (0xA3) should be "Map of 4 items" (0xA4), and if we manually adjust + the single byte there's a good chance the authData can be correctly parsed. Let's try to + detect when this happens and gracefully handle it. + """ + # Decodes to `{1: "OKP", 3: -8, -1: "Ed25519"}` (it's missing key -2 a.k.a. COSEKey.X) + bad_eddsa_cbor = bytearray.fromhex("a301634f4b500327206745643235353139") + # If we find the bytes here then let's fix the bad data + if val[pointer : pointer + len(bad_eddsa_cbor)] == bad_eddsa_cbor: + # Make a mutable copy of the bytes... + _val = bytearray(val) + # ...Fix the bad byte... + _val[pointer] = 0xA4 + # ...Then replace `val` with the fixed bytes + val = bytes(_val) + # Load the next CBOR-encoded value credential_public_key = cbor2.loads(val[pointer:]) credential_public_key_bytes = cbor2.dumps(credential_public_key)
duo-labs/py_webauthn
a86965850429b86c94ac18db875cbbf545d0ebe2
diff --git a/tests/test_parse_authenticator_data.py b/tests/test_parse_authenticator_data.py index c6e284c..f4e3d0d 100644 --- a/tests/test_parse_authenticator_data.py +++ b/tests/test_parse_authenticator_data.py @@ -182,3 +182,29 @@ class TestWebAuthnParseAuthenticatorData(TestCase): assert output.flags.be is True assert output.flags.be is True + + def test_parses_bad_eddsa_auth_data(self) -> None: + """ + Help out particular YubiKeys that incorrectly CBOR-encode authData when they use Ed25519 + for their public key. + + See https://github.com/duo-labs/py_webauthn/issues/160 + """ + auth_data = bytearray.fromhex( + "16B02DFBC3D4CCA37EBC2F6516659B12210DB9E1018AB9F13A9690638EA6FDA845000000012FC0579F811347EAB116BB5A8DB9202A0080E82FE6BDE300E4ECC93E0016448AD00FA6F28A011A6F87FF7B0CFCA499BEAF83344C3660B5ECABF72A3B2838A0CC7D87D3FA58292B53449CFF13AD69732D7521649D365CCBC5D0A0FA4B4E09EAE99537261F2F44093F8F4FD4CF5796E0FE58FF0615FFC5882836BBE7B99B08BE2986721C1C5A6AC7F32D3220D9B34D8DEE2FC9A301634F4B5003272067456432353531392198201618F6185918FA182E141875183A18841718521874187A18C51318D918C51883182D18ED181818EA188F182E187407185E18F41518CC18C9186D" + ) + + output = parse_authenticator_data(auth_data) + + cred_data = output.attested_credential_data + self.assertIsNotNone(cred_data) + assert cred_data # Make mypy happy + + self.assertEqual( + cred_data.credential_id.hex(), + "e82fe6bde300e4ecc93e0016448ad00fa6f28a011a6f87ff7b0cfca499beaf83344c3660b5ecabf72a3b2838a0cc7d87d3fa58292b53449cff13ad69732d7521649d365ccbc5d0a0fa4b4e09eae99537261f2f44093f8f4fd4cf5796e0fe58ff0615ffc5882836bbe7b99b08be2986721c1c5a6ac7f32d3220d9b34d8dee2fc9" + ) + self.assertEqual( + cred_data.credential_public_key.hex(), + "a401634f4b5003272067456432353531392198201618f6185918fa182e141875183a18841718521874187a18c51318d918c51883182d18ed181818ea188f182e187407185e18f41518cc18c9186d", + )
Systemic presence of extra byte for registration with eddsa In goal to register a passkey on a website, I use a php library (https://github.com/web-auth/webauthn-framework). When I try to register a new credential with eddsa as 'prefered' algorithm, the load of passkey's response failed for presence of extra bytes in authentication data .If I comment the check then all is good. I've tried to decompose the attestation object by hand and find that: ``` 00000000: 10100011 01100011 01100110 01101101 01110100 01100100 01101110 01101111 .cfmtdno map 3 txt 3 f m t txt 4 n o 00000008: 01101110 01100101 01100111 01100001 01110100 01110100 01010011 01110100 negattSt n e txt 7 a t t S t 00000016: 01101101 01110100 10100000 01101000 01100001 01110101 01110100 01101000 mt.hauth m t map 0 txt 8 a u t h 00000024: 01000100 01100001 01110100 01100001 01011001 00000001 00000101 00010110 DataY... ==> 25 means length is in 2 next bytes (total length 292, -261 = 31) D a t a byt 25 261 <rpIdHash 00000032: 10110000 00101101 11111011 11000011 11010100 11001100 10100011 01111110 .-.....~ 00000040: 10111100 00101111 01100101 00010110 01100101 10011011 00010010 00100001 ./e.e..! 00000048: 00001101 10111001 11100001 00000001 10001010 10111001 11110001 00111010 .......: 00000056: 10010110 10010000 01100011 10001110 10100110 11111101 10101000 01000101 ..c....E ==> flags UP:/:UV:/:/:/:AT:ED little-endian rpIdHash> <flags > 1 0 1 0 0 0 1 0 00000064: 00000000 00000000 00000000 00000001 00101111 11000000 01010111 10011111 ..../.W. ==> signCount: 1 <signCount > <aaguid <attestedCredentialData 00000072: 10000001 00010011 01000111 11101010 10110001 00010110 10111011 01011010 ..G....Z ==> aaguid: 2fc0579f-8113-47ea-b116-bb5a8db9202a 00000080: 10001101 10111001 00100000 00101010 00000000 10000000 11101000 00101111 .. *.../ ==> credentialIdLength: 128 aaguid> <credentialIdLen> <credentialId 00000088: 11100110 10111101 11100011 00000000 11100100 11101100 11001001 00111110 .......> 00000096: 00000000 00010110 01000100 10001010 11010000 00001111 10100110 11110010 ..D..... 00000104: 10001010 00000001 00011010 01101111 10000111 11111111 01111011 00001100 ...o..{. 00000112: 11111100 10100100 10011001 10111110 10101111 10000011 00110100 01001100 ......4L 00000120: 00110110 01100000 10110101 11101100 10101011 11110111 00101010 00111011 6`....*; 00000128: 00101000 00111000 10100000 11001100 01111101 10000111 11010011 11111010 (8..}... 00000136: 01011000 00101001 00101011 01010011 01000100 10011100 11111111 00010011 X)+SD... 00000144: 10101101 01101001 01110011 00101101 01110101 00100001 01100100 10011101 .is-u!d. 00000152: 00110110 01011100 11001011 11000101 11010000 10100000 11111010 01001011 6\.....K 00000160: 01001110 00001001 11101010 11101001 10010101 00110111 00100110 00011111 N....7&. 00000168: 00101111 01000100 00001001 00111111 10001111 01001111 11010100 11001111 /D.?.O.. 00000176: 01010111 10010110 11100000 11111110 01011000 11111111 00000110 00010101 W...X... 00000184: 11111111 11000101 10001000 00101000 00110110 10111011 11100111 10111001 ...(6... 00000192: 10011011 00001000 10111110 00101001 10000110 01110010 00011100 00011100 ...).r.. 00000200: 01011010 01101010 11000111 11110011 00101101 00110010 00100000 11011001 Zj..-2 . 00000208: 10110011 01001101 10001101 11101110 00101111 11001001 10100011 00000001 .M../... ==> 1 -> kty: OKP credentialId> map 3 uin 1 <credentialPublicKey 00000216: 01100011 01001111 01001011 01010000 00000011 00100111 00100000 01100111 cOKP.' g ==> 3 -> alg: -8 (eddsa) txt 3 O K P uin 3 nin 7 nin 0 txt 7 00000224: 01000101 01100100 00110010 00110101 00110101 00110001 00111001 00100001 Ed25519! ==> -1 -> crv: Ed25519 E d 2 5 5 1 9 nin 1 ==> -2 -> should be public key (bstr) credentialPublicKey> <extensions? (should be a map 101 not a negative integer 001) attestedCredentialData> 00000232: 10011000 00100000 00010110 00011000 11110110 00011000 01011001 00011000 . ....Y. arr 24 32 uin 22 uin 24 246 uin 24 89 uin 24 00000240: 11111010 00011000 00101110 00010100 00011000 01110101 00011000 00111010 .....u.: 250 uin 24 46 uin 20 uin 24 117 uin 24 58 00000248: 00011000 10000100 00010111 00011000 01010010 00011000 01110100 00011000 ....R.t. uin 24 132 uin 23 uin 24 82 uin 24 116 uin 24 00000256: 01111010 00011000 11000101 00010011 00011000 11011001 00011000 11000101 z....... 122 uin 24 197 uin 19 uin 24 217 uin 24 197 00000264: 00011000 10000011 00011000 00101101 00011000 11101101 00011000 00011000 ...-.... uin 24 131 uin 24 45 uin 24 237 uin 24 24 00000272: 00011000 11101010 00011000 10001111 00011000 00101110 00011000 01110100 .......t uin 24 234 uin 24 143 uin 24 46 uin 24 116 00000280: 00000111 00011000 01011110 00011000 11110100 00010101 00011000 11001100 ..^..... uin 7 uin 24 94 uin 24 244 uin 21 uin 24 204 00000288: 00011000 11001001 00011000 01101101 ...m uin 24 201 uin 24 109 ``` If we follow strictly the webauthn doc, yes, there is some extra bytes. So to check if the problem comes from the library I use, I decide to try another one (yours). I've write this little script: ```python import sys from webauthn.helpers import (parse_attestation_object, base64url_to_bytes) if __name__ == "__main__": if len(sys.argv) != 2: print("Expect one argument (filename)") exit(1) filename = sys.argv[1] print("decode", filename) file = open(filename, "r") base64 = file.read() bytes = base64url_to_bytes(base64) parse_attestation_object(bytes) pass ``` The file contains: ``` o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVkBBRawLfvD1MyjfrwvZRZlmxIhDbnhAYq58TqWkGOOpv2oRQAAAAEvwFefgRNH6rEWu1qNuSAqAIDoL-a94wDk7Mk-ABZEitAPpvKKARpvh_97DPykmb6vgzRMNmC17Kv3KjsoOKDMfYfT-lgpK1NEnP8TrWlzLXUhZJ02XMvF0KD6S04J6umVNyYfL0QJP49P1M9XluD-WP8GFf_FiCg2u-e5mwi-KYZyHBxaasfzLTIg2bNNje4vyaMBY09LUAMnIGdFZDI1NTE5IZggFhj2GFkY-hguFBh1GDoYhBcYUhh0GHoYxRMY2RjFGIMYLRjtGBgY6hiPGC4YdAcYXhj0FRjMGMkYbQ ``` But your lib also raised an error `webauthn.helpers.exceptions.InvalidAuthenticatorDataStructure: Leftover bytes detected while parsing authenticator data`. So, did we really need to check that ? I use a Yubikey 5 NFC (firmware 5.4.3) and have also opened an issue on the php lib https://github.com/web-auth/webauthn-framework/issues/436
0.0
a86965850429b86c94ac18db875cbbf545d0ebe2
[ "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_parses_bad_eddsa_auth_data" ]
[ "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_correctly_parses_attested_credential_data", "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_correctly_parses_simple", "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_parses_attested_credential_data_and_extension_data", "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_parses_backup_state_flags", "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_parses_only_extension_data", "tests/test_parse_authenticator_data.py::TestWebAuthnParseAuthenticatorData::test_parses_uv_false" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-08-15 05:16:10+00:00
bsd-3-clause
2,027
duosecurity__duo_client_python-137
diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml index 4b666cd..d61eb4f 100644 --- a/.github/workflows/python-ci.yml +++ b/.github/workflows/python-ci.yml @@ -7,7 +7,7 @@ jobs: strategy: matrix: - python-version: [2.7, 3.5, 3.6, 3.7, 3.8] + python-version: [2.7, 3.5, 3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 diff --git a/duo_client/admin.py b/duo_client/admin.py index b9d68e6..57a144d 100644 --- a/duo_client/admin.py +++ b/duo_client/admin.py @@ -1058,6 +1058,21 @@ class Admin(client.Client): params = {} return self.json_api_call('DELETE', path, params) + def get_endpoint(self, epkey): + """ + Get a single endpoint from the AdminAPI by a supplied epkey. + + Params: + epkey (str) - The supplied endpoint key to fetch. + + Returns: The endpoint object represented as a dict. + Raises: + RuntimeError: if the request returns a non-200 status response. + """ + escaped_epkey = six.moves.urllib.parse.quote_plus(str(epkey)) + path = '/admin/v1/endpoints/' + escaped_epkey + return self.json_api_call('GET', path, {}) + def get_endpoints_iterator(self): """ Returns iterator of endpoints objects.
duosecurity/duo_client_python
34c165c3a74ec791c5e2079872b8dceba14e3d5d
diff --git a/tests/admin/test_endpoints.py b/tests/admin/test_endpoints.py index 8f19861..8a04170 100644 --- a/tests/admin/test_endpoints.py +++ b/tests/admin/test_endpoints.py @@ -80,6 +80,19 @@ class TestEndpoints(TestAdmin): 'offset': ['20'], }) + def test_get_endpoint(self): + """ Test getting a single endpoint. + """ + epkey = 'EP18JX1A10AB102M2T2X' + response = self.client_list.get_endpoint(epkey)[0] + (uri, args) = response['uri'].split('?') + self.assertEqual(response['method'], 'GET') + self.assertEqual(uri, '/admin/v1/endpoints/' + epkey) + self.assertEqual( + util.params_to_dict(args), + { + 'account_id': [self.client.account_id], + }) if __name__ == '__main__': unittest.main()
Retrieve Endpoint by ID Would be great if there was a function in the admin client that covered this endpoint. `/admin/v1/endpoints/[epkey]`
0.0
34c165c3a74ec791c5e2079872b8dceba14e3d5d
[ "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoint" ]
[ "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoints", "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoints_iterator", "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoints_limit", "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoints_limit_and_offset", "tests/admin/test_endpoints.py::TestEndpoints::test_get_endpoints_offset" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-03-23 23:45:56+00:00
bsd-3-clause
2,028
duosecurity__duo_client_python-86
diff --git a/duo_client/admin.py b/duo_client/admin.py index 48bb1d6..c482019 100644 --- a/duo_client/admin.py +++ b/duo_client/admin.py @@ -2001,7 +2001,7 @@ class Admin(client.Client): return self.json_api_call('GET', url + group_id, {}) - def get_group_users(self, group_id, limit=100, offset=0): + def get_group_users(self, group_id, limit=None, offset=0): """ Get a paginated list of users associated with the specified group. @@ -2010,13 +2010,28 @@ class Admin(client.Client): limit - The maximum number of records to return. Maximum is 500. (Optional) offset - The offset of the first record to return. (Optional) """ - return self.json_api_call( + (limit, offset) = self.normalize_paging_args(limit, offset) + if limit: + return self.json_api_call( + 'GET', + '/admin/v2/groups/' + group_id + '/users', + { + 'limit': limit, + 'offset': offset, + }) + return list(self.get_group_users_iterator(group_id)) + + def get_group_users_iterator(self, group_id): + """ + Returns an iterator of users associated with the specified group. + + group_id - The id of the group (Required) + """ + return self.json_paging_api_call( 'GET', '/admin/v2/groups/' + group_id + '/users', - { - 'limit': str(limit), - 'offset': str(offset), - }) + {} + ) def create_group(self, name, desc=None,
duosecurity/duo_client_python
c69c3da2e13f8a7680c06d94f80fadb23eb49ec9
diff --git a/tests/admin/test_groups.py b/tests/admin/test_groups.py index 6bbed7f..7e516e1 100644 --- a/tests/admin/test_groups.py +++ b/tests/admin/test_groups.py @@ -119,7 +119,7 @@ class TestGroups(TestAdmin): def test_get_group_users(self): """ Test for getting list of users associated with a group """ - response = self.client.get_group_users('ABC123') + response = self.client_list.get_group_users('ABC123')[0] uri, args = response['uri'].split('?') self.assertEqual(response['method'], 'GET') @@ -132,6 +132,69 @@ class TestGroups(TestAdmin): 'offset': ['0'], }) + def test_get_group_users_with_offset(self): + """Test to get users by group id with pagination params + """ + response = self.client_list.get_group_users('ABC123', offset=30)[0] + uri, args = response['uri'].split('?') + + self.assertEqual(response['method'], 'GET') + self.assertEqual(uri, '/admin/v2/groups/ABC123/users') + self.assertEqual(util.params_to_dict(args), + { + 'account_id':[self.client.account_id], + 'limit': ['100'], + 'offset': ['0'], + }) + + def test_get_group_users_with_limit(self): + """Test to get users by group id with pagination params + """ + response = self.client_list.get_group_users('ABC123', limit=30)[0] + uri, args = response['uri'].split('?') + + self.assertEqual(response['method'], 'GET') + self.assertEqual(uri, '/admin/v2/groups/ABC123/users') + self.assertEqual(util.params_to_dict(args), + { + 'account_id':[self.client.account_id], + 'limit': ['30'], + 'offset': ['0'], + }) + + def test_get_group_users_with_limit_and_offset(self): + """Test to get users by group id with pagination params + """ + response = self.client_list.get_group_users( + 'ABC123', limit=30, offset=60)[0] + uri, args = response['uri'].split('?') + + self.assertEqual(response['method'], 'GET') + self.assertEqual(uri, '/admin/v2/groups/ABC123/users') + self.assertEqual(util.params_to_dict(args), + { + 'account_id':[self.client.account_id], + 'limit': ['30'], + 'offset': ['60'], + }) + + def test_get_group_users_iterator(self): + """Test to get user iterator by group id + """ + iterator = self.client_list.get_group_users_iterator( + 'ABC123') + response = next(iterator) + uri, args = response['uri'].split('?') + + self.assertEqual(response['method'], 'GET') + self.assertEqual(uri, '/admin/v2/groups/ABC123/users') + self.assertEqual(util.params_to_dict(args), + { + 'account_id':[self.client.account_id], + 'limit': ['100'], + 'offset': ['0'], + }) + def test_delete_group(self): """ Test for deleting a group """
group pagination not part of the code Hi, In `duo_client/admin.py`, there are `get_user_groups` and `get_user_groups_iterator` which (via `json_paging_api_call` in `duo_client/client.py`) seem to be doing the pagination for us (kinda already touched on in #63). Minor note: per https://duo.com/docs/adminapi#retrieve-groups-by-user-id, `get_user_groups` should have limits of 100/500, but the API shows None. I don't particularly care here - you're doing the paging for me, so, "cool!" What I'm opening an issue over is, `get_group_users` looks the same as `get_user_groups` from the docs https://duo.com/docs/adminapi#v2-groups-get-users. ("Same" as in, both API calls take optional paging-related parameters, with limits of 100/500 defined; obviously they return different data.) But there's no similar iterator/listmaker offered for `get_group_users` - you get back one limit-sized slurp of data. I'm not seeing the metadata get to me from a call to `get_group_users` in order to manage my own pagination, but that could be an error on my part. If it's an oversight that `get_group_users` doesn't page, well, here's a request. If it's deliberate, is there something you can maybe drop in a comment for why this call is seemingly unique/different? Thanks!
0.0
c69c3da2e13f8a7680c06d94f80fadb23eb49ec9
[ "tests/admin/test_groups.py::TestGroups::test_get_group_users_iterator", "tests/admin/test_groups.py::TestGroups::test_get_group_users_with_offset" ]
[ "tests/admin/test_groups.py::TestGroups::test_delete_group", "tests/admin/test_groups.py::TestGroups::test_get_group_users", "tests/admin/test_groups.py::TestGroups::test_get_group_users_with_limit", "tests/admin/test_groups.py::TestGroups::test_get_group_users_with_limit_and_offset", "tests/admin/test_groups.py::TestGroups::test_get_group_v1", "tests/admin/test_groups.py::TestGroups::test_get_group_v2", "tests/admin/test_groups.py::TestGroups::test_get_groups", "tests/admin/test_groups.py::TestGroups::test_get_groups_generator", "tests/admin/test_groups.py::TestGroups::test_get_groups_limit", "tests/admin/test_groups.py::TestGroups::test_get_groups_limit_offset", "tests/admin/test_groups.py::TestGroups::test_get_groups_offset", "tests/admin/test_groups.py::TestGroups::test_modify_group" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2019-02-25 18:34:20+00:00
bsd-3-clause
2,029
dwavesystems__dimod-331
diff --git a/dimod/binary_quadratic_model.py b/dimod/binary_quadratic_model.py index f6121123..28996cd9 100644 --- a/dimod/binary_quadratic_model.py +++ b/dimod/binary_quadratic_model.py @@ -981,6 +981,22 @@ class BinaryQuadraticModel(abc.Sized, abc.Container, abc.Iterable): self.add_offset(value * linear[v]) self.remove_variable(v) + def fix_variables(self, fixed): + """Fix the value of the variables and remove it from a binary quadratic model. + + Args: + fixed (dict): + A dictionary of variable assignments. + + Examples: + >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN) + >>> bqm.fix_variables({'a': -1, 'b': +1}) + + """ + for v, val in fixed.items(): + self.fix_variable(v, val) + + def flip_variable(self, v): """Flip variable v in a binary quadratic model. diff --git a/docs/reference/binary_quadratic_model.rst b/docs/reference/binary_quadratic_model.rst index 882831e2..76150d8e 100644 --- a/docs/reference/binary_quadratic_model.rst +++ b/docs/reference/binary_quadratic_model.rst @@ -59,6 +59,7 @@ Transformations BinaryQuadraticModel.contract_variables BinaryQuadraticModel.fix_variable + BinaryQuadraticModel.fix_variables BinaryQuadraticModel.flip_variable BinaryQuadraticModel.relabel_variables BinaryQuadraticModel.scale
dwavesystems/dimod
e89fd52174afdcb783a7859892b328ee989e01dd
diff --git a/tests/test_binary_quadratic_model.py b/tests/test_binary_quadratic_model.py index b43d8e27..7442c21a 100644 --- a/tests/test_binary_quadratic_model.py +++ b/tests/test_binary_quadratic_model.py @@ -757,6 +757,11 @@ class TestBinaryQuadraticModel(unittest.TestCase): self.assertConsistentBQM(bqm) self.assertEqual(bqm, dimod.BinaryQuadraticModel({0: -1, 1: 1}, {(0, 1): -1.}, .5, dimod.SPIN)) + def test_fix_variables(self): + bqm = dimod.BinaryQuadraticModel({'a': .3}, {('a', 'b'): -1}, 1.2, dimod.SPIN) + bqm.fix_variables({'a': -1, 'b': +1}) + + def test_fix_variable(self): # spin model, fix variable to +1 bqm = dimod.BinaryQuadraticModel({'a': .3}, {('a', 'b'): -1}, 1.2, dimod.SPIN)
Add fix_variables (fix multiple variables at once) **Application** For example, given a multiplication circuit CSP, I'd like to do this: ``` In [142]: bqm.fix_variables({'a0': 1, 'a1': 0, 'a2': 1, 'b0': 1, 'b1': 1, 'b2': 0}) ``` Instead of this: ``` In [142]: bqm.fix_variable('a0', 1) In [143]: bqm.fix_variable('a1', 0) In [144]: bqm.fix_variable('a2', 1) In [145]: bqm.fix_variable('b0', 1) In [146]: bqm.fix_variable('b1', 1) In [147]: bqm.fix_variable('b2', 0) ``` **Proposed Solution** Enable fixing multiple variables in a single command. **Alternatives Considered** Using fix_variables multiple times. **Additional Context** I think there are lots of situation where users will fix multiple variables and would like to manipulate the values using dicts.
0.0
e89fd52174afdcb783a7859892b328ee989e01dd
[ "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_fix_variables" ]
[ "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__contains__", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__eq__", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__iter__", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__len__", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__repr__", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interaction", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interaction_counterpart", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interactions_from", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_offset", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variable", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variable_counterpart", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variables_from", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_binary_property", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_binary_property_relabel", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_change_vartype", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction_quadratic", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction_vartype", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_contract_variables", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_copy", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_fix_variable", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_flip_variable", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_normalize", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_partial_relabel_copy", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_partial_relabel_inplace", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical_copy", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical_inplace", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_with_identity", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_with_overlap", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_interaction", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_interactions_from", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_offset", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_variable", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_variables_from", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_scale", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_scale_exclusions", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_spin_property", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_spin_property_relabel", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_update", "tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_variables", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_empty_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_empty_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_empty_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_empty_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_two_digit_integers_string", "tests/test_binary_quadratic_model.py::TestConvert::test_empty", "tests/test_binary_quadratic_model.py::TestConvert::test_from_coo_file", "tests/test_binary_quadratic_model.py::TestConvert::test_from_coo_string", "tests/test_binary_quadratic_model.py::TestConvert::test_from_ising", "tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_matrix", "tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_vectors", "tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_vectors_labels", "tests/test_binary_quadratic_model.py::TestConvert::test_from_qubo", "tests/test_binary_quadratic_model.py::TestConvert::test_functional_to_and_from_json", "tests/test_binary_quadratic_model.py::TestConvert::test_functional_to_and_from_json_empty", "tests/test_binary_quadratic_model.py::TestConvert::test_functional_to_and_from_json_with_info", "tests/test_binary_quadratic_model.py::TestConvert::test_info", "tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_empty_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_empty_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_typical_BINARY", "tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_typical_SPIN", "tests/test_binary_quadratic_model.py::TestConvert::test_to_ising_binary_to_ising", "tests/test_binary_quadratic_model.py::TestConvert::test_to_ising_spin_to_ising", "tests/test_binary_quadratic_model.py::TestConvert::test_to_json_file", "tests/test_binary_quadratic_model.py::TestConvert::test_to_json_file_empty", "tests/test_binary_quadratic_model.py::TestConvert::test_to_json_string", "tests/test_binary_quadratic_model.py::TestConvert::test_to_json_string_empty", "tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_matrix", "tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors", "tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors_labels_sorted", "tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors_sorted", "tests/test_binary_quadratic_model.py::TestConvert::test_to_qubo_binary_to_qubo", "tests/test_binary_quadratic_model.py::TestConvert::test_to_qubo_spin_to_qubo" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-19 19:59:00+00:00
apache-2.0
2,030
dwavesystems__dwave-cloud-client-120
diff --git a/dwave/cloud/cli.py b/dwave/cloud/cli.py index 0e5a503..da8a816 100644 --- a/dwave/cloud/cli.py +++ b/dwave/cloud/cli.py @@ -1,18 +1,72 @@ from __future__ import print_function +from functools import wraps + import click from timeit import default_timer as timer from dwave.cloud import Client from dwave.cloud.utils import readline_input +from dwave.cloud.package_info import __title__, __version__ from dwave.cloud.exceptions import ( SolverAuthenticationError, InvalidAPIResponseError, UnsupportedSolverError) from dwave.cloud.config import ( load_config_from_files, get_default_config, - get_configfile_path, get_default_configfile_path) + get_configfile_path, get_default_configfile_path, + get_configfile_paths) + + +def click_info_switch(f): + """Decorator to create Click eager info switch option, as described in docs: + http://click.pocoo.org/6/options/#callbacks-and-eager-options. + + Takes a no-argument function and abstracts the boilerplate required by + Click (value checking, exit on done). + + Example: + + @click.option('--my-option', is_flag=True, callback=my_option, + expose_value=False, is_eager=True) + def test(): + pass + + @click_info_switch + def my_option() + click.echo('some info related to my switch') + """ + + @wraps(f) + def wrapped(ctx, param, value): + if not value or ctx.resilient_parsing: + return + f() + ctx.exit() + return wrapped + + +@click_info_switch +def list_config_files(): + for path in get_configfile_paths(): + click.echo(path) + +@click_info_switch +def list_system_config(): + for path in get_configfile_paths(user=False, local=False, only_existing=False): + click.echo(path) + +@click_info_switch +def list_user_config(): + for path in get_configfile_paths(system=False, local=False, only_existing=False): + click.echo(path) + +@click_info_switch +def list_local_config(): + for path in get_configfile_paths(system=False, user=False, only_existing=False): + click.echo(path) @click.group() [email protected]_option(prog_name=__title__, version=__version__) def cli(): """D-Wave cloud tool.""" @@ -22,6 +76,18 @@ def cli(): type=click.Path(exists=True, dir_okay=False)) @click.option('--profile', default=None, help='Connection profile name (config section name)') [email protected]('--list-config-files', is_flag=True, callback=list_config_files, + expose_value=False, is_eager=True, + help='List paths of all config files detected on this system') [email protected]('--list-system-paths', is_flag=True, callback=list_system_config, + expose_value=False, is_eager=True, + help='List paths of system-wide config files examined') [email protected]('--list-user-paths', is_flag=True, callback=list_user_config, + expose_value=False, is_eager=True, + help='List paths of user-local config files examined') [email protected]('--list-local-paths', is_flag=True, callback=list_local_config, + expose_value=False, is_eager=True, + help='List paths of local config files examined') def configure(config_file, profile): """Create and/or update cloud client configuration file.""" diff --git a/dwave/cloud/config.py b/dwave/cloud/config.py index e84711f..e61d1b1 100644 --- a/dwave/cloud/config.py +++ b/dwave/cloud/config.py @@ -13,38 +13,61 @@ CONF_AUTHOR = "dwavesystem" CONF_FILENAME = "dwave.conf" -def detect_existing_configfile_paths(): - """Returns the list of existing config files found on disk. +def get_configfile_paths(system=True, user=True, local=True, only_existing=True): + """Returns a list of (existing) config files found on disk. Candidates examined depend on the OS, but for Linux possible list is: ``dwave.conf`` in CWD, user-local ``.config/dwave/``, system-wide ``/etc/dwave/``. For details, see :func:`load_config_from_file`. + + Args: + system (boolean, default=True): + Search for system-wide config files. + + user (boolean, default=True): + Search for user-local config files. + + local (boolean, default=True): + Search for local config files (in CWD). + + only_existing (boolean, default=True): + Return only paths for files that exist on disk. + + Returns: + list[str]: + A list of config file paths. """ + candidates = [] + # system-wide has the lowest priority, `/etc/dwave/dwave.conf` - candidates = homebase.site_config_dir_list( - app_author=CONF_AUTHOR, app_name=CONF_APP, - use_virtualenv=False, create=False) + if system: + candidates.extend(homebase.site_config_dir_list( + app_author=CONF_AUTHOR, app_name=CONF_APP, + use_virtualenv=False, create=False)) # user-local will override it, `~/.config/dwave/dwave.conf` - candidates.append(homebase.user_config_dir( - app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, - use_virtualenv=False, create=False)) + if user: + candidates.append(homebase.user_config_dir( + app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, + use_virtualenv=False, create=False)) # highest priority (overrides all): `./dwave.conf` - candidates.append(".") + if local: + candidates.append(".") paths = [os.path.join(base, CONF_FILENAME) for base in candidates] - existing_paths = [path for path in paths if os.path.exists(path)] + if only_existing: + paths = list(filter(os.path.exists, paths)) - return existing_paths + return paths def get_configfile_path(): """Returns the highest-priority existing config file from a list - of possible candidates returned by `detect_existing_configfile_paths()`, and + of possible candidates returned by `get_configfile_paths()`, and ``None`` if no candidate config file exists.""" - paths = detect_existing_configfile_paths() + paths = get_configfile_paths() return paths[-1] if paths else None @@ -123,7 +146,7 @@ def load_config_from_files(filenames=None): Config file parse failed. """ if filenames is None: - filenames = detect_existing_configfile_paths() + filenames = get_configfile_paths() config = configparser.ConfigParser(default_section="defaults") for filename in filenames:
dwavesystems/dwave-cloud-client
840af65d31c8b24fb3c238c2343ae9dea5f0301e
diff --git a/tests/test_cli.py b/tests/test_cli.py index d48105b..266ee25 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -40,6 +40,43 @@ class TestCli(unittest.TestCase): for val in values: self.assertEqual(config.get(val), val) + def test_configure_list_config(self): + runner = CliRunner() + with runner.isolated_filesystem(): + touch('dwave.conf') + with mock.patch('dwave.cloud.config.homebase.site_config_dir_list', + lambda **kw: ['/system1', '/system2']): + with mock.patch('dwave.cloud.config.homebase.user_config_dir', + lambda **kw: '/user'): + with mock.patch('os.path.exists', lambda *x: True): + # test --list-config-files + result = runner.invoke(cli, [ + 'configure', '--list-config-files' + ]) + self.assertEqual(result.output.strip(), '\n'.join([ + '/system1/dwave.conf', '/system2/dwave.conf', + '/user/dwave.conf', './dwave.conf'])) + + # test --list-system-paths + result = runner.invoke(cli, [ + 'configure', '--list-system-paths' + ]) + self.assertEqual(result.output.strip(), '\n'.join([ + '/system1/dwave.conf', '/system2/dwave.conf'])) + + # test --list-user-paths + result = runner.invoke(cli, [ + 'configure', '--list-user-paths' + ]) + self.assertEqual(result.output.strip(), '/user/dwave.conf') + + # test --list-local-paths + result = runner.invoke(cli, [ + 'configure', '--list-local-paths' + ]) + self.assertEqual(result.output.strip(), './dwave.conf') + + def test_ping(self): config_file = 'dwave.conf' profile = 'profile' diff --git a/tests/test_config.py b/tests/test_config.py index 84ef393..11d26ff 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -9,7 +9,7 @@ from functools import partial from dwave.cloud.exceptions import ConfigFileParseError, ConfigFileReadError from dwave.cloud.testing import mock, iterable_mock_open from dwave.cloud.config import ( - detect_existing_configfile_paths, load_config_from_files, load_config) + get_configfile_paths, load_config_from_files, load_config) class TestConfig(unittest.TestCase): @@ -70,7 +70,7 @@ class TestConfig(unittest.TestCase): def test_no_config_detected(self): """When no config file detected, `load_config_from_files` should return empty config.""" - with mock.patch("dwave.cloud.config.detect_existing_configfile_paths", lambda: []): + with mock.patch("dwave.cloud.config.get_configfile_paths", lambda: []): self.assertFalse(load_config_from_files().sections()) def test_invalid_filename_given(self): @@ -79,7 +79,7 @@ class TestConfig(unittest.TestCase): def test_config_file_detection_cwd(self): configpath = "./dwave.conf" with mock.patch("os.path.exists", lambda path: path == configpath): - self.assertEqual(detect_existing_configfile_paths(), [configpath]) + self.assertEqual(get_configfile_paths(), [configpath]) def test_config_file_detection_user(self): if sys.platform == 'win32': @@ -91,7 +91,7 @@ class TestConfig(unittest.TestCase): configpath = os.path.expanduser("~/.config/dwave/dwave.conf") with mock.patch("os.path.exists", lambda path: path == configpath): - self.assertEqual(detect_existing_configfile_paths(), [configpath]) + self.assertEqual(get_configfile_paths(), [configpath]) def test_config_file_detection_system(self): if sys.platform == 'win32': @@ -103,11 +103,11 @@ class TestConfig(unittest.TestCase): configpath = "/etc/xdg/dwave/dwave.conf" with mock.patch("os.path.exists", lambda path: path == configpath): - self.assertEqual(detect_existing_configfile_paths(), [configpath]) + self.assertEqual(get_configfile_paths(), [configpath]) def test_config_file_detection_nonexisting(self): with mock.patch("os.path.exists", lambda path: False): - self.assertEqual(detect_existing_configfile_paths(), []) + self.assertEqual(get_configfile_paths(), []) def _assert_config_valid(self, config): @@ -281,7 +281,7 @@ class TestConfig(unittest.TestCase): endpoint = beta """ - with mock.patch("dwave.cloud.config.detect_existing_configfile_paths", + with mock.patch("dwave.cloud.config.get_configfile_paths", lambda: ['config_system', 'config_user']): # test per-key override diff --git a/tests/test_mock_solver_loading.py b/tests/test_mock_solver_loading.py index d1ee10c..21adf08 100644 --- a/tests/test_mock_solver_loading.py +++ b/tests/test_mock_solver_loading.py @@ -210,7 +210,7 @@ solver = alpha-solver # patch the new config loading mechanism, to test only legacy config loading [email protected]("dwave.cloud.config.detect_existing_configfile_paths", lambda: []) [email protected]("dwave.cloud.config.get_configfile_paths", lambda: []) class MockLegacyConfiguration(unittest.TestCase): """Ensure that the precedence of configuration sources is followed.""" @@ -265,7 +265,7 @@ class MockLegacyConfiguration(unittest.TestCase): def test_only_file_key(self): """If give a name from the config file the proper URL should be loaded.""" with mock.patch("dwave.cloud.config.open", iterable_mock_open(config_body), create=True): - with mock.patch("dwave.cloud.config.detect_existing_configfile_paths", lambda *x: ['file']): + with mock.patch("dwave.cloud.config.get_configfile_paths", lambda *x: ['file']): with Client.from_config(profile='alpha') as client: client.session.get = GetEvent.handle try:
Add option(s) to list system/user/local config lookup paths in CLI tool Something like: ``` $ dwave --list-system /usr/share/dwave/dwave.conf /usr/local/share/dwave/dwave.conf $ dwave --list-user /home/user/.config/dwave/dwave.conf $ dwave --list-local ./dwave.conf ```
0.0
840af65d31c8b24fb3c238c2343ae9dea5f0301e
[ "tests/test_cli.py::TestCli::test_configure", "tests/test_cli.py::TestCli::test_configure_list_config", "tests/test_cli.py::TestCli::test_ping", "tests/test_config.py::TestConfig::test_config_file_detection_cwd", "tests/test_config.py::TestConfig::test_config_file_detection_nonexisting", "tests/test_config.py::TestConfig::test_config_file_detection_system", "tests/test_config.py::TestConfig::test_config_file_detection_user", "tests/test_config.py::TestConfig::test_config_load__profile_arg_nonexisting", "tests/test_config.py::TestConfig::test_config_load__profile_first_section", "tests/test_config.py::TestConfig::test_config_load__profile_from_defaults", "tests/test_config.py::TestConfig::test_config_load_configfile_arg", "tests/test_config.py::TestConfig::test_config_load_configfile_arg_profile_default", "tests/test_config.py::TestConfig::test_config_load_configfile_arg_profile_default_nonexisting", "tests/test_config.py::TestConfig::test_config_load_configfile_detect", "tests/test_config.py::TestConfig::test_config_load_configfile_detect_profile_env", "tests/test_config.py::TestConfig::test_config_load_configfile_env", "tests/test_config.py::TestConfig::test_config_load_configfile_env_profile_env", "tests/test_config.py::TestConfig::test_config_load_configfile_env_profile_env_key_arg", "tests/test_config.py::TestConfig::test_config_load_force_autodetection", "tests/test_config.py::TestConfig::test_config_load_from_file", "tests/test_config.py::TestConfig::test_config_load_from_file__invalid_format__duplicate_sections", "tests/test_config.py::TestConfig::test_config_load_multiple_configfiles", "tests/test_config.py::TestConfig::test_config_load_skip_configfiles", "tests/test_config.py::TestConfig::test_invalid_filename_given", "tests/test_config.py::TestConfig::test_no_config_detected", "tests/test_mock_solver_loading.py::MockConnectivityTests::test_bad_token", "tests/test_mock_solver_loading.py::MockConnectivityTests::test_bad_url", "tests/test_mock_solver_loading.py::MockConnectivityTests::test_good_connection", "tests/test_mock_solver_loading.py::MockSolverLoading::test_load_all_solvers", "tests/test_mock_solver_loading.py::MockSolverLoading::test_load_missing_solver", "tests/test_mock_solver_loading.py::MockSolverLoading::test_load_solver", "tests/test_mock_solver_loading.py::MockSolverLoading::test_load_solver_broken_response", "tests/test_mock_solver_loading.py::MockSolverLoading::test_load_solver_missing_data", "tests/test_mock_solver_loading.py::MockSolverLoading::test_solver_filtering_in_client", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_env_args_set", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_env_with_file_set", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_explicit_only", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_explicit_with_file", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_file_read_error", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_nonexisting_file", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_only_file", "tests/test_mock_solver_loading.py::MockLegacyConfiguration::test_only_file_key" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-04-16 22:18:41+00:00
apache-2.0
2,031
dwavesystems__dwave-cloud-client-126
diff --git a/dwave/cloud/cli.py b/dwave/cloud/cli.py index d2a1e95..b4b37d9 100644 --- a/dwave/cloud/cli.py +++ b/dwave/cloud/cli.py @@ -8,9 +8,10 @@ from dwave.cloud import Client from dwave.cloud.utils import readline_input from dwave.cloud.package_info import __title__, __version__ from dwave.cloud.exceptions import ( - SolverAuthenticationError, InvalidAPIResponseError, UnsupportedSolverError) + SolverAuthenticationError, InvalidAPIResponseError, UnsupportedSolverError, + ConfigFileReadError, ConfigFileParseError) from dwave.cloud.config import ( - load_config_from_files, get_default_config, + load_profile_from_files, load_config_from_files, get_default_config, get_configfile_path, get_default_configfile_path, get_configfile_paths) @@ -64,6 +65,29 @@ def list_local_config(): click.echo(path) +def inspect_config(ctx, param, value): + if not value or ctx.resilient_parsing: + return + + config_file = ctx.params.get('config_file') + profile = ctx.params.get('profile') + + try: + section = load_profile_from_files( + [config_file] if config_file else None, profile) + + click.echo("Config file: {}".format(config_file if config_file else "auto-detected")) + click.echo("Profile: {}".format(profile if profile else "auto-detected")) + click.echo("---") + for key, val in section.items(): + click.echo("{} = {}".format(key, val)) + + except (ValueError, ConfigFileReadError, ConfigFileParseError) as e: + click.echo(e) + + ctx.exit() + + @click.group() @click.version_option(prog_name=__title__, version=__version__) def cli(): @@ -71,10 +95,13 @@ def cli(): @cli.command() [email protected]('--config-file', default=None, help='Config file path', - type=click.Path(exists=False, dir_okay=False)) [email protected]('--profile', default=None, [email protected]('--config-file', '-c', default=None, is_eager=True, + type=click.Path(exists=False, dir_okay=False), + help='Config file path') [email protected]('--profile', '-p', default=None, is_eager=True, help='Connection profile name (config section name)') [email protected]('--inspect', is_flag=True, expose_value=False, callback=inspect_config, + help='Only inspect existing config/profile (no update)') @click.option('--list-config-files', is_flag=True, callback=list_config_files, expose_value=False, is_eager=True, help='List paths of all config files detected on this system') @@ -163,9 +190,9 @@ def configure(config_file, profile): @cli.command() [email protected]('--config-file', default=None, help='Config file path', [email protected]('--config-file', '-c', default=None, help='Config file path', type=click.Path(exists=True, dir_okay=False)) [email protected]('--profile', default=None, help='Connection profile name') [email protected]('--profile', '-p', default=None, help='Connection profile name') def ping(config_file, profile): """Ping the QPU by submitting a single-qubit problem.""" diff --git a/dwave/cloud/config.py b/dwave/cloud/config.py index e61d1b1..ae2e9c1 100644 --- a/dwave/cloud/config.py +++ b/dwave/cloud/config.py @@ -18,7 +18,7 @@ def get_configfile_paths(system=True, user=True, local=True, only_existing=True) Candidates examined depend on the OS, but for Linux possible list is: ``dwave.conf`` in CWD, user-local ``.config/dwave/``, system-wide - ``/etc/dwave/``. For details, see :func:`load_config_from_file`. + ``/etc/dwave/``. For details, see :func:`load_config_from_files`. Args: system (boolean, default=True): @@ -160,6 +160,70 @@ def load_config_from_files(filenames=None): return config +def load_profile_from_files(filenames=None, profile=None): + """Load config from a list of `filenames`, returning only section + defined with `profile`. + + Note: + Config files and profile name are **not** read from process environment. + + Args: + filenames (list[str], default=None): + D-Wave cloud client configuration file locations. Set to ``None`` to + auto-detect config files, as described in + :func:`load_config_from_files`. + + profile (str, default=None): + Name of the profile to return from configuration read from config + file(s). Set to ``None`` fallback to ``profile`` key under + ``[defaults]`` section, or the first non-defaults section, or the + actual ``[defaults]`` section. + + Returns: + dict: + Mapping of config keys to config values. If no valid config/profile + found, returns an empty dict. + + Raises: + :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: + Config file specified or detected could not be opened or read. + + :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: + Config file parse failed. + + :exc:`ValueError`: + Profile name not found. + """ + + # progressively build config from a file, or a list of auto-detected files + # raises ConfigFileReadError/ConfigFileParseError on error + config = load_config_from_files(filenames) + + # determine profile name fallback: + # (1) profile key under [defaults], + # (2) first non-[defaults] section + # (3) [defaults] section + first_section = next(iter(config.sections() + [None])) + config_defaults = config.defaults() + if not profile: + profile = config_defaults.get('profile', first_section) + + if profile: + try: + section = dict(config[profile]) + except KeyError: + raise ValueError("Config profile {!r} not found".format(profile)) + else: + # as the very last resort (unspecified profile name and + # no profiles defined in config), try to use [defaults] + if config_defaults: + section = config_defaults + else: + section = {} + + return section + + def get_default_config(): config = configparser.ConfigParser(default_section="defaults") config.read_string(u""" @@ -204,7 +268,7 @@ def load_config(config_file=None, profile=None, client=None, performed (looking first for ``dwave.conf`` in process' current working directory, then in user-local config directories, and finally in system-wide config dirs). For details on format and location detection, see - :func:`load_config_from_file`. + :func:`load_config_from_files`. If location of ``config_file`` is explicitly specified (via arguments or environment variable), but the file does not exits, or is not readable, @@ -327,51 +391,22 @@ def load_config(config_file=None, profile=None, client=None, Config file parse failed. """ - def _get_section(filenames, profile): - """Load config from a list of `filenames`, returning only section - defined with `profile`.""" - - # progressively build config from a file, or a list of auto-detected files - # raises ConfigFileReadError/ConfigFileParseError on error - config = load_config_from_files(filenames) - - # determine profile name fallback: - # (1) profile key under [defaults], - # (2) first non-[defaults] section - first_section = next(iter(config.sections() + [None])) - config_defaults = config.defaults() - default_profile = config_defaults.get('profile', first_section) - - # select profile from the config - if profile is None: - profile = os.getenv("DWAVE_PROFILE", default_profile) - if profile: - try: - section = dict(config[profile]) - except KeyError: - raise ValueError("Config profile {!r} not found".format(profile)) - else: - # as the very last resort (unspecified profile name and - # no profiles defined in config), try to use [defaults] - if config_defaults: - section = config_defaults - else: - section = {} - - return section + if profile is None: + profile = os.getenv("DWAVE_PROFILE") if config_file == False: # skip loading from file altogether section = {} elif config_file == True: # force auto-detection, disregarding DWAVE_CONFIG_FILE - section = _get_section(None, profile) + section = load_profile_from_files(None, profile) else: # auto-detect if not specified with arg or env if config_file is None: # note: both empty and undefined DWAVE_CONFIG_FILE treated as None config_file = os.getenv("DWAVE_CONFIG_FILE") - section = _get_section([config_file] if config_file else None, profile) + section = load_profile_from_files( + [config_file] if config_file else None, profile) # override a selected subset of values via env or kwargs, # pass-through the rest unmodified @@ -424,7 +459,7 @@ def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, profile-b|https://two.com,token-two Assuming the new config file ``dwave.conf`` is not found (in any of the - standard locations, see :meth:`~dwave.cloud.config.load_config_from_file` + standard locations, see :meth:`~dwave.cloud.config.load_config_from_files` and :meth:`~dwave.cloud.config.load_config`), then: >>> client = dwave.cloud.Client.from_config()
dwavesystems/dwave-cloud-client
31e170e1fc5df92bb7d57a45825379814c1aab84
diff --git a/tests/test_cli.py b/tests/test_cli.py index 266ee25..c3522ab 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -76,6 +76,49 @@ class TestCli(unittest.TestCase): ]) self.assertEqual(result.output.strip(), './dwave.conf') + def test_configure_inspect(self): + runner = CliRunner() + with runner.isolated_filesystem(): + config_file = 'dwave.conf' + with open(config_file, 'w') as f: + f.write(''' + [defaults] + endpoint = 1 + [a] + endpoint = 2 + [b] + token = 3''') + + # test auto-detected case + with mock.patch('dwave.cloud.config.get_configfile_paths', + lambda **kw: [config_file]): + result = runner.invoke(cli, [ + 'configure', '--inspect' + ]) + self.assertIn('endpoint = 2', result.output) + + # test explicit config + result = runner.invoke(cli, [ + 'configure', '--inspect', '--config-file', config_file + ]) + self.assertIn('endpoint = 2', result.output) + + # test explicit profile + result = runner.invoke(cli, [ + 'configure', '--inspect', '--config-file', config_file, + '--profile', 'b' + ]) + self.assertIn('endpoint = 1', result.output) + self.assertIn('token = 3', result.output) + + # test eagerness of config-file ane profile + result = runner.invoke(cli, [ + 'configure', '--config-file', config_file, + '--profile', 'b', '--inspect' + ]) + self.assertIn('endpoint = 1', result.output) + self.assertIn('token = 3', result.output) + def test_ping(self): config_file = 'dwave.conf'
Add config debug/show feature to dwave CLI
0.0
31e170e1fc5df92bb7d57a45825379814c1aab84
[ "tests/test_cli.py::TestCli::test_configure_inspect" ]
[ "tests/test_cli.py::TestCli::test_configure", "tests/test_cli.py::TestCli::test_configure_list_config", "tests/test_cli.py::TestCli::test_ping" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-04-18 20:30:37+00:00
apache-2.0
2,032
dwavesystems__dwave-cloud-client-168
diff --git a/dwave/cloud/__init__.py b/dwave/cloud/__init__.py index f46c8ba..15e0bed 100644 --- a/dwave/cloud/__init__.py +++ b/dwave/cloud/__init__.py @@ -17,3 +17,14 @@ handler.setFormatter(formatter) root = logging.getLogger(__name__) root.setLevel(logging.WARNING) root.addHandler(handler) + + +# add TRACE log level and Logger.trace() method +TRACE_LOGLEVEL = 5 + +logging.addLevelName(TRACE_LOGLEVEL, "TRACE") +def _trace(logger, message, *args, **kws): + if logger.isEnabledFor(TRACE_LOGLEVEL): + logger._log(TRACE_LOGLEVEL, message, args, **kws) + +logging.Logger.trace = _trace diff --git a/dwave/cloud/client.py b/dwave/cloud/client.py index 89b5146..bf283fe 100644 --- a/dwave/cloud/client.py +++ b/dwave/cloud/client.py @@ -751,6 +751,7 @@ class Client(object): try: status = message['status'] _LOGGER.debug("Handling response for %s with status %s", message['id'], status) + _LOGGER.trace("Handling response: %r", message) # The future may not have the ID set yet with future._single_cancel_lock: diff --git a/dwave/cloud/coders.py b/dwave/cloud/coders.py index 8b91335..43fc314 100644 --- a/dwave/cloud/coders.py +++ b/dwave/cloud/coders.py @@ -3,7 +3,8 @@ from __future__ import division, absolute_import import struct import base64 -from dwave.cloud.utils import uniform_iterator, uniform_get +from dwave.cloud.utils import ( + uniform_iterator, uniform_get, strip_tail, active_qubits) __all__ = ['encode_bqm_as_qp', 'decode_qp', 'decode_qp_numpy'] @@ -25,20 +26,25 @@ def encode_bqm_as_qp(solver, linear, quadratic): Returns: encoded submission dictionary """ + active = active_qubits(linear, quadratic) # Encode linear terms. The coefficients of the linear terms of the objective # are encoded as an array of little endian 64 bit doubles. # This array is then base64 encoded into a string safe for json. # The order of the terms is determined by the _encoding_qubits property # specified by the server. - lin = [uniform_get(linear, qubit, 0) for qubit in solver._encoding_qubits] + # Note: only active qubits are coded with double, inactive with NaN + nan = float('nan') + lin = [uniform_get(linear, qubit, 0 if qubit in active else nan) + for qubit in solver._encoding_qubits] lin = base64.b64encode(struct.pack('<' + ('d' * len(lin)), *lin)) # Encode the coefficients of the quadratic terms of the objective # in the same manner as the linear terms, in the order given by the - # _encoding_couplers property - quad = [quadratic.get(edge, 0) + quadratic.get((edge[1], edge[0]), 0) - for edge in solver._encoding_couplers] + # _encoding_couplers property, discarding tailing zero couplings + quad = [quadratic.get((q1,q2), 0) + quadratic.get((q2,q1), 0) + for (q1,q2) in solver._encoding_couplers + if q1 in active and q2 in active] quad = base64.b64encode(struct.pack('<' + ('d' * len(quad)), *quad)) # The name for this encoding is 'qp' and is explicitly included in the @@ -192,8 +198,9 @@ def decode_qp_numpy(msg, return_matrix=True): dtype=byte_type)) # Clip off the extra bits from encoding - bits = np.reshape(bits, (num_solutions, bits.size // num_solutions)) - bits = np.delete(bits, range(num_variables, bits.shape[1]), 1) + if num_solutions: + bits = np.reshape(bits, (num_solutions, bits.size // num_solutions)) + bits = np.delete(bits, range(num_variables, bits.shape[1]), 1) # Switch from bits to spins default = 3 diff --git a/dwave/cloud/solver.py b/dwave/cloud/solver.py index 2a2cf4a..094ac8a 100644 --- a/dwave/cloud/solver.py +++ b/dwave/cloud/solver.py @@ -241,6 +241,7 @@ class Solver(object): 'type': type_, 'params': params }) + _LOGGER.trace("Encoded sample request: %s", body) future = Future(solver=self, id_=None, return_matrix=self.return_matrix, submission_data=(type_, linear, quadratic, params)) @@ -278,8 +279,6 @@ class Solver(object): ... False True - - """ for key, value in uniform_iterator(linear): if value != 0 and key not in self.nodes: diff --git a/dwave/cloud/utils.py b/dwave/cloud/utils.py index 0294da8..6d67e0b 100644 --- a/dwave/cloud/utils.py +++ b/dwave/cloud/utils.py @@ -3,6 +3,7 @@ from __future__ import division, absolute_import from datetime import datetime from dateutil.tz import UTC from functools import wraps +import itertools import six import readline @@ -29,6 +30,7 @@ def evaluate_ising(linear, quad, state): Returns: Energy of the state evaluated by the given energy function. """ + # If we were given a numpy array cast to list if _numpy and isinstance(state, np.ndarray): return evaluate_ising(linear, quad, state.tolist()) @@ -42,6 +44,16 @@ def evaluate_ising(linear, quad, state): return energy +def active_qubits(linear, quadratic): + """Calculate a set of all active qubits. Qubit is "active" if it has + bias or coupling attached.""" + + active = set(linear) + for edge, _ in six.iteritems(quadratic): + active.update(edge) + return active + + def uniform_iterator(sequence): """Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.""" @@ -62,6 +74,17 @@ def uniform_get(sequence, index, default=None): return sequence[index] if index < len(sequence) else default +def strip_head(sequence, values): + """Strips elements of `values` from the beginning of `sequence`.""" + values = set(values) + return list(itertools.dropwhile(lambda x: x in values, sequence)) + + +def strip_tail(sequence, values): + """Strip `values` from the end of `sequence`.""" + return list(reversed(list(strip_head(reversed(sequence), values)))) + + def readline_input(prompt, prefill=''): """Provide an editable default for ``input()``.""" # see: https://stackoverflow.com/q/2533120/
dwavesystems/dwave-cloud-client
e2399af70d7261da34b1e43b1321597bcaac3422
diff --git a/tests/test_coders.py b/tests/test_coders.py index 5c90433..382796b 100644 --- a/tests/test_coders.py +++ b/tests/test_coders.py @@ -24,7 +24,9 @@ def get_solver(): class TestCoders(unittest.TestCase): - def test_qpu_request_encoding(self): + def test_qpu_request_encoding_all_qubits(self): + """Test biases and coupling strengths are properly encoded (base64 little-endian doubles).""" + solver = get_solver() linear = {index: 1 for index in solver.nodes} quadratic = {key: -1 for key in solver.undirected_edges} @@ -32,3 +34,55 @@ class TestCoders(unittest.TestCase): self.assertEqual(request['format'], 'qp') self.assertEqual(request['lin'], 'AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAA8D8=') self.assertEqual(request['quad'], 'AAAAAAAA8L8AAAAAAADwvwAAAAAAAPC/AAAAAAAA8L8=') + + def test_qpu_request_encoding_sub_qubits(self): + """Inactive qubits should be encoded as NaNs. Inactive couplers should be omitted.""" + + solver = get_solver() + linear = {index: 1 for index in sorted(list(solver.nodes))[:2]} + quadratic = {key: -1 for key in sorted(list(solver.undirected_edges))[:1]} + request = encode_bqm_as_qp(solver, linear, quadratic) + self.assertEqual(request['format'], 'qp') + # [1, 1, NaN, NaN] + self.assertEqual(request['lin'], 'AAAAAAAA8D8AAAAAAADwPwAAAAAAAPh/AAAAAAAA+H8=') + # [-1] + self.assertEqual(request['quad'], 'AAAAAAAA8L8=') + + def test_qpu_request_encoding_missing_qubits(self): + """Qubits don't have to be specified with biases only, but also with couplings.""" + + solver = get_solver() + linear = {} + quadratic = {(0, 1): -1} + request = encode_bqm_as_qp(solver, linear, quadratic) + self.assertEqual(request['format'], 'qp') + # [0, 0, NaN, NaN] + self.assertEqual(request['lin'], 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAPh/AAAAAAAA+H8=') + # [-1] + self.assertEqual(request['quad'], 'AAAAAAAA8L8=') + + def test_qpu_request_encoding_sub_qubits_implicit_biases(self): + """Biases don't have to be specified for qubits to be active.""" + + solver = get_solver() + linear = {} + quadratic = {(0,3): -1} + request = encode_bqm_as_qp(solver, linear, quadratic) + self.assertEqual(request['format'], 'qp') + # [0, NaN, NaN, 0] + self.assertEqual(request['lin'], 'AAAAAAAAAAAAAAAAAAD4fwAAAAAAAPh/AAAAAAAAAAA=') + # [-1] + self.assertEqual(request['quad'], 'AAAAAAAA8L8=') + + def test_qpu_request_encoding_sub_qubits_implicit_couplings(self): + """Couplings should be zero for active qubits, if not specified.""" + + solver = get_solver() + linear = {0: 0, 3: 0} + quadratic = {} + request = encode_bqm_as_qp(solver, linear, quadratic) + self.assertEqual(request['format'], 'qp') + # [0, NaN, NaN, 0] + self.assertEqual(request['lin'], 'AAAAAAAAAAAAAAAAAAD4fwAAAAAAAPh/AAAAAAAAAAA=') + # [-1] + self.assertEqual(request['quad'], 'AAAAAAAAAAA=') diff --git a/tests/test_utils.py b/tests/test_utils.py index a3fcd6f..8a6f4db 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,7 +1,8 @@ import unittest from collections import OrderedDict -from dwave.cloud.utils import readline_input, uniform_iterator, uniform_get +from dwave.cloud.utils import ( + readline_input, uniform_iterator, uniform_get, strip_head, strip_tail) from dwave.cloud.testing import mock @@ -22,6 +23,18 @@ class TestUtils(unittest.TestCase): self.assertEqual(uniform_get(l, 2), None) self.assertEqual(uniform_get(l, 2, default=0), 0) + def test_strip_head(self): + self.assertEqual(strip_head([0, 0, 1, 2], [0]), [1, 2]) + self.assertEqual(strip_head([1], [0]), [1]) + self.assertEqual(strip_head([1], []), [1]) + self.assertEqual(strip_head([0, 0, 1, 2], [0, 1, 2]), []) + + def test_strip_tail(self): + self.assertEqual(strip_tail([1, 2, 0, 0], [0]), [1, 2]) + self.assertEqual(strip_tail([1], [0]), [1]) + self.assertEqual(strip_tail([1], []), [1]) + self.assertEqual(strip_tail([0, 0, 1, 2], [0, 1, 2]), []) + def test_readline_input(self): val = "value" with mock.patch("six.moves.input", side_effect=[val], create=True):
computation.occurrences() output not as expected I set QPU parameter answer_mode=histogram and submit a problem with several ground states, I expected to see the result returned in a histogram with ~4 occurrences buckets, similar to what results through SAPI: ![image](https://user-images.githubusercontent.com/34041130/39498504-5df90e42-4d5d-11e8-85fb-bad595f0ae64.png) The resultant samples have repetitions (e.g. 3rd and 4th) but occurrences are always 1: ``` In [690]: with Client.from_config() as client: ...: solver = client.get_solver() ...: solver.parameters['answer_mode']='histogram' ...: quad = {(16, 20): -1, (17, 20): 1, (16, 21): 1, (17, 21): 1} ...: computation = solver.sample_ising({}, quad, num_reads=20) ...: for i in range(len(computation.occurrences)): ...: print(computation.samples[i][16],computation.samples[i][17], computation.samples[i][20], computation.sa ...: mples[i][21], ' --> ', computation.energies[i], computation.occurrences[i]) ...: (-1, 1, -1, 1, ' --> ', -2.0, 1) (-1, -1, -1, 1, ' --> ', -2.0, 1) (1, -1, 1, -1, ' --> ', -2.0, 1) (1, -1, 1, -1, ' --> ', -2.0, 1) (1, -1, 1, -1, ' --> ', -2.0, 1) (1, -1, 1, 1, ' --> ', -2.0, 1) (-1, 1, -1, -1, ' --> ', -2.0, 1) (1, -1, 1, 1, ' --> ', -2.0, 1) (1, -1, 1, 1, ' --> ', -2.0, 1) (-1, -1, 1, 1, ' --> ', -2.0, 1) (1, -1, 1, -1, ' --> ', -2.0, 1) (-1, 1, -1, -1, ' --> ', -2.0, 1) (1, 1, -1, -1, ' --> ', -2.0, 1) (-1, -1, -1, 1, ' --> ', -2.0, 1) (-1, 1, -1, 1, ' --> ', -2.0, 1) (-1, -1, 1, 1, ' --> ', -2.0, 1) (1, 1, -1, -1, ' --> ', -2.0, 1) (1, 1, 1, -1, ' --> ', -2.0, 1) (1, 1, 1, -1, ' --> ', -2.0, 1) (1, -1, 1, 1, ' --> ', -2.0, 1) ```
0.0
e2399af70d7261da34b1e43b1321597bcaac3422
[ "tests/test_coders.py::TestCoders::test_qpu_request_encoding_all_qubits", "tests/test_coders.py::TestCoders::test_qpu_request_encoding_missing_qubits", "tests/test_coders.py::TestCoders::test_qpu_request_encoding_sub_qubits", "tests/test_coders.py::TestCoders::test_qpu_request_encoding_sub_qubits_implicit_biases", "tests/test_coders.py::TestCoders::test_qpu_request_encoding_sub_qubits_implicit_couplings", "tests/test_utils.py::TestUtils::test_readline_input", "tests/test_utils.py::TestUtils::test_strip_head", "tests/test_utils.py::TestUtils::test_strip_tail", "tests/test_utils.py::TestUtils::test_uniform_get", "tests/test_utils.py::TestUtils::test_uniform_iterator" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-10 19:17:13+00:00
apache-2.0
2,033
dwavesystems__dwave-cloud-client-252
diff --git a/dwave/cloud/client.py b/dwave/cloud/client.py index 2661473..3e5941e 100644 --- a/dwave/cloud/client.py +++ b/dwave/cloud/client.py @@ -881,9 +881,20 @@ class Client(object): This method is always run inside of a daemon thread. """ try: - status = message['status'] - _LOGGER.debug("Handling response for %s with status %s", message['id'], status) _LOGGER.trace("Handling response: %r", message) + _LOGGER.debug("Handling response for %s with status %s", message.get('id'), message.get('status')) + + # Handle errors in batch mode + if 'error_code' in message and 'error_msg' in message: + raise SolverFailureError(message['error_msg']) + + if 'status' not in message: + raise InvalidAPIResponseError("'status' missing in problem description response") + if 'id' not in message: + raise InvalidAPIResponseError("'id' missing in problem description response") + + future.id = message['id'] + future.remote_status = status = message['status'] # The future may not have the ID set yet with future._single_cancel_lock: @@ -897,10 +908,6 @@ class Client(object): # If a cancel request could meaningfully be sent it has been now future._cancel_sent = True - # Set the id field in the future - future.id = message['id'] - future.remote_status = status - if not future.time_received and message.get('submitted_on'): future.time_received = parse_datetime(message['submitted_on']) @@ -931,15 +938,14 @@ class Client(object): self._poll(future) elif status == self.STATUS_CANCELLED: # If canceled return error - future._set_error(CanceledFutureError()) + raise CanceledFutureError() else: # Return an error to the future object errmsg = message.get('error_message', 'An unknown error has occurred.') if 'solver is offline' in errmsg.lower(): - err = SolverOfflineError(errmsg) + raise SolverOfflineError(errmsg) else: - err = SolverFailureError(errmsg) - future._set_error(err) + raise SolverFailureError(errmsg) except Exception as error: # If there were any unhandled errors we need to release the
dwavesystems/dwave-cloud-client
1ac533f411dda0ccdc6ffece158472994219e5e9
diff --git a/tests/test_mock_submission.py b/tests/test_mock_submission.py index 2c72d09..7eb3f97 100644 --- a/tests/test_mock_submission.py +++ b/tests/test_mock_submission.py @@ -12,7 +12,7 @@ from dateutil.tz import UTC from dateutil.parser import parse as parse_datetime from requests.structures import CaseInsensitiveDict -from dwave.cloud.utils import evaluate_ising +from dwave.cloud.utils import evaluate_ising, generate_random_ising_problem from dwave.cloud.qpu import Client, Solver from dwave.cloud.exceptions import SolverFailureError, CanceledFutureError from dwave.cloud.testing import mock @@ -84,6 +84,14 @@ def error_reply(id_, solver_name, error): }) +def immediate_error_reply(code, msg): + """A reply saying an error has occurred (before scheduling for execution).""" + return json.dumps({ + "error_code": code, + "error_msg": msg + }) + + def cancel_reply(id_, solver_name): """A reply saying a problem was canceled.""" return json.dumps({ @@ -204,6 +212,20 @@ class MockSubmission(_QueryTest): with self.assertRaises(SolverFailureError): results.samples + def test_submit_immediate_error_reply(self): + """Handle an (obvious) error on problem submission.""" + with Client('endpoint', 'token') as client: + client.session = mock.Mock() + client.session.post = lambda a, _: choose_reply(a, { + 'endpoint/problems/': '[%s]' % immediate_error_reply(400, "Missing parameter 'num_reads' in problem JSON")}) + solver = Solver(client, solver_data('abc123')) + + linear, quad = generate_random_ising_problem(solver) + results = solver.sample_ising(linear, quad) + + with self.assertRaises(SolverFailureError): + results.samples + def test_submit_cancel_reply(self): """Handle a response for a canceled job.""" with Client('endpoint', 'token') as client: diff --git a/tests/test_solver.py b/tests/test_solver.py index 957d3b5..15e1a73 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -40,7 +40,7 @@ class PropertyLoading(unittest.TestCase): """Ensure that the parameters are populated.""" with Client(**config) as client: solver = client.get_solver() - assert 'not_a_parameter' not in solver.parameters + self.assertNotIn('not_a_parameter', solver.parameters) with self.assertRaises(KeyError): solver.sample_ising({}, {}, not_a_parameter=True) @@ -48,7 +48,7 @@ class PropertyLoading(unittest.TestCase): """Ensure that the experimental parameters are populated.""" with Client(**config) as client: solver = client.get_solver() - assert 'x_test' not in solver.parameters + self.assertNotIn('x_test', solver.parameters) with self.assertRaises(SolverFailureError): self.assertTrue(solver.sample_ising([0], {}, x_test=123).result())
Handle errors in batch mode On problem submit and cancel, we are reading responses from a list of JSON objects. In case any of these problems failed, the structure will be specific (as documented in the [REST API docs](https://cloud.dwavesys.com/qubist/docs/dev_guide_sapi/sapi_resources/)): ``` { "error_code": 400, "error_msg": "Missing parameter 'num_reads' in problem JSON" } ``` Current problem response handler does not handle this case -- it always assumes this structure (in case problem failed): ``` { "status": "FAILED", "id": "f004cea4-0f18-4b44-8aca-4e3acbb6831b", "error_message": "Some error message" ... } ```
0.0
1ac533f411dda0ccdc6ffece158472994219e5e9
[ "tests/test_mock_submission.py::MockSubmission::test_submit_immediate_error_reply" ]
[ "tests/test_mock_submission.py::MockSubmission::test_eta_min_is_respected_on_first_poll", "tests/test_mock_submission.py::MockSubmission::test_exponential_backoff_polling", "tests/test_mock_submission.py::MockSubmission::test_immediate_polling_with_local_clock_unsynced", "tests/test_mock_submission.py::MockSubmission::test_immediate_polling_without_eta_min", "tests/test_mock_submission.py::MockSubmission::test_submit_cancel_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_continue_then_error_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_continue_then_ok_and_error_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_continue_then_ok_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_error_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_null_reply", "tests/test_mock_submission.py::MockSubmission::test_submit_ok_reply", "tests/test_mock_submission.py::MockCancel::test_cancel_with_id", "tests/test_mock_submission.py::MockCancel::test_cancel_without_id" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-09-20 23:09:17+00:00
apache-2.0
2,034