prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django import forms
from ncdjango.interfaces.arcgis.form_fields import SrField
class PointForm(forms.Form):
x = forms.FloatField()<|fim▁hole|> projection = SrField()<|fim▁end|> | y = forms.FloatField() |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django import forms
from ncdjango.interfaces.arcgis.form_fields import SrField
class PointForm(forms.Form):
<|fim_middle|>
<|fim▁end|> | x = forms.FloatField()
y = forms.FloatField()
projection = SrField() |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-<|fim▁hole|>from __future__ import unicode_literals
from __future__ import print_function<|fim▁end|> | # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" This package contains the qibuild actions. """
from __future__ import absolute_import |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
<|fim▁hole|> os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()<|fim▁end|> | import pytest
needs_posix = pytest.mark.skipif( |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
<|fim_middle|>
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
A particular errno.
"""
return errno.EINVAL |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
<|fim_middle|>
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value) |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
<|fim_middle|>
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
<|fim_middle|>
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
<|fim_middle|>
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1 |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
<|fim_middle|>
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
<|fim_middle|>
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
<|fim_middle|>
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0 |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
<|fim_middle|>
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1) |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
<|fim_middle|>
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1 |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
<|fim_middle|>
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)" |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
<|fim_middle|>
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1) |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
<|fim_middle|>
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
<|fim_middle|>
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic") |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
<|fim_middle|>
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
<|fim_middle|>
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
<|fim_middle|>
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0) |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
<|fim_middle|>
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic") |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
<|fim_middle|>
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0) |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
<|fim_middle|>
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
<|fim_middle|>
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | """
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
<|fim_middle|>
<|fim▁end|> | """
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic() |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
<|fim_middle|>
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | expected_resolution = 1e-09 |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
<|fim_middle|>
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | expected_resolution = 1.0 |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def <|fim_middle|>():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | errno_value |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def <|fim_middle|>(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | strerror |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def <|fim_middle|>(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | apply_failing_clock_call |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def <|fim_middle|>(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | _apply_failing_clock_call |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def <|fim_middle|>(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | _failing_clock_call |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def <|fim_middle|>(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | apply_timespec |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def <|fim_middle|>(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | _apply_timespec |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def <|fim_middle|>(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | _fake_clock_call |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def <|fim_middle|>(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_init |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def <|fim_middle|>(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_repr |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def <|fim_middle|>(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_eq |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def <|fim_middle|>(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_non_monotonic |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def <|fim_middle|>(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_failure |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def <|fim_middle|>(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_info |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def <|fim_middle|>(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_non_monotonic |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def <|fim_middle|>(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_info |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def <|fim_middle|>(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_monotonic_fails_posix |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def <|fim_middle|>(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_clock |
<|file_name|>test_monotone.py<|end_file_name|><|fim▁begin|>"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def <|fim_middle|>():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
<|fim▁end|> | test_clock_increases |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:<|fim▁hole|> res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False<|fim▁end|> | fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
|
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
<|fim_middle|>
<|fim▁end|> | _inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
<|fim_middle|>
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
<|fim_middle|>
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
<|fim_middle|>
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg) |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
<|fim_middle|>
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
<|fim_middle|>
<|fim▁end|> | self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
<|fim_middle|>
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | self.send_to_shipper() |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
<|fim_middle|>
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | return None |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
<|fim_middle|>
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | return None |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
<|fim_middle|>
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice) |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
<|fim_middle|>
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | account_id = carrier.product_id.categ_id.property_account_income_categ.id |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
<|fim_middle|>
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def <|fim_middle|>(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | do_transfer |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def <|fim_middle|>(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | _prepare_shipping_invoice_line |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def <|fim_middle|>(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | send_to_shipper |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def <|fim_middle|>(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | open_website_url |
<|file_name|>stock_picking.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def <|fim_middle|>(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
<|fim▁end|> | cancel_shipment |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^pis', views.pis),
url(r'^words', views.words, { 'titles': False }),
url(r'^projects', views.projects),
url(r'^posters', views.posters),
url(r'^posterpresenters', views.posterpresenters),
url(r'^pigraph', views.pigraph),
url(r'^institutions', views.institutions),
url(r'^institution/(?P<institutionid>\d+)', views.institution),
url(r'^profile/$', views.profile),
url(r'^schedule/(?P<email>\S+)', views.schedule),
url(r'^ratemeeting/(?P<rmid>\d+)/(?P<email>\S+)', views.ratemeeting),
url(r'^submitrating/(?P<rmid>\d+)/(?P<email>\S+)', views.submitrating),
url(r'^feedback/(?P<email>\S+)', views.after),
url(r'^breakouts', views.breakouts),
url(r'^breakout/(?P<bid>\d+)', views.breakout),
url(r'^about', views.about),
url(r'^buginfo', views.buginfo),
url(r'^allrms', views.allrms),
url(r'^allratings', views.allratings),
url(r'^login', views.login),
url(r'^logout', views.logout),
url(r'^edit_home_page', views.edit_home_page),
url(r'^pi/(?P<userid>\d+)', views.pi), # , name = 'pi'),
url(r'^pi/(?P<email>\S+)', views.piEmail), # , name = 'pi'),
url(r'^project/(?P<abstractid>\S+)', views.project, name = 'project'),
url(r'^scope=(?P<scope>\w+)/(?P<url>.+)$', views.set_scope),
url(r'^active=(?P<active>\d)/(?P<url>.+)$', views.set_active),
url(r'^admin/', include(admin.site.urls)),
(r'', include('django_browserid.urls')),
url(r'^$', views.index, name = 'index'),<|fim▁hole|> ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)<|fim▁end|> | |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
<|fim▁hole|> return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))<|fim▁end|> | if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner): |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
<|fim_middle|>
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const("")) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
<|fim_middle|>
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups") |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
<|fim_middle|>
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
<|fim_middle|>
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
} |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
<|fim_middle|>
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
} |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
<|fim_middle|>
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
<|fim_middle|>
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return serializers.Resource(MaxCount=1, MinCount=1) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
<|fim_middle|>
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
<|fim_middle|>
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
<|fim_middle|>
<|fim▁end|> | resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts)) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
<|fim_middle|>
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
<|fim_middle|>
<|fim▁end|> | obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts)) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
<|fim_middle|>
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"]) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
<|fim_middle|>
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"]) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
<|fim_middle|>
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return serializers.Const(obj["PrivateIpAddress"]) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
<|fim_middle|>
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return serializers.Const(obj["PublicDnsName"]) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
<|fim_middle|>
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | return serializers.Const(obj["PublicIpAddress"]) |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def <|fim_middle|>(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | get_describe_filters |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def <|fim_middle|>(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | get_create_serializer |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def <|fim_middle|>(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | get_destroy_serializer |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def <|fim_middle|>(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | get_network_id |
<|file_name|>instance.py<|end_file_name|><|fim▁begin|># Copyright 2014-2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def <|fim_middle|>(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
<|fim▁end|> | get_serializer |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding:utf-8 -*-
from setuptools import setup
setup(
name='libipa',
version='0.0.6',
author='Andrew Udvare',
author_email='[email protected]',
packages=['ipa'],
scripts=['bin/ipa-unzip-bin', 'bin/ipa-dump-info'],<|fim▁hole|> test_suite='ipa.test',
long_description='No description.',
install_requires=[
'biplist>=0.7',
'six>=1.7.3',
],
)<|fim▁end|> | url='https://github.com/Tatsh/libipa',
license='LICENSE.txt',
description='Library to read IPA files (iOS application archives).', |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:<|fim▁hole|> styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)<|fim▁end|> | |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
<|fim_middle|>
<|fim▁end|> | if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
<|fim_middle|>
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
<|fim▁end|> | raise Http404() |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
<|fim_middle|>
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
<|fim▁end|> | styleguide = cache.get(STYLEGUIDE_CACHE_NAME) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
<|fim_middle|>
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
<|fim▁end|> | styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
<|fim_middle|>
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
<|fim▁end|> | styleguide.set_current_module(module_name) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def <|fim_middle|>(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
<|fim▁end|> | index |
<|file_name|>dummy_operator.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at<|fim▁hole|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class DummyOperator(BaseOperator):
"""
Operator that does literally nothing. It can be used to group tasks in a
DAG.
"""
ui_color = '#e8f7e4'
@apply_defaults
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def execute(self, context):
pass<|fim▁end|> | # |
<|file_name|>dummy_operator.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class DummyOperator(BaseOperator):
<|fim_middle|>
<|fim▁end|> | """
Operator that does literally nothing. It can be used to group tasks in a
DAG.
"""
ui_color = '#e8f7e4'
@apply_defaults
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def execute(self, context):
pass |
<|file_name|>dummy_operator.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class DummyOperator(BaseOperator):
"""
Operator that does literally nothing. It can be used to group tasks in a
DAG.
"""
ui_color = '#e8f7e4'
@apply_defaults
def __init__(self, *args, **kwargs) -> None:
<|fim_middle|>
def execute(self, context):
pass
<|fim▁end|> | super().__init__(*args, **kwargs) |