after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def shrink_offset_pairs(self):
"""Lower any two blocks offset from each other the same ammount.
Before this shrink pass, two blocks explicitly offset from each
other would not get minimized properly:
>>> b = st.integers(0, 255)
>>> find(st.tuples(b, b), lambda x: x[0] == x[1] + 1)
(149,148)
This expensive (O(n^2)) pass goes through every pair of non-zero
blocks in the current shrink target and sees if the shrink
target can be improved by applying an offset to both of them.
"""
self.debug("Shrinking offset pairs.")
current = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
def int_from_block(i):
return int_from_bytes(current[i])
def block_len(i):
u, v = self.blocks[i]
return v - u
# Try reoffseting every pair
def reoffset_pair(pair, o):
n = len(self.blocks)
# Number of blocks may have changed, need to validate
valid_pair = [
p
for p in pair
if p < n and int_from_block(p) > 0 and self.is_payload_block(p)
]
if len(valid_pair) < 2:
return
m = min([int_from_block(p) for p in valid_pair])
new_blocks = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
for i in valid_pair:
new_blocks[i] = int_to_bytes(int_from_block(i) + o - m, block_len(i))
buffer = hbytes().join(new_blocks)
return self.incorporate_new_buffer(buffer)
i = 0
while i < len(self.blocks):
if self.is_payload_block(i) and int_from_block(i) > 0:
j = i + 1
while j < len(self.shrink_target.blocks):
block_val = int_from_block(j)
i_block_val = int_from_block(i)
if self.is_payload_block(j) and block_val > 0 and i_block_val > 0:
offset = min(int_from_block(i), int_from_block(j))
# Save current before shrinking
current = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
minimize_int(offset, lambda o: reoffset_pair((i, j), o))
j += 1
i += 1
|
def shrink_offset_pairs(self):
"""Lower any two blocks offset from each other the same ammount.
Before this shrink pass, two blocks explicitly offset from each
other would not get minimized properly:
>>> b = st.integers(0, 255)
>>> find(st.tuples(b, b), lambda x: x[0] == x[1] + 1)
(149,148)
This expensive (O(n^2)) pass goes through every pair of non-zero
blocks in the current shrink target and sees if the shrink
target can be improved by applying an offset to both of them.
"""
self.debug("Shrinking offset pairs.")
current = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
def int_from_block(i):
return int_from_bytes(current[i])
def block_len(i):
u, v = self.blocks[i]
return v - u
# Try reoffseting every pair
def reoffset_pair(pair, o):
n = len(self.blocks)
# Number of blocks may have changed, need to validate
valid_pair = [p for p in pair if p < n and int_from_block(p) > 0]
if len(valid_pair) < 2:
return
m = min([int_from_block(p) for p in valid_pair])
new_blocks = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
for i in valid_pair:
new_blocks[i] = int_to_bytes(int_from_block(i) + o - m, block_len(i))
buffer = hbytes().join(new_blocks)
return self.incorporate_new_buffer(buffer)
i = 0
while i < len(self.blocks):
if not self.is_shrinking_block(i) and int_from_block(i) > 0:
j = i + 1
while j < len(self.shrink_target.blocks):
block_val = int_from_block(j)
i_block_val = int_from_block(i)
if not self.is_shrinking_block(j) and block_val > 0 and i_block_val > 0:
offset = min(int_from_block(i), int_from_block(j))
# Save current before shrinking
current = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
minimize_int(offset, lambda o: reoffset_pair((i, j), o))
j += 1
i += 1
|
https://github.com/HypothesisWorks/hypothesis/issues/1299
|
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1325, in greedy_shrink
self.shrink_offset_pairs()
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1581, in shrink_offset_pairs
block_val = int_from_block(j)
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1551, in int_from_block
return int_from_bytes(current[i])
IndexError: list index out of range
|
IndexError
|
def reoffset_pair(pair, o):
n = len(self.blocks)
# Number of blocks may have changed, need to validate
valid_pair = [
p for p in pair if p < n and int_from_block(p) > 0 and self.is_payload_block(p)
]
if len(valid_pair) < 2:
return
m = min([int_from_block(p) for p in valid_pair])
new_blocks = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
for i in valid_pair:
new_blocks[i] = int_to_bytes(int_from_block(i) + o - m, block_len(i))
buffer = hbytes().join(new_blocks)
return self.incorporate_new_buffer(buffer)
|
def reoffset_pair(pair, o):
n = len(self.blocks)
# Number of blocks may have changed, need to validate
valid_pair = [p for p in pair if p < n and int_from_block(p) > 0]
if len(valid_pair) < 2:
return
m = min([int_from_block(p) for p in valid_pair])
new_blocks = [self.shrink_target.buffer[u:v] for u, v in self.blocks]
for i in valid_pair:
new_blocks[i] = int_to_bytes(int_from_block(i) + o - m, block_len(i))
buffer = hbytes().join(new_blocks)
return self.incorporate_new_buffer(buffer)
|
https://github.com/HypothesisWorks/hypothesis/issues/1299
|
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1325, in greedy_shrink
self.shrink_offset_pairs()
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1581, in shrink_offset_pairs
block_val = int_from_block(j)
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1551, in int_from_block
return int_from_bytes(current[i])
IndexError: list index out of range
|
IndexError
|
def escape_local_minimum(self):
"""Attempt to restart the shrink process from a larger initial value in
a way that allows us to escape a local minimum that the main greedy
shrink process will get stuck in.
The idea is that when we've completed the shrink process, we try
starting it again from something reasonably near to the shrunk example
that is likely to exhibit the same behaviour.
We search for an example that is selected randomly among ones that are
"structurally similar" to the original. If we don't find one we bail
out fairly quickly as this will usually not work. If we do, we restart
the shrink process from there. If this results in us finding a better
final example, we do this again until it stops working.
This is especially useful for things where the tendency to move
complexity to the right works against us - often a generic instance of
the problem is easy to shrink, but trying to reduce the size of a
minimized example further is hard. For example suppose we had something
like:
x = data.draw(lists(integers()))
y = data.draw(lists(integers(), min_size=len(x), max_size=len(x)))
assert not (any(x) and any(y))
Then this could shrink to something like [0, 1], [0, 1].
Attempting to shrink this further by deleting an element of x would
result in losing the last element of y, and the test would start
passing. But if we were to replace this with [a, b], [c, d] with c != 0
then deleting a or b would work.
"""
count = 0
while count < 10:
count += 1
self.debug("Retrying from random restart")
attempt_buf = bytearray(self.shrink_target.buffer)
# We use the shrinking information to identify the
# structural locations in the byte stream - if lowering
# the block would result in changing the size of the
# example, changing it here is too likely to break whatever
# it was caused the behaviour we're trying to shrink.
# Everything non-structural, we redraw uniformly at random.
for i, (u, v) in enumerate(self.blocks):
if self.is_payload_block(i):
attempt_buf[u:v] = uniform(self.__engine.random, v - u)
attempt = self.cached_test_function(attempt_buf)
if self.__predicate(attempt):
prev = self.shrink_target
self.update_shrink_target(attempt)
self.__shrinking_block_cache = {}
self.greedy_shrink()
if sort_key(self.shrink_target.buffer) < sort_key(prev.buffer):
# We have successfully shrunk the example past where
# we started from. Now we begin the whole process
# again from the new, smaller, example.
count = 0
else:
self.update_shrink_target(prev)
self.__shrinking_block_cache = {}
|
def escape_local_minimum(self):
"""Attempt to restart the shrink process from a larger initial value in
a way that allows us to escape a local minimum that the main greedy
shrink process will get stuck in.
The idea is that when we've completed the shrink process, we try
starting it again from something reasonably near to the shrunk example
that is likely to exhibit the same behaviour.
We search for an example that is selected randomly among ones that are
"structurally similar" to the original. If we don't find one we bail
out fairly quickly as this will usually not work. If we do, we restart
the shrink process from there. If this results in us finding a better
final example, we do this again until it stops working.
This is especially useful for things where the tendency to move
complexity to the right works against us - often a generic instance of
the problem is easy to shrink, but trying to reduce the size of a
minimized example further is hard. For example suppose we had something
like:
x = data.draw(lists(integers()))
y = data.draw(lists(integers(), min_size=len(x), max_size=len(x)))
assert not (any(x) and any(y))
Then this could shrink to something like [0, 1], [0, 1].
Attempting to shrink this further by deleting an element of x would
result in losing the last element of y, and the test would start
passing. But if we were to replace this with [a, b], [c, d] with c != 0
then deleting a or b would work.
"""
count = 0
while count < 10:
count += 1
self.debug("Retrying from random restart")
attempt_buf = bytearray(self.shrink_target.buffer)
# We use the shrinking information to identify the
# structural locations in the byte stream - if lowering
# the block would result in changing the size of the
# example, changing it here is too likely to break whatever
# it was caused the behaviour we're trying to shrink.
# Everything non-structural, we redraw uniformly at random.
for i, (u, v) in enumerate(self.blocks):
if not self.is_shrinking_block(i):
attempt_buf[u:v] = uniform(self.__engine.random, v - u)
attempt = self.cached_test_function(attempt_buf)
if self.__predicate(attempt):
prev = self.shrink_target
self.update_shrink_target(attempt)
self.__shrinking_block_cache = {}
self.greedy_shrink()
if sort_key(self.shrink_target.buffer) < sort_key(prev.buffer):
# We have successfully shrunk the example past where
# we started from. Now we begin the whole process
# again from the new, smaller, example.
count = 0
else:
self.update_shrink_target(prev)
self.__shrinking_block_cache = {}
|
https://github.com/HypothesisWorks/hypothesis/issues/1299
|
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1325, in greedy_shrink
self.shrink_offset_pairs()
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1581, in shrink_offset_pairs
block_val = int_from_block(j)
File "/home/david/hypothesis/hypothesis-python/src/hypothesis/internal/conjecture/engine.py", line 1551, in int_from_block
return int_from_bytes(current[i])
IndexError: list index out of range
|
IndexError
|
def from_typing_type(thing):
# We start with special-case support for Union and Tuple - the latter
# isn't actually a generic type. Support for Callable may be added to
# this section later.
# We then explicitly error on non-Generic types, which don't carry enough
# information to sensibly resolve to strategies at runtime.
# Finally, we run a variation of the subclass lookup in st.from_type
# among generic types in the lookup.
import typing
# Under 3.6 Union is handled directly in st.from_type, as the argument is
# not an instance of `type`. However, under Python 3.5 Union *is* a type
# and we have to handle it here, including failing if it has no parameters.
if hasattr(thing, "__union_params__"): # pragma: no cover
args = sorted(thing.__union_params__ or (), key=type_sorting_key)
if not args:
raise ResolutionFailed("Cannot resolve Union of no types.")
return st.one_of([st.from_type(t) for t in args])
if getattr(thing, "__origin__", None) == tuple or isinstance(
thing, getattr(typing, "TupleMeta", ())
):
elem_types = getattr(thing, "__tuple_params__", None) or ()
elem_types += getattr(thing, "__args__", None) or ()
if (
getattr(thing, "__tuple_use_ellipsis__", False)
or len(elem_types) == 2
and elem_types[-1] is Ellipsis
):
return st.lists(st.from_type(elem_types[0])).map(tuple)
elif len(elem_types) == 1 and elem_types[0] == ():
return st.tuples() # Empty tuple; see issue #1583
return st.tuples(*map(st.from_type, elem_types))
if isinstance(thing, typing.TypeVar):
if getattr(thing, "__bound__", None) is not None:
return st.from_type(thing.__bound__)
if getattr(thing, "__constraints__", None):
return st.shared(
st.sampled_from(thing.__constraints__), key="typevar-with-constraint"
).flatmap(st.from_type)
# Constraints may be None or () on various Python versions.
return st.text() # An arbitrary type for the typevar
# Now, confirm that we're dealing with a generic type as we expected
if not isinstance(thing, typing_root_type): # pragma: no cover
raise ResolutionFailed("Cannot resolve %s to a strategy" % (thing,))
# Parametrised generic types have their __origin__ attribute set to the
# un-parametrised version, which we need to use in the subclass checks.
# e.g.: typing.List[int].__origin__ == typing.List
mapping = {
k: v
for k, v in _global_type_lookup.items()
if isinstance(k, typing_root_type) and try_issubclass(k, thing)
}
if typing.Dict in mapping:
# The subtype relationships between generic and concrete View types
# are sometimes inconsistent under Python 3.5, so we pop them out to
# preserve our invariant that all examples of from_type(T) are
# instances of type T - and simplify the strategy for abstract types
# such as Container
for t in (typing.KeysView, typing.ValuesView, typing.ItemsView):
mapping.pop(t, None)
strategies = [
v if isinstance(v, st.SearchStrategy) else v(thing)
for k, v in mapping.items()
if sum(try_issubclass(k, T) for T in mapping) == 1
]
empty = ", ".join(repr(s) for s in strategies if s.is_empty)
if empty or not strategies: # pragma: no cover
raise ResolutionFailed(
"Could not resolve %s to a strategy; consider using "
"register_type_strategy" % (empty or thing,)
)
return st.one_of(strategies)
|
def from_typing_type(thing):
# We start with special-case support for Union and Tuple - the latter
# isn't actually a generic type. Support for Callable may be added to
# this section later.
# We then explicitly error on non-Generic types, which don't carry enough
# information to sensibly resolve to strategies at runtime.
# Finally, we run a variation of the subclass lookup in st.from_type
# among generic types in the lookup.
import typing
# Under 3.6 Union is handled directly in st.from_type, as the argument is
# not an instance of `type`. However, under Python 3.5 Union *is* a type
# and we have to handle it here, including failing if it has no parameters.
if hasattr(thing, "__union_params__"): # pragma: no cover
args = sorted(thing.__union_params__ or (), key=type_sorting_key)
if not args:
raise ResolutionFailed("Cannot resolve Union of no types.")
return st.one_of([st.from_type(t) for t in args])
if getattr(thing, "__origin__", None) == tuple or isinstance(
thing, getattr(typing, "TupleMeta", ())
):
elem_types = getattr(thing, "__tuple_params__", None) or ()
elem_types += getattr(thing, "__args__", None) or ()
if (
getattr(thing, "__tuple_use_ellipsis__", False)
or len(elem_types) == 2
and elem_types[-1] is Ellipsis
):
return st.lists(st.from_type(elem_types[0])).map(tuple)
return st.tuples(*map(st.from_type, elem_types))
if isinstance(thing, typing.TypeVar):
if getattr(thing, "__bound__", None) is not None:
return st.from_type(thing.__bound__)
if getattr(thing, "__constraints__", None):
return st.shared(
st.sampled_from(thing.__constraints__), key="typevar-with-constraint"
).flatmap(st.from_type)
# Constraints may be None or () on various Python versions.
return st.text() # An arbitrary type for the typevar
# Now, confirm that we're dealing with a generic type as we expected
if not isinstance(thing, typing_root_type): # pragma: no cover
raise ResolutionFailed("Cannot resolve %s to a strategy" % (thing,))
# Parametrised generic types have their __origin__ attribute set to the
# un-parametrised version, which we need to use in the subclass checks.
# e.g.: typing.List[int].__origin__ == typing.List
mapping = {
k: v
for k, v in _global_type_lookup.items()
if isinstance(k, typing_root_type) and try_issubclass(k, thing)
}
if typing.Dict in mapping:
# The subtype relationships between generic and concrete View types
# are sometimes inconsistent under Python 3.5, so we pop them out to
# preserve our invariant that all examples of from_type(T) are
# instances of type T - and simplify the strategy for abstract types
# such as Container
for t in (typing.KeysView, typing.ValuesView, typing.ItemsView):
mapping.pop(t, None)
strategies = [
v if isinstance(v, st.SearchStrategy) else v(thing)
for k, v in mapping.items()
if sum(try_issubclass(k, T) for T in mapping) == 1
]
empty = ", ".join(repr(s) for s in strategies if s.is_empty)
if empty or not strategies: # pragma: no cover
raise ResolutionFailed(
"Could not resolve %s to a strategy; consider using "
"register_type_strategy" % (empty or thing,)
)
return st.one_of(strategies)
|
https://github.com/HypothesisWorks/hypothesis/issues/1583
|
from typing import Tuple
from hypothesis.strategies import from_type
from_type(Tuple[()]).example()
Traceback (most recent call last):
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 131, in recur
result = mapping[strat]
KeyError: tuples(deferred(lambda: func(*args, **kwargs)))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 131, in recur
result = mapping[strat]
KeyError: tuples(deferred(lambda: func(*args, **kwargs)))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 304, in example
phases=tuple(set(Phase) - {Phase.shrink}),
File "<venv path>\lib\site-packages\hypothesis\core.py", line 979, in find
specifier.validate()
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 380, in validate
self.is_empty
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 142, in accept
recur(self)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 139, in recur
mapping[strat] = getattr(strat, calculation)(recur)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\deferred.py", line 81, in calc_is_empty
return recur(self.wrapped_strategy)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\strategies.py", line 139, in recur
mapping[strat] = getattr(strat, calculation)(recur)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\lazy.py", line 90, in calc_is_empty
return recur(self.wrapped_strategy)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\lazy.py", line 106, in wrapped_strategy
unwrap_strategies(s) for s in self.__args)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\lazy.py", line 106, in <genexpr>
unwrap_strategies(s) for s in self.__args)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\lazy.py", line 48, in unwrap_strategies
result = unwrap_strategies(s.wrapped_strategy)
File "<venv path>\lib\site-packages\hypothesis\searchstrategy\deferred.py", line 45, in wrapped_strategy
result = self.__definition()
File "<venv path>\lib\site-packages\hypothesis\strategies.py", line 1200, in <lambda>
return deferred(lambda: func(*args, **kwargs))
File "<venv path>\lib\site-packages\hypothesis\strategies.py", line 1261, in from_type
raise InvalidArgument('thing=%s must be a type' % (thing,))
hypothesis.errors.InvalidArgument: thing=() must be a type
|
KeyError
|
def _get_strategy_for_field(f):
if f.choices:
choices = []
for value, name_or_optgroup in f.choices:
if isinstance(name_or_optgroup, (list, tuple)):
choices.extend(key for key, _ in name_or_optgroup)
else:
choices.append(value)
if isinstance(f, (dm.CharField, dm.TextField)) and f.blank:
choices.insert(0, "")
strategy = st.sampled_from(choices)
elif type(f) == dm.SlugField:
strategy = st.text(
alphabet=string.ascii_letters + string.digits,
min_size=(None if f.blank else 1),
max_size=f.max_length,
)
elif type(f) == dm.GenericIPAddressField:
lookup = {
"both": ip4_addr_strings() | ip6_addr_strings(),
"ipv4": ip4_addr_strings(),
"ipv6": ip6_addr_strings(),
}
strategy = lookup[f.protocol.lower()]
elif type(f) in (dm.TextField, dm.CharField):
strategy = st.text(
alphabet=st.characters(
blacklist_characters="\x00", blacklist_categories=("Cs",)
),
min_size=(None if f.blank else 1),
max_size=f.max_length,
)
elif type(f) == dm.DecimalField:
bound = Decimal(10**f.max_digits - 1) / (10**f.decimal_places)
strategy = st.decimals(
min_value=-bound, max_value=bound, places=f.decimal_places
)
else:
strategy = field_mappings().get(type(f), st.nothing())
if f.validators:
strategy = strategy.filter(validator_to_filter(f))
if f.null:
strategy = st.one_of(st.none(), strategy)
return strategy
|
def _get_strategy_for_field(f):
if f.choices:
choices = []
for value, name_or_optgroup in f.choices:
if isinstance(name_or_optgroup, (list, tuple)):
choices.extend(key for key, _ in name_or_optgroup)
else:
choices.append(value)
if isinstance(f, (dm.CharField, dm.TextField)) and f.blank:
choices.insert(0, "")
strategy = st.sampled_from(choices)
elif type(f) == dm.SlugField:
strategy = st.text(
alphabet=string.ascii_letters + string.digits,
min_size=(None if f.blank else 1),
max_size=f.max_length,
)
elif type(f) == dm.GenericIPAddressField:
lookup = {
"both": ip4_addr_strings() | ip6_addr_strings(),
"ipv4": ip4_addr_strings(),
"ipv6": ip6_addr_strings(),
}
strategy = lookup[f.protocol.lower()]
elif type(f) in (dm.TextField, dm.CharField):
strategy = st.text(min_size=(None if f.blank else 1), max_size=f.max_length)
elif type(f) == dm.DecimalField:
bound = Decimal(10**f.max_digits - 1) / (10**f.decimal_places)
strategy = st.decimals(
min_value=-bound, max_value=bound, places=f.decimal_places
)
else:
strategy = field_mappings().get(type(f), st.nothing())
if f.validators:
strategy = strategy.filter(validator_to_filter(f))
if f.null:
strategy = st.one_of(st.none(), strategy)
return strategy
|
https://github.com/HypothesisWorks/hypothesis/issues/1045
|
Error
Traceback (most recent call last):
File "/vagrant/savings_champion/products/tests/models.py", line 33, in test_check_bonus
user=models(User),
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 1001, in wrapped_test
state.run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 725, in run
runner.run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 393, in run
self._run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 791, in _run
self.generate_new_examples()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 706, in generate_new_examples
self.test_function(last_data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 153, in test_function
self._test_function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 691, in evaluate_test_data
escalate_hypothesis_internal_error()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 663, in evaluate_test_data
result = self.execute(data, collect=True)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 578, in execute
result = self.test_runner(data, run)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 78, in <lambda>
lambda: function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 33, in execute
return function()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 78, in <lambda>
lambda: function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 552, in run
args, kwargs = data.draw(self.search_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 121, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 136, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 180, in do_draw
return self.base.do_draw(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1550, in do_draw
return f(draw, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/extra/django/models.py", line 161, in _models_impl
return draw(strat)[0]
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1548, in draw
return data.draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1550, in do_draw
return f(draw, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/extra/django/models.py", line 161, in _models_impl
return draw(strat)[0]
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1548, in draw
return data.draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 970, in <lambda>
lambda value: target(*value[0], **value[1])
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 487, in get_or_create
return self.get(**lookup), False
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 397, in get
num = len(clone)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 254, in __len__
self._fetch_all()
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1063, in execute_sql
cursor.execute(sql, params)
File "/home/ubuntu/.local/lib/python3.5/site-packages/raven/contrib/django/client.py", line 123, in execute
return real_execute(self, sql, params)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
ValueError: A string literal cannot contain NUL (0x00) characters.
|
ValueError
|
def text(alphabet=None, min_size=None, average_size=None, max_size=None):
"""Generates values of a unicode text type (unicode on python 2, str on
python 3) with values drawn from alphabet, which should be an iterable of
length one strings or a strategy generating such. If it is None it will
default to generating the full unicode range (excluding surrogate
characters). If it is an empty collection this will only generate empty
strings.
min_size, max_size and average_size have the usual interpretations.
Examples from this strategy shrink towards shorter strings, and with the
characters in the text shrinking as per the alphabet strategy.
"""
from hypothesis.searchstrategy.strings import StringStrategy
if alphabet is None:
char_strategy = characters(blacklist_categories=("Cs",))
elif not alphabet:
if (min_size or 0) > 0:
raise InvalidArgument(
"Invalid min_size %r > 0 for empty alphabet" % (min_size,)
)
return just("")
elif isinstance(alphabet, SearchStrategy):
char_strategy = alphabet
else:
char_strategy = sampled_from(list(map(text_type, alphabet)))
return StringStrategy(
lists(
char_strategy,
average_size=average_size,
min_size=min_size,
max_size=max_size,
)
)
|
def text(alphabet=None, min_size=None, average_size=None, max_size=None):
"""Generates values of a unicode text type (unicode on python 2, str on
python 3) with values drawn from alphabet, which should be an iterable of
length one strings or a strategy generating such. If it is None it will
default to generating the full unicode range. If it is an empty collection
this will only generate empty strings.
min_size, max_size and average_size have the usual interpretations.
Examples from this strategy shrink towards shorter strings, and with the
characters in the text shrinking as per the alphabet strategy.
"""
from hypothesis.searchstrategy.strings import StringStrategy
if alphabet is None:
char_strategy = characters(blacklist_categories=("Cs",))
elif not alphabet:
if (min_size or 0) > 0:
raise InvalidArgument(
"Invalid min_size %r > 0 for empty alphabet" % (min_size,)
)
return just("")
elif isinstance(alphabet, SearchStrategy):
char_strategy = alphabet
else:
char_strategy = sampled_from(list(map(text_type, alphabet)))
return StringStrategy(
lists(
char_strategy,
average_size=average_size,
min_size=min_size,
max_size=max_size,
)
)
|
https://github.com/HypothesisWorks/hypothesis/issues/1045
|
Error
Traceback (most recent call last):
File "/vagrant/savings_champion/products/tests/models.py", line 33, in test_check_bonus
user=models(User),
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 1001, in wrapped_test
state.run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 725, in run
runner.run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 393, in run
self._run()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 791, in _run
self.generate_new_examples()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 706, in generate_new_examples
self.test_function(last_data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 153, in test_function
self._test_function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 691, in evaluate_test_data
escalate_hypothesis_internal_error()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 663, in evaluate_test_data
result = self.execute(data, collect=True)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 578, in execute
result = self.test_runner(data, run)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 78, in <lambda>
lambda: function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 33, in execute
return function()
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/executors.py", line 78, in <lambda>
lambda: function(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 552, in run
args, kwargs = data.draw(self.search_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 121, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 136, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/core.py", line 180, in do_draw
return self.base.do_draw(data)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1550, in do_draw
return f(draw, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/extra/django/models.py", line 161, in _models_impl
return draw(strat)[0]
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1548, in draw
return data.draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/lazy.py", line 158, in do_draw
return data.draw(self.wrapped_strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in do_draw
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 56, in newtuple
return tuple(xs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/collections.py", line 60, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1550, in do_draw
return f(draw, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/extra/django/models.py", line 161, in _models_impl
return draw(strat)[0]
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 1548, in draw
return data.draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 125, in draw
return self.__draw(strategy)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/internal/conjecture/data.py", line 132, in __draw
return strategy.do_draw(self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/searchstrategy/strategies.py", line 507, in do_draw
return self.pack(data.draw(self.mapped_strategy))
File "/home/ubuntu/.local/lib/python3.5/site-packages/hypothesis/strategies.py", line 970, in <lambda>
lambda value: target(*value[0], **value[1])
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 487, in get_or_create
return self.get(**lookup), False
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 397, in get
num = len(clone)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 254, in __len__
self._fetch_all()
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1063, in execute_sql
cursor.execute(sql, params)
File "/home/ubuntu/.local/lib/python3.5/site-packages/raven/contrib/django/client.py", line 123, in execute
return real_execute(self, sql, params)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
ValueError: A string literal cannot contain NUL (0x00) characters.
|
ValueError
|
def __init__(self, test_runner, search_strategy, test, settings, random):
self.test_runner = test_runner
self.search_strategy = search_strategy
self.settings = settings
self.at_least_one_success = False
self.last_exception = None
self.falsifying_examples = ()
self.__was_flaky = False
self.random = random
self.__warned_deadline = False
self.__existing_collector = None
self.__test_runtime = None
self.test = test
self.coverage_data = CoverageData()
self.files_to_propagate = set()
if settings.use_coverage and not IN_COVERAGE_TESTS: # pragma: no cover
if Collector._collectors:
self.hijack_collector(Collector._collectors[-1])
self.collector = Collector(
branch=True,
timid=FORCE_PURE_TRACER,
should_trace=self.should_trace,
check_include=hypothesis_check_include,
concurrency="thread",
warn=escalate_warning,
)
self.collector.reset()
# Hide the other collectors from this one so it doesn't attempt to
# pause them (we're doing trace function management ourselves so
# this will just cause problems).
self.collector._collectors = []
else:
self.collector = None
|
def __init__(self, test_runner, search_strategy, test, settings, random):
self.test_runner = test_runner
self.search_strategy = search_strategy
self.settings = settings
self.at_least_one_success = False
self.last_exception = None
self.repr_for_last_exception = None
self.falsifying_examples = ()
self.__was_flaky = False
self.random = random
self.__warned_deadline = False
self.__existing_collector = None
self.__test_runtime = None
self.__in_final_replay = False
if self.settings.deadline is None:
self.test = test
else:
@proxies(test)
def timed_test(*args, **kwargs):
self.__test_runtime = None
start = time.time()
result = test(*args, **kwargs)
runtime = (time.time() - start) * 1000
self.__test_runtime = runtime
if self.settings.deadline is not_set:
if not self.__warned_deadline and runtime >= 200:
self.__warned_deadline = True
note_deprecation(
(
"Test took %.2fms to run. In future the default "
"deadline setting will be 200ms, which will "
"make this an error. You can set deadline to "
"an explicit value of e.g. %d to turn tests "
"slower than this into an error, or you can set "
"it to None to disable this check entirely."
)
% (
runtime,
ceil(runtime / 100) * 100,
)
)
elif runtime >= self.current_deadline:
raise DeadlineExceeded(runtime, self.settings.deadline)
return result
self.test = timed_test
self.coverage_data = CoverageData()
self.files_to_propagate = set()
if settings.use_coverage and not IN_COVERAGE_TESTS: # pragma: no cover
if Collector._collectors:
self.hijack_collector(Collector._collectors[-1])
self.collector = Collector(
branch=True,
timid=FORCE_PURE_TRACER,
should_trace=self.should_trace,
check_include=hypothesis_check_include,
concurrency="thread",
warn=escalate_warning,
)
self.collector.reset()
# Hide the other collectors from this one so it doesn't attempt to
# pause them (we're doing trace function management ourselves so
# this will just cause problems).
self.collector._collectors = []
else:
self.collector = None
|
https://github.com/HypothesisWorks/hypothesis/issues/911
|
Unreliable test timings! On an initial run, this test took 161.08ms, which exceeded the deadline of 125.00ms, but on a subsequent run it took 78.93 ms, which did not. If you expect this sort of variability in your test timings, consider turning deadlines off for this test by setting deadline=None.
Falsifying example: test_slow_draw(data=data(...))
You can add @seed(302934307671667531413257853548643485645) to this test to reproduce this failure.
Traceback (most recent call last):
File "slow_draw.py", line 24, in <module>
test_slow_draw()
File "slow_draw.py", line 15, in test_slow_draw
deadline=mid, timeout=unlimited, max_examples=10,
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 1008, in wrapped_test
state.run()
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 900, in run
print_example=True, is_final=True
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
return function(data)
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 140, in run
return test(*args, **kwargs)
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 87, in test_or_flaky
) % (test.__name__, text_repr,))
hypothesis.errors.Flaky: Hypothesis test_slow_draw(data=data(...)) produces unreliable results: Falsified on the first call but did not on a subsequent one
|
hypothesis.errors.Flaky
|
def run(data):
with self.settings:
with BuildContext(data, is_final=is_final):
import random as rnd_module
rnd_module.seed(0)
args, kwargs = data.draw(self.search_strategy)
if expected_failure is not None:
text_repr[0] = arg_string(test, args, kwargs)
if print_example:
report(
lambda: "Falsifying example: %s(%s)"
% (test.__name__, arg_string(test, args, kwargs))
)
elif current_verbosity() >= Verbosity.verbose:
report(
lambda: "Trying example: %s(%s)"
% (test.__name__, arg_string(test, args, kwargs))
)
if self.collector is None or not collect:
return test(*args, **kwargs)
else: # pragma: no cover
try:
self.collector.start()
return test(*args, **kwargs)
finally:
self.collector.stop()
|
def run(self):
# Tell pytest to omit the body of this function from tracebacks
__tracebackhide__ = True
database_key = str_to_bytes(fully_qualified_name(self.test))
self.start_time = time.time()
global in_given
runner = ConjectureRunner(
self.evaluate_test_data,
settings=self.settings,
random=self.random,
database_key=database_key,
)
if in_given or self.collector is None:
runner.run()
else: # pragma: no cover
in_given = True
original_trace = sys.gettrace()
try:
sys.settrace(None)
runner.run()
finally:
in_given = False
sys.settrace(original_trace)
note_engine_for_statistics(runner)
run_time = time.time() - self.start_time
timed_out = runner.exit_reason == ExitReason.timeout
if runner.last_data is None:
return
if runner.interesting_examples:
self.falsifying_examples = sorted(
[d for d in runner.interesting_examples.values()],
key=lambda d: sort_key(d.buffer),
reverse=True,
)
else:
if timed_out:
note_deprecation(
(
"Your tests are hitting the settings timeout (%.2fs). "
"This functionality will go away in a future release "
"and you should not rely on it. Instead, try setting "
"max_examples to be some value lower than %d (the number "
"of examples your test successfully ran here). Or, if you "
"would prefer your tests to run to completion, regardless "
"of how long they take, you can set the timeout value to "
"hypothesis.unlimited."
)
% (self.settings.timeout, runner.valid_examples),
self.settings,
)
if runner.valid_examples < min(
self.settings.min_satisfying_examples,
self.settings.max_examples,
) and not (
runner.exit_reason == ExitReason.finished and self.at_least_one_success
):
if timed_out:
raise Timeout(
(
"Ran out of time before finding a satisfying "
"example for "
"%s. Only found %d examples in " + "%.2fs."
)
% (
get_pretty_function_description(self.test),
runner.valid_examples,
run_time,
)
)
else:
raise Unsatisfiable(
(
"Unable to satisfy assumptions of hypothesis "
"%s. Only %d examples considered "
"satisfied assumptions"
)
% (
get_pretty_function_description(self.test),
runner.valid_examples,
)
)
if not self.falsifying_examples:
return
flaky = 0
self.__in_final_replay = True
for falsifying_example in self.falsifying_examples:
self.__was_flaky = False
try:
with self.settings:
self.test_runner(
ConjectureData.for_buffer(falsifying_example.buffer),
reify_and_execute(
self.search_strategy,
self.test,
print_example=True,
is_final=True,
),
)
except (UnsatisfiedAssumption, StopTest):
report(traceback.format_exc())
self.__flaky(
"Unreliable assumption: An example which satisfied "
"assumptions on the first run now fails it."
)
except BaseException:
if len(self.falsifying_examples) <= 1:
raise
report(traceback.format_exc())
else:
if (
isinstance(falsifying_example.__expected_exception, DeadlineExceeded)
and self.__test_runtime is not None
):
report(
(
"Unreliable test timings! On an initial run, this "
"test took %.2fms, which exceeded the deadline of "
"%.2fms, but on a subsequent run it took %.2f ms, "
"which did not. If you expect this sort of "
"variability in your test timings, consider turning "
"deadlines off for this test by setting deadline=None."
)
% (
falsifying_example.__expected_exception.runtime,
self.settings.deadline,
self.__test_runtime,
)
)
else:
report(
"Failed to reproduce exception. Expected: \n"
+ falsifying_example.__expected_traceback,
)
filter_message = (
"Unreliable test data: Failed to reproduce a failure "
"and then when it came to recreating the example in "
"order to print the test data with a flaky result "
"the example was filtered out (by e.g. a "
"call to filter in your strategy) when we didn't "
"expect it to be."
)
try:
self.test_runner(
ConjectureData.for_buffer(falsifying_example.buffer),
reify_and_execute(
self.search_strategy,
test_is_flaky(self.test, self.repr_for_last_exception),
print_example=True,
is_final=True,
),
)
except (UnsatisfiedAssumption, StopTest):
self.__flaky(filter_message)
except Flaky as e:
if len(self.falsifying_examples) > 1:
self.__flaky(e.args[0])
else:
raise
if self.__was_flaky:
flaky += 1
# If we only have one example then we should have raised an error or
# flaky prior to this point.
assert len(self.falsifying_examples) > 1
if flaky > 0:
raise Flaky(
(
"Hypothesis found %d distinct failures, but %d of them "
"exhibited some sort of flaky behaviour."
)
% (len(self.falsifying_examples), flaky)
)
else:
raise MultipleFailures(
("Hypothesis found %d distinct failures.")
% (
len(
self.falsifying_examples,
)
)
)
|
https://github.com/HypothesisWorks/hypothesis/issues/911
|
Unreliable test timings! On an initial run, this test took 161.08ms, which exceeded the deadline of 125.00ms, but on a subsequent run it took 78.93 ms, which did not. If you expect this sort of variability in your test timings, consider turning deadlines off for this test by setting deadline=None.
Falsifying example: test_slow_draw(data=data(...))
You can add @seed(302934307671667531413257853548643485645) to this test to reproduce this failure.
Traceback (most recent call last):
File "slow_draw.py", line 24, in <module>
test_slow_draw()
File "slow_draw.py", line 15, in test_slow_draw
deadline=mid, timeout=unlimited, max_examples=10,
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 1008, in wrapped_test
state.run()
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 900, in run
print_example=True, is_final=True
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
return function(data)
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 140, in run
return test(*args, **kwargs)
File "/home/david/scratch/v/lib/python3.5/site-packages/hypothesis/core.py", line 87, in test_or_flaky
) % (test.__name__, text_repr,))
hypothesis.errors.Flaky: Hypothesis test_slow_draw(data=data(...)) produces unreliable results: Falsified on the first call but did not on a subsequent one
|
hypothesis.errors.Flaky
|
def from_type(thing):
"""Looks up the appropriate search strategy for the given type.
``from_type`` is used internally to fill in missing arguments to
:func:`~hypothesis.strategies.builds` and can be used interactively
to explore what strategies are available or to debug type resolution.
You can use :func:`~hypothesis.strategies.register_type_strategy` to
handle your custom types, or to globally redefine certain strategies -
for example excluding NaN from floats, or use timezone-aware instead of
naive time and datetime strategies.
The resolution logic may be changed in a future version, but currently
tries these four options:
1. If ``thing`` is in the default lookup mapping or user-registered lookup,
return the corresponding strategy. The default lookup covers all types
with Hypothesis strategies, including extras where possible.
2. If ``thing`` is from the :mod:`python:typing` module, return the
corresponding strategy (special logic).
3. If ``thing`` has one or more subtypes in the merged lookup, return
the union of the strategies for those types that are not subtypes of
other elements in the lookup.
4. Finally, if ``thing`` has type annotations for all required arguments,
it is resolved via :func:`~hypothesis.strategies.builds`.
"""
from hypothesis.searchstrategy import types
if not isinstance(thing, type):
try:
# At runtime, `typing.NewType` returns an identity function rather
# than an actual type, but we can check that for a possible match
# and then read the magic attribute to unwrap it.
import typing
if all(
[
hasattr(thing, "__supertype__"),
hasattr(typing, "NewType"),
isfunction(thing),
getattr(thing, "__module__", 0) == "typing",
]
):
return from_type(thing.__supertype__)
# Under Python 3.6, Unions are not instances of `type` - but we
# still want to resolve them!
if getattr(thing, "__origin__", None) is typing.Union:
args = sorted(thing.__args__, key=types.type_sorting_key)
return one_of([from_type(t) for t in args])
except ImportError: # pragma: no cover
pass
raise InvalidArgument("thing=%s must be a type" % (thing,))
# Now that we know `thing` is a type, the first step is to check for an
# explicitly registered strategy. This is the best (and hopefully most
# common) way to resolve a type to a strategy. Note that the value in the
# lookup may be a strategy or a function from type -> strategy; and we
# convert empty results into an explicit error.
if thing in types._global_type_lookup:
strategy = types._global_type_lookup[thing]
if not isinstance(strategy, SearchStrategy):
strategy = strategy(thing)
if strategy.is_empty:
raise ResolutionFailed("Error: %r resolved to an empty strategy" % (thing,))
return strategy
# If there's no explicitly registered strategy, maybe a subtype of thing
# is registered - if so, we can resolve it to the subclass strategy.
# We'll start by checking if thing is from from the typing module,
# because there are several special cases that don't play well with
# subclass and instance checks.
try:
import typing
if isinstance(thing, typing.TypingMeta):
return types.from_typing_type(thing)
except ImportError: # pragma: no cover
pass
# If it's not from the typing module, we get all registered types that are
# a subclass of `thing` and are not themselves a subtype of any other such
# type. For example, `Number -> integers() | floats()`, but bools() is
# not included because bool is a subclass of int as well as Number.
strategies = [
v if isinstance(v, SearchStrategy) else v(thing)
for k, v in types._global_type_lookup.items()
if issubclass(k, thing)
and sum(types.try_issubclass(k, T) for T in types._global_type_lookup) == 1
]
empty = ", ".join(repr(s) for s in strategies if s.is_empty)
if empty:
raise ResolutionFailed(
"Could not resolve %s to a strategy; consider using "
"register_type_strategy" % empty
)
elif strategies:
return one_of(strategies)
# If we don't have a strategy registered for this type or any subtype, we
# may be able to fall back on type annotations.
# Types created via typing.NamedTuple use a custom attribute instead -
# but we can still use builds(), if we work out the right kwargs.
if (
issubclass(thing, tuple)
and hasattr(thing, "_fields")
and hasattr(thing, "_field_types")
):
kwargs = {k: from_type(thing._field_types[k]) for k in thing._fields}
return builds(thing, **kwargs)
# If the constructor has an annotation for every required argument,
# we can (and do) use builds() without supplying additional arguments.
required = required_args(thing)
if not required or required.issubset(get_type_hints(thing.__init__)):
return builds(thing)
# We have utterly failed, and might as well say so now.
raise ResolutionFailed(
"Could not resolve %r to a strategy; consider "
"using register_type_strategy" % (thing,)
)
|
def from_type(thing):
"""Looks up the appropriate search strategy for the given type.
``from_type`` is used internally to fill in missing arguments to
:func:`~hypothesis.strategies.builds` and can be used interactively
to explore what strategies are available or to debug type resolution.
You can use :func:`~hypothesis.strategies.register_type_strategy` to
handle your custom types, or to globally redefine certain strategies -
for example excluding NaN from floats, or use timezone-aware instead of
naive time and datetime strategies.
The resolution logic may be changed in a future version, but currently
tries these four options:
1. If ``thing`` is in the default lookup mapping or user-registered lookup,
return the corresponding strategy. The default lookup covers all types
with Hypothesis strategies, including extras where possible.
2. If ``thing`` is from the :mod:`python:typing` module, return the
corresponding strategy (special logic).
3. If ``thing`` has one or more subtypes in the merged lookup, return
the union of the strategies for those types that are not subtypes of
other elements in the lookup.
4. Finally, if ``thing`` has type annotations for all required arguments,
it is resolved via :func:`~hypothesis.strategies.builds`.
"""
from hypothesis.searchstrategy import types
if not isinstance(thing, type):
# Under Python 3.6, Unions are not instances of `type` - but we still
# want to resolve them! This __origin__ check only passes if thing is
# a Union with parameters; if it doesn't we can't resolve it anyway.
try:
import typing
if getattr(thing, "__origin__", None) is typing.Union:
args = sorted(thing.__args__, key=types.type_sorting_key)
return one_of([from_type(t) for t in args])
except ImportError: # pragma: no cover
pass
raise InvalidArgument("thing=%s must be a type" % (thing,))
# Now that we know `thing` is a type, the first step is to check for an
# explicitly registered strategy. This is the best (and hopefully most
# common) way to resolve a type to a strategy. Note that the value in the
# lookup may be a strategy or a function from type -> strategy; and we
# convert empty results into an explicit error.
if thing in types._global_type_lookup:
strategy = types._global_type_lookup[thing]
if not isinstance(strategy, SearchStrategy):
strategy = strategy(thing)
if strategy.is_empty:
raise ResolutionFailed("Error: %r resolved to an empty strategy" % (thing,))
return strategy
# If there's no explicitly registered strategy, maybe a subtype of thing
# is registered - if so, we can resolve it to the subclass strategy.
# We'll start by checking if thing is from from the typing module,
# because there are several special cases that don't play well with
# subclass and instance checks.
try:
import typing
if isinstance(thing, typing.TypingMeta):
return types.from_typing_type(thing)
except ImportError: # pragma: no cover
pass
# If it's not from the typing module, we get all registered types that are
# a subclass of `thing` and are not themselves a subtype of any other such
# type. For example, `Number -> integers() | floats()`, but bools() is
# not included because bool is a subclass of int as well as Number.
strategies = [
v if isinstance(v, SearchStrategy) else v(thing)
for k, v in types._global_type_lookup.items()
if issubclass(k, thing)
and sum(types.try_issubclass(k, T) for T in types._global_type_lookup) == 1
]
empty = ", ".join(repr(s) for s in strategies if s.is_empty)
if empty:
raise ResolutionFailed(
"Could not resolve %s to a strategy; consider using "
"register_type_strategy" % empty
)
elif strategies:
return one_of(strategies)
# If we don't have a strategy registered for this type or any subtype, we
# may be able to fall back on type annotations.
# Types created via typing.NamedTuple use a custom attribute instead -
# but we can still use builds(), if we work out the right kwargs.
if (
issubclass(thing, tuple)
and hasattr(thing, "_fields")
and hasattr(thing, "_field_types")
):
kwargs = {k: from_type(thing._field_types[k]) for k in thing._fields}
return builds(thing, **kwargs)
# If the constructor has an annotation for every required argument,
# we can (and do) use builds() without supplying additional arguments.
required = required_args(thing)
if not required or required.issubset(get_type_hints(thing.__init__)):
return builds(thing)
# We have utterly failed, and might as well say so now.
raise ResolutionFailed(
"Could not resolve %r to a strategy; consider "
"using register_type_strategy" % (thing,)
)
|
https://github.com/HypothesisWorks/hypothesis/issues/901
|
In [14]: st.from_type(T).example()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in cached_strategy(*args, **kwargs)
104 try:
--> 105 return STRATEGY_CACHE[cache_key]
106 except TypeError:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/cache.py in __getitem__(self, key)
69 def __getitem__(self, key):
---> 70 i = self.keys_to_indices[key]
71 result = self.data[i]
KeyError: (<function from_type at 0x106c740d0>, ((<class 'type'>, <class '__main__.T'>),), frozenset())
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in cached_strategy(*args, **kwargs)
104 try:
--> 105 return STRATEGY_CACHE[cache_key]
106 except TypeError:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/cache.py in __getitem__(self, key)
69 def __getitem__(self, key):
---> 70 i = self.keys_to_indices[key]
71 result = self.data[i]
KeyError: (<function from_type at 0x106c740d0>, ((<class 'function'>, <function NewType.<locals>.new_type at 0x107fd40d0>),), frozenset())
During handling of the above exception, another exception occurred:
InvalidArgument Traceback (most recent call last)
<ipython-input-14-87157b77bd3c> in <module>()
----> 1 st.from_type(T).example()
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/strategies.py in example(self, random)
284 max_iterations=1000,
285 database=None,
--> 286 verbosity=Verbosity.quiet,
287 )
288 )
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/core.py in find(specifier, condition, settings, random, database_key)
1067 database_key=database_key,
1068 )
-> 1069 runner.run()
1070 note_engine_for_statistics(runner)
1071 run_time = time.time() - start
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/engine.py in run(self)
380 with self.settings:
381 try:
--> 382 self._run()
383 except RunIsComplete:
384 pass
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/engine.py in _run(self)
754
755 self.reuse_existing_examples()
--> 756 self.generate_new_examples()
757
758 if (
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/engine.py in generate_new_examples(self)
655 draw_bytes=lambda data, n: self.__rewrite_for_novelty(
656 data, hbytes(n)))
--> 657 self.test_function(zero_data)
658
659 count = 0
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/engine.py in test_function(self, data)
122 self.call_count += 1
123 try:
--> 124 self._test_function(data)
125 data.freeze()
126 except StopTest as e:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/core.py in template_condition(data)
1036 try:
1037 data.is_find = True
-> 1038 result = data.draw(search)
1039 data.note(result)
1040 success = condition(result)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
123 try:
124 sys.settrace(None)
--> 125 return self.__draw(strategy)
126 finally:
127 sys.settrace(original_tracer)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/lazy.py in do_draw(self, data)
165
166 def do_draw(self, data):
--> 167 return data.draw(self.wrapped_strategy)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/strategies.py in do_draw(self, data)
505 i = data.index
506 try:
--> 507 return self.pack(data.draw(self.mapped_strategy))
508 except UnsatisfiedAssumption:
509 if data.index == i:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/lazy.py in do_draw(self, data)
165
166 def do_draw(self, data):
--> 167 return data.draw(self.wrapped_strategy)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in do_draw(self, data)
58 def do_draw(self, data):
59 return self.newtuple(
---> 60 data.draw(e) for e in self.element_strategies
61 )
62
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in newtuple(self, xs)
54 def newtuple(self, xs):
55 """Produce a new tuple of the correct type."""
---> 56 return tuple(xs)
57
58 def do_draw(self, data):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in <genexpr>(.0)
58 def do_draw(self, data):
59 return self.newtuple(
---> 60 data.draw(e) for e in self.element_strategies
61 )
62
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/strategies.py in do_draw(self, data)
505 i = data.index
506 try:
--> 507 return self.pack(data.draw(self.mapped_strategy))
508 except UnsatisfiedAssumption:
509 if data.index == i:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in do_draw(self, data)
58 def do_draw(self, data):
59 return self.newtuple(
---> 60 data.draw(e) for e in self.element_strategies
61 )
62
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in newtuple(self, xs)
54 def newtuple(self, xs):
55 """Produce a new tuple of the correct type."""
---> 56 return tuple(xs)
57
58 def do_draw(self, data):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/collections.py in <genexpr>(.0)
58 def do_draw(self, data):
59 return self.newtuple(
---> 60 data.draw(e) for e in self.element_strategies
61 )
62
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in draw(self, strategy)
127 sys.settrace(original_tracer)
128 else:
--> 129 return self.__draw(strategy)
130
131 def __draw(self, strategy):
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/internal/conjecture/data.py in __draw(self, strategy)
132 self.start_example()
133 try:
--> 134 return strategy.do_draw(self)
135 finally:
136 if not self.frozen:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/searchstrategy/strategies.py in do_draw(self, data)
505 i = data.index
506 try:
--> 507 return self.pack(data.draw(self.mapped_strategy))
508 except UnsatisfiedAssumption:
509 if data.index == i:
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in <lambda>(value)
871 kwargs[ms] = from_type(hints[ms])
872 return tuples(tuples(*args), fixed_dictionaries(kwargs)).map(
--> 873 lambda value: target(*value[0], **value[1])
874 )
875
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in lazy_error()
891
892 def lazy_error():
--> 893 raise error
894
895 return builds(lazy_error)
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in inner(*args, **kwargs)
886 def inner(*args, **kwargs):
887 try:
--> 888 return func(*args, **kwargs)
889 except Exception as e:
890 error = e
/Users/daenyth/.pyenv/versions/3.6.1/envs/obs-venv/lib/python3.6/site-packages/hypothesis/strategies.py in from_type(thing)
938 except ImportError: # pragma: no cover
939 pass
--> 940 raise InvalidArgument('thing=%s must be a type' % (thing,))
941 # Now that we know `thing` is a type, the first step is to check for an
942 # explicitly registered strategy. This is the best (and hopefully most
InvalidArgument: thing=<function NewType.<locals>.new_type at 0x107fd40d0> must be a type
|
KeyError
|
def fractions(min_value=None, max_value=None, max_denominator=None):
"""Returns a strategy which generates Fractions.
If min_value is not None then all generated values are no less than
min_value. If max_value is not None then all generated values are no
greater than max_value. min_value and max_value may be anything accepted
by the `python:`~fractions.Fraction` constructor.
If max_denominator is not None then the denominator of any generated
values is no greater than max_denominator. Note that max_denominator must
be None or a positive integer.
"""
if min_value is not None:
min_value = Fraction(min_value)
if max_value is not None:
max_value = Fraction(max_value)
check_valid_bound(min_value, "min_value")
check_valid_bound(max_value, "max_value")
check_valid_interval(min_value, max_value, "min_value", "max_value")
check_valid_integer(max_denominator)
if max_denominator is not None:
if max_denominator < 1:
raise InvalidArgument("max_denominator=%r must be >= 1" % max_denominator)
def fraction_bounds(value):
"""Find the best lower and upper approximation for value."""
# Adapted from CPython's Fraction.limit_denominator here:
# https://github.com/python/cpython/blob/3.6/Lib/fractions.py#L219
if value is None or value.denominator <= max_denominator:
return value, value
p0, q0, p1, q1 = 0, 1, 1, 0
n, d = value.numerator, value.denominator
while True:
a = n // d
q2 = q0 + a * q1
if q2 > max_denominator:
break
p0, q0, p1, q1 = p1, q1, p0 + a * p1, q2
n, d = d, n - a * d
k = (max_denominator - q0) // q1
low, high = Fraction(p1, q1), Fraction(p0 + k * p1, q0 + k * q1)
assert low < value < high
return low, high
# Take the high approximation for min_value and low for max_value
bounds = (max_denominator, min_value, max_value)
_, min_value = fraction_bounds(min_value)
max_value, _ = fraction_bounds(max_value)
if None not in (min_value, max_value) and min_value > max_value:
raise InvalidArgument(
"There are no fractions with a denominator <= %r between "
"min_value=%r and max_value=%r" % bounds
)
if min_value is not None and min_value == max_value:
return just(min_value)
def dm_func(denom):
"""Take denom, construct numerator strategy, and build fraction."""
# Four cases of algebra to get integer bounds and scale factor.
min_num, max_num = None, None
if max_value is None and min_value is None:
pass
elif min_value is None:
max_num = denom * max_value.numerator
denom *= max_value.denominator
elif max_value is None:
min_num = denom * min_value.numerator
denom *= min_value.denominator
else:
low = min_value.numerator * max_value.denominator
high = max_value.numerator * min_value.denominator
scale = min_value.denominator * max_value.denominator
# After calculating our integer bounds and scale factor, we remove
# the gcd to avoid drawing more bytes for the example than needed.
# Note that `div` can be at most equal to `scale`.
div = gcd(scale, gcd(low, high))
min_num = denom * low // div
max_num = denom * high // div
denom *= scale // div
return builds(
Fraction, integers(min_value=min_num, max_value=max_num), just(denom)
)
if max_denominator is None:
return integers(min_value=1).flatmap(dm_func)
return (
integers(1, max_denominator)
.flatmap(dm_func)
.map(lambda f: f.limit_denominator(max_denominator))
)
|
def fractions(min_value=None, max_value=None, max_denominator=None):
"""Returns a strategy which generates Fractions.
If min_value is not None then all generated values are no less than
min_value.
If max_value is not None then all generated values are no greater than
max_value.
If max_denominator is not None then the absolute value of the denominator
of any generated values is no greater than max_denominator. Note that
max_denominator must be at least 1.
"""
check_valid_bound(min_value, "min_value")
check_valid_bound(max_value, "max_value")
check_valid_interval(min_value, max_value, "min_value", "max_value")
check_valid_integer(max_denominator)
if max_denominator is not None and max_denominator < 1:
raise InvalidArgument("Invalid denominator bound %s" % max_denominator)
denominator_strategy = integers(min_value=1, max_value=max_denominator)
def dm_func(denom):
max_num = max_value * denom if max_value is not None else None
min_num = min_value * denom if min_value is not None else None
return builds(
Fraction, integers(min_value=min_num, max_value=max_num), just(denom)
)
return denominator_strategy.flatmap(dm_func)
|
https://github.com/HypothesisWorks/hypothesis/issues/739
|
tmpproj.test_tight_decimal_range ... FAIL
======================================================================
FAIL: tmpproj.test_tight_decimal_range
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/private/var/folders/fl/lt_vq2n17117s6n2qp9s7z2m0000gn/T/tmp.WjAPvqmP/tmpproj.py", line 5, in test_tight_decimal_range
def test_tight_decimal_range(num):
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 634, in wrapped_test
state.run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 478, in run
runner.run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 235, in run
self._run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 387, in _run
self.test_function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 97, in test_function
self._test_function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 465, in evaluate_test_data
escalate_hypothesis_internal_error()
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 448, in evaluate_test_data
self.search_strategy, self.test,
File "/usr/local/lib/python2.7/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
return function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 103, in run
args, kwargs = data.draw(search_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in do_draw
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 59, in newtuple
return tuple(xs)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in do_draw
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 59, in newtuple
return tuple(xs)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 225, in do_draw
return data.draw(self.element_strategies[i])
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/flatmapped.py", line 44, in do_draw
return data.draw(self.expand(source))
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 79, in wrapped_strategy
*[unwrap_strategies(s) for s in self.__args],
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 39, in unwrap_strategies
s = s.wrapped_strategy
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 81, in wrapped_strategy
for k, v in self.__kwargs.items()})
File "/usr/local/lib/python2.7/site-packages/hypothesis/strategies.py", line 232, in integers
assert min_int_value <= max_int_value
AssertionError
----------------------------------------------------------------------
Ran 1 test in 0.014s
FAILED (failures=1)
|
AssertionError
|
def dm_func(denom):
"""Take denom, construct numerator strategy, and build fraction."""
# Four cases of algebra to get integer bounds and scale factor.
min_num, max_num = None, None
if max_value is None and min_value is None:
pass
elif min_value is None:
max_num = denom * max_value.numerator
denom *= max_value.denominator
elif max_value is None:
min_num = denom * min_value.numerator
denom *= min_value.denominator
else:
low = min_value.numerator * max_value.denominator
high = max_value.numerator * min_value.denominator
scale = min_value.denominator * max_value.denominator
# After calculating our integer bounds and scale factor, we remove
# the gcd to avoid drawing more bytes for the example than needed.
# Note that `div` can be at most equal to `scale`.
div = gcd(scale, gcd(low, high))
min_num = denom * low // div
max_num = denom * high // div
denom *= scale // div
return builds(Fraction, integers(min_value=min_num, max_value=max_num), just(denom))
|
def dm_func(denom):
max_num = max_value * denom if max_value is not None else None
min_num = min_value * denom if min_value is not None else None
return builds(Fraction, integers(min_value=min_num, max_value=max_num), just(denom))
|
https://github.com/HypothesisWorks/hypothesis/issues/739
|
tmpproj.test_tight_decimal_range ... FAIL
======================================================================
FAIL: tmpproj.test_tight_decimal_range
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/private/var/folders/fl/lt_vq2n17117s6n2qp9s7z2m0000gn/T/tmp.WjAPvqmP/tmpproj.py", line 5, in test_tight_decimal_range
def test_tight_decimal_range(num):
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 634, in wrapped_test
state.run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 478, in run
runner.run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 235, in run
self._run()
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 387, in _run
self.test_function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/engine.py", line 97, in test_function
self._test_function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 465, in evaluate_test_data
escalate_hypothesis_internal_error()
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 448, in evaluate_test_data
self.search_strategy, self.test,
File "/usr/local/lib/python2.7/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
return function(data)
File "/usr/local/lib/python2.7/site-packages/hypothesis/core.py", line 103, in run
args, kwargs = data.draw(search_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in do_draw
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 59, in newtuple
return tuple(xs)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in do_draw
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 59, in newtuple
return tuple(xs)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/collections.py", line 63, in <genexpr>
data.draw(e) for e in self.element_strategies
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 225, in do_draw
return data.draw(self.element_strategies[i])
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/strategies.py", line 279, in do_draw
return self.pack(self.mapped_strategy.do_draw(data))
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/flatmapped.py", line 44, in do_draw
return data.draw(self.expand(source))
File "/usr/local/lib/python2.7/site-packages/hypothesis/internal/conjecture/data.py", line 104, in draw
return strategy.do_draw(self)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 117, in do_draw
return data.draw(self.wrapped_strategy)
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 79, in wrapped_strategy
*[unwrap_strategies(s) for s in self.__args],
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 39, in unwrap_strategies
s = s.wrapped_strategy
File "/usr/local/lib/python2.7/site-packages/hypothesis/searchstrategy/deferred.py", line 81, in wrapped_strategy
for k, v in self.__kwargs.items()})
File "/usr/local/lib/python2.7/site-packages/hypothesis/strategies.py", line 232, in integers
assert min_int_value <= max_int_value
AssertionError
----------------------------------------------------------------------
Ran 1 test in 0.014s
FAILED (failures=1)
|
AssertionError
|
def set_cookie(
cls,
message,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
):
"""
Sets a cookie in the passed HTTP response message.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
"""
value = force_str(value)
cookies = SimpleCookie()
cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = expires - expires.utcnow()
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
cookies[key]["expires"] = expires
else:
cookies[key]["expires"] = ""
if max_age is not None:
cookies[key]["max-age"] = max_age
# IE requires expires, so set it if hasn't been already.
if not expires:
cookies[key]["expires"] = http_date(time.time() + max_age)
if path is not None:
cookies[key]["path"] = path
if domain is not None:
cookies[key]["domain"] = domain
if secure:
cookies[key]["secure"] = True
if httponly:
cookies[key]["httponly"] = True
# Write out the cookies to the response
for c in cookies.values():
message.setdefault("headers", []).append(
(b"Set-Cookie", bytes(c.output(header=""), encoding="utf-8"))
)
|
def set_cookie(
cls,
message,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
):
"""
Sets a cookie in the passed HTTP response message.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
"""
value = force_str(value)
cookies = SimpleCookie()
cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = expires - expires.utcnow()
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
cookies[key]["expires"] = expires
else:
cookies[key]["expires"] = ""
if max_age is not None:
cookies[key]["max-age"] = max_age
# IE requires expires, so set it if hasn't been already.
if not expires:
cookies[key]["expires"] = cookie_date(time.time() + max_age)
if path is not None:
cookies[key]["path"] = path
if domain is not None:
cookies[key]["domain"] = domain
if secure:
cookies[key]["secure"] = True
if httponly:
cookies[key]["httponly"] = True
# Write out the cookies to the response
for c in cookies.values():
message.setdefault("headers", []).append(
(b"Set-Cookie", bytes(c.output(header=""), encoding="utf-8"))
)
|
https://github.com/django/channels/issues/1226
|
Traceback (most recent call last):
File "manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\core\management\__init__.py", line 357, in execute
django.setup()
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\apps\registry.py", line 122, in populate
app_config.ready()
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\apps.py", line 9, in ready
from . import signals # Bind signals.
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\signals.py", line 6, in <module>
from .consumers import TimerConsumer
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\consumers.py", line 7, in <module>
from channels.auth import get_user
File "D:\Professional\firstinspires\fll-scoring\fllfms\venv\lib\site-packages\channels\auth.py", line 19, in <module>
from channels.sessions import CookieMiddleware, SessionMiddleware
File "D:\Professional\firstinspires\fll-scoring\fllfms\venv\lib\site-packages\channels\sessions.py", line 13, in <module>
from django.utils.http import cookie_date
ImportError: cannot import name 'cookie_date'
|
ImportError
|
async def send(self, message):
"""
Overridden send that also does session saves/cookies.
"""
# Only save session if we're the outermost session middleware
if self.activated:
modified = self.scope["session"].modified
empty = self.scope["session"].is_empty()
# If this is a message type that we want to save on, and there's
# changed data, save it. We also save if it's empty as we might
# not be able to send a cookie-delete along with this message.
if (
message["type"] in self.middleware.save_message_types
and message.get("status", 200) != 500
and (modified or settings.SESSION_SAVE_EVERY_REQUEST)
):
self.save_session()
# If this is a message type that can transport cookies back to the
# client, then do so.
if message["type"] in self.middleware.cookie_response_message_types:
if empty:
# Delete cookie if it's set
if settings.SESSION_COOKIE_NAME in self.scope["cookies"]:
CookieMiddleware.delete_cookie(
message,
settings.SESSION_COOKIE_NAME,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
)
else:
# Get the expiry data
if self.scope["session"].get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = self.scope["session"].get_expiry_age()
expires_time = time.time() + max_age
expires = http_date(expires_time)
# Set the cookie
CookieMiddleware.set_cookie(
message,
self.middleware.cookie_name,
self.scope["session"].session_key,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
)
# Pass up the send
return await self.real_send(message)
|
async def send(self, message):
"""
Overridden send that also does session saves/cookies.
"""
# Only save session if we're the outermost session middleware
if self.activated:
modified = self.scope["session"].modified
empty = self.scope["session"].is_empty()
# If this is a message type that we want to save on, and there's
# changed data, save it. We also save if it's empty as we might
# not be able to send a cookie-delete along with this message.
if (
message["type"] in self.middleware.save_message_types
and message.get("status", 200) != 500
and (modified or settings.SESSION_SAVE_EVERY_REQUEST)
):
self.save_session()
# If this is a message type that can transport cookies back to the
# client, then do so.
if message["type"] in self.middleware.cookie_response_message_types:
if empty:
# Delete cookie if it's set
if settings.SESSION_COOKIE_NAME in self.scope["cookies"]:
CookieMiddleware.delete_cookie(
message,
settings.SESSION_COOKIE_NAME,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
)
else:
# Get the expiry data
if self.scope["session"].get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = self.scope["session"].get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Set the cookie
CookieMiddleware.set_cookie(
message,
self.middleware.cookie_name,
self.scope["session"].session_key,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
)
# Pass up the send
return await self.real_send(message)
|
https://github.com/django/channels/issues/1226
|
Traceback (most recent call last):
File "manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\core\management\__init__.py", line 357, in execute
django.setup()
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "d:\professional\firstinspires\fll-scoring\fllfms\venv\src\django\django\apps\registry.py", line 122, in populate
app_config.ready()
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\apps.py", line 9, in ready
from . import signals # Bind signals.
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\signals.py", line 6, in <module>
from .consumers import TimerConsumer
File "D:\Professional\firstinspires\fll-scoring\fllfms\fllfms\consumers.py", line 7, in <module>
from channels.auth import get_user
File "D:\Professional\firstinspires\fll-scoring\fllfms\venv\lib\site-packages\channels\auth.py", line 19, in <module>
from channels.sessions import CookieMiddleware, SessionMiddleware
File "D:\Professional\firstinspires\fll-scoring\fllfms\venv\lib\site-packages\channels\sessions.py", line 13, in <module>
from django.utils.http import cookie_date
ImportError: cannot import name 'cookie_date'
|
ImportError
|
def touch_member(self, data, ttl=None, permanent=False):
cluster = self.cluster
member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
create_member = not permanent and self.refresh_session()
if member and (create_member or member.session != self._session):
self._client.kv.delete(self.member_path)
create_member = True
if not create_member and member and deep_compare(data, member.data):
return True
try:
args = {} if permanent else {"acquire": self._session}
self._client.kv.put(
self.member_path, json.dumps(data, separators=(",", ":")), **args
)
if self._register_service:
self.update_service(
not create_member and member and member.data or {}, data
)
return True
except Exception:
logger.exception("touch_member")
return False
|
def touch_member(self, data, ttl=None, permanent=False):
cluster = self.cluster
member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
create_member = not permanent and self.refresh_session()
if member and (create_member or member.session != self._session):
try:
self._client.kv.delete(self.member_path)
create_member = True
except Exception:
return False
if not create_member and member and deep_compare(data, member.data):
return True
try:
args = {} if permanent else {"acquire": self._session}
self._client.kv.put(
self.member_path, json.dumps(data, separators=(",", ":")), **args
)
if self._register_service:
self.update_service(
not create_member and member and member.data or {}, data
)
return True
except Exception:
logger.exception("touch_member")
return False
|
https://github.com/zalando/patroni/issues/853
|
2018-11-06 23:06:17,073 INFO: Lock owner: db1; I am db1reserve
2018-11-06 23:06:17,074 INFO: does not have lock
2018-11-06 23:06:17,095 INFO: no action. i am a secondary and i am following a leader
2018-11-06 23:06:27,497 ERROR: watch
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib64/python3.4/http/client.py", line 1227, in getresponse
response.begin()
File "/usr/lib64/python3.4/http/client.py", line 386, in begin
version, status, reason = self._read_status()
File "/usr/lib64/python3.4/http/client.py", line 348, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib64/python3.4/socket.py", line 378, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 386, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 306, in _raise_timeout
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='localhost', port=8500): Read timed out. (read timeout=10.388829231262207)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 494, in watch
idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's')
File "/usr/lib/python3.4/site-packages/consul/base.py", line 554, in get
params=params)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 105, in wrapper
return callback(self.response(self.http.request(method.upper(), self.uri(path, params), **kwargs)))
File "/usr/lib/python3.4/site-packages/urllib3/request.py", line 68, in request
**urlopen_kw)
File "/usr/lib/python3.4/site-packages/urllib3/request.py", line 89, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File "/usr/lib/python3.4/site-packages/urllib3/poolmanager.py", line 322, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "/usr/lib/python3.4/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3.4/site-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=8500): Max retries exceeded with url: /v1/kv/patroni/dbcluster/leader?wait=9.388829231262207s&index=22078692 (Caused by ReadTimeoutError("HTTPConnectionPool(host='localhost', port=8500): Read timed out. (read timeout=10.388829231262207)",))
2018-11-06 23:06:39,312 INFO: Lock owner: db1; I am db1reserve
2018-11-06 23:06:39,315 INFO: does not have lock
2018-11-06 23:07:46,569 ERROR: refresh_session
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/utils.py", line 254, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 249, in _do_refresh_session
self._client.session.renew(self._session)
File "/usr/lib/python3.4/site-packages/consul/base.py", line 1913, in renew
params=params)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 105, in wrapper
return callback(self.response(self.http.request(method.upper(), self.uri(path, params), **kwargs)))
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 76, in response
raise ConsulInternalError(msg)
patroni.dcs.consul.ConsulInternalError: 500 rpc error getting client: failed to get conn: dial tcp <nil>->192.168.241.12:8300: i/o timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 268, in refresh_session
return self.retry(self._do_refresh_session)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 214, in retry
return self._retry.copy()(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/patroni/utils.py", line 263, in __call__
raise RetryFailedError("Exceeded retry deadline")
patroni.utils.RetryFailedError: 'Exceeded retry deadline'
2018-11-06 23:07:49,542 INFO: Lock owner: db1; I am db1reserve
2018-11-06 23:08:56,082 ERROR: refresh_session
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 149, in patroni_main
patroni.run()
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 114, in run
logger.info(self.ha.run_cycle())
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 1236, in run_cycle
info = self._run_cycle()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 1232, in _run_cycle
self.touch_member()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 178, in touch_member
return self.dcs.touch_member(data)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 344, in touch_member
create_member = not permanent and self.refresh_session()
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 271, in refresh_session
raise ConsulError('Failed to renew/create session')
patroni.dcs.consul.ConsulError: 'Failed to renew/create session'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/utils.py", line 254, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 249, in _do_refresh_session
self._client.session.renew(self._session)
File "/usr/lib/python3.4/site-packages/consul/base.py", line 1913, in renew
params=params)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 105, in wrapper
return callback(self.response(self.http.request(method.upper(), self.uri(path, params), **kwargs)))
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 76, in response
raise ConsulInternalError(msg)
patroni.dcs.consul.ConsulInternalError: 500 rpc error getting client: failed to get conn: dial tcp <nil>->192.168.241.12:8300: i/o timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 268, in refresh_session
return self.retry(self._do_refresh_session)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 214, in retry
return self._retry.copy()(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/patroni/utils.py", line 263, in __call__
raise RetryFailedError("Exceeded retry deadline")
patroni.utils.RetryFailedError: 'Exceeded retry deadline'
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 53742)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 51610)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 51612)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 39238)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 39242)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.242.11', 39240)
----------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 149, in patroni_main
patroni.run()
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 114, in run
logger.info(self.ha.run_cycle())
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 1236, in run_cycle
info = self._run_cycle()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 1232, in _run_cycle
self.touch_member()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 178, in touch_member
return self.dcs.touch_member(data)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 344, in touch_member
create_member = not permanent and self.refresh_session()
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 271, in refresh_session
raise ConsulError('Failed to renew/create session')
patroni.dcs.consul.ConsulError: 'Failed to renew/create session'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/patroni", line 11, in <module>
sys.exit(main())
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 182, in main
return patroni_main()
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 153, in patroni_main
patroni.shutdown()
File "/usr/lib/python3.4/site-packages/patroni/__init__.py", line 137, in shutdown
self.ha.shutdown()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 1253, in shutdown
self.touch_member()
File "/usr/lib/python3.4/site-packages/patroni/ha.py", line 178, in touch_member
return self.dcs.touch_member(data)
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 344, in touch_member
create_member = not permanent and self.refresh_session()
File "/usr/lib/python3.4/site-packages/patroni/dcs/consul.py", line 271, in refresh_session
raise ConsulError('Failed to renew/create session')
patroni.dcs.consul.ConsulError: 'Failed to renew/create session'
|
urllib3.exceptions.ReadTimeoutError
|
def apply_config_changes(before_editing, data, kvpairs):
"""Applies config changes specified as a list of key-value pairs.
Keys are interpreted as dotted paths into the configuration data structure. Except for paths beginning with
`postgresql.parameters` where rest of the path is used directly to allow for PostgreSQL GUCs containing dots.
Values are interpreted as YAML values.
:param before_editing: human representation before editing
:param data: configuration datastructure
:param kvpairs: list of strings containing key value pairs separated by =
:returns tuple of human readable and parsed datastructure after changes
"""
changed_data = copy.deepcopy(data)
def set_path_value(config, path, value, prefix=()):
# Postgresql GUCs can't be nested, but can contain dots so we re-flatten the structure for this case
if prefix == ("postgresql", "parameters"):
path = [".".join(path)]
key = path[0]
if len(path) == 1:
if value is None:
config.pop(key, None)
else:
config[key] = value
else:
if not isinstance(config.get(key), dict):
config[key] = {}
set_path_value(config[key], path[1:], value, prefix + (key,))
if config[key] == {}:
del config[key]
for pair in kvpairs:
if not pair or "=" not in pair:
raise PatroniCtlException("Invalid parameter setting {0}".format(pair))
key_path, value = pair.split("=", 1)
set_path_value(changed_data, key_path.strip().split("."), yaml.safe_load(value))
return format_config_for_editing(changed_data), changed_data
|
def apply_config_changes(before_editing, data, kvpairs):
"""Applies config changes specified as a list of key-value pairs.
Keys are interpreted as dotted paths into the configuration data structure. Except for paths beginning with
`postgresql.parameters` where rest of the path is used directly to allow for PostgreSQL GUCs containing dots.
Values are interpreted as YAML values.
:param before_editing: human representation before editing
:param data: configuration datastructure
:param kvpairs: list of strings containing key value pairs separated by =
:returns tuple of human readable and parsed datastructure after changes
"""
changed_data = copy.deepcopy(data)
def set_path_value(config, path, value, prefix=()):
# Postgresql GUCs can't be nested, but can contain dots so we re-flatten the structure for this case
if prefix == ("postgresql", "parameters"):
path = [".".join(path)]
if len(path) == 1:
if value is None:
config.pop(path[0], None)
else:
config[path[0]] = value
else:
key = path[0]
if key not in config:
config[key] = {}
set_path_value(config[key], path[1:], value, prefix + (key,))
if config[key] == {}:
del config[key]
for pair in kvpairs:
if not pair or "=" not in pair:
raise PatroniCtlException("Invalid parameter setting {0}".format(pair))
key_path, value = pair.split("=", 1)
set_path_value(changed_data, key_path.strip().split("."), yaml.safe_load(value))
return format_config_for_editing(changed_data), changed_data
|
https://github.com/zalando/patroni/issues/491
|
[root@postgres-5-2 ~]# patronictl -c /etc/patroni.yaml edit-config postgres-5
---
+++
@@ -11,4 +11,4 @@
use_pg_rewind: true
use_slots: true
retry_timeout: 10
-ttl: 30
+ttl: 31
Apply these changes? [y/N]: y
2017-07-28 23:27:53,965 - ERROR - Unhandled exception in connection loop
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python3.4/threading.py", line 911, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.4/threading.py", line 859, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 471, in zk_loop
if retry(self._connect_loop, retry) is STOP_CONNECTING:
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 488, in _connect_loop
status = self._connect_attempt(host, port, retry)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
2017-07-28 23:27:54,328 - ERROR - set_config_value
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/zookeeper.py", line 230, in set_config_value
self._client.retry(self._client.set, self.config_path, value.encode('utf-8'), version=index or -1)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 273, in _retry
return self._retry.copy()(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 1219, in set
return self.set_async(path, value, version).get()
File "/usr/lib/python3.4/site-packages/kazoo/handlers/utils.py", line 72, in get
raise self._exception
kazoo.exceptions.ConnectionClosedError: Connection has been closed
Error: Config modification aborted due to concurrent changes
|
kazoo.exceptions.ConnectionClosedError
|
def set_path_value(config, path, value, prefix=()):
# Postgresql GUCs can't be nested, but can contain dots so we re-flatten the structure for this case
if prefix == ("postgresql", "parameters"):
path = [".".join(path)]
key = path[0]
if len(path) == 1:
if value is None:
config.pop(key, None)
else:
config[key] = value
else:
if not isinstance(config.get(key), dict):
config[key] = {}
set_path_value(config[key], path[1:], value, prefix + (key,))
if config[key] == {}:
del config[key]
|
def set_path_value(config, path, value, prefix=()):
# Postgresql GUCs can't be nested, but can contain dots so we re-flatten the structure for this case
if prefix == ("postgresql", "parameters"):
path = [".".join(path)]
if len(path) == 1:
if value is None:
config.pop(path[0], None)
else:
config[path[0]] = value
else:
key = path[0]
if key not in config:
config[key] = {}
set_path_value(config[key], path[1:], value, prefix + (key,))
if config[key] == {}:
del config[key]
|
https://github.com/zalando/patroni/issues/491
|
[root@postgres-5-2 ~]# patronictl -c /etc/patroni.yaml edit-config postgres-5
---
+++
@@ -11,4 +11,4 @@
use_pg_rewind: true
use_slots: true
retry_timeout: 10
-ttl: 30
+ttl: 31
Apply these changes? [y/N]: y
2017-07-28 23:27:53,965 - ERROR - Unhandled exception in connection loop
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python3.4/threading.py", line 911, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.4/threading.py", line 859, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 471, in zk_loop
if retry(self._connect_loop, retry) is STOP_CONNECTING:
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 488, in _connect_loop
status = self._connect_attempt(host, port, retry)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
2017-07-28 23:27:54,328 - ERROR - set_config_value
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/zookeeper.py", line 230, in set_config_value
self._client.retry(self._client.set, self.config_path, value.encode('utf-8'), version=index or -1)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 273, in _retry
return self._retry.copy()(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 1219, in set
return self.set_async(path, value, version).get()
File "/usr/lib/python3.4/site-packages/kazoo/handlers/utils.py", line 72, in get
raise self._exception
kazoo.exceptions.ConnectionClosedError: Connection has been closed
Error: Config modification aborted due to concurrent changes
|
kazoo.exceptions.ConnectionClosedError
|
def edit_config(
obj,
cluster_name,
force,
quiet,
kvpairs,
pgkvpairs,
apply_filename,
replace_filename,
):
dcs = get_dcs(obj, cluster_name)
cluster = dcs.get_cluster()
before_editing = format_config_for_editing(cluster.config.data)
after_editing = None # Serves as a flag if any changes were requested
changed_data = cluster.config.data
if replace_filename:
after_editing, changed_data = apply_yaml_file({}, replace_filename)
if apply_filename:
after_editing, changed_data = apply_yaml_file(changed_data, apply_filename)
if kvpairs or pgkvpairs:
all_pairs = list(kvpairs) + [
"postgresql.parameters." + v.lstrip() for v in pgkvpairs
]
after_editing, changed_data = apply_config_changes(
before_editing, changed_data, all_pairs
)
# If no changes were specified on the command line invoke editor
if after_editing is None:
after_editing, changed_data = invoke_editor(before_editing, cluster_name)
if cluster.config.data == changed_data:
if not quiet:
click.echo("Not changed")
return
if not quiet:
show_diff(before_editing, after_editing)
if (apply_filename == "-" or replace_filename == "-") and not force:
click.echo("Use --force option to apply changes")
return
if force or click.confirm("Apply these changes?"):
if not dcs.set_config_value(json.dumps(changed_data), cluster.config.index):
raise PatroniCtlException(
"Config modification aborted due to concurrent changes"
)
click.echo("Configuration changed")
|
def edit_config(
obj,
cluster_name,
force,
quiet,
kvpairs,
pgkvpairs,
apply_filename,
replace_filename,
):
dcs = get_dcs(obj, cluster_name)
cluster = dcs.get_cluster()
before_editing = format_config_for_editing(cluster.config.data)
after_editing = None # Serves as a flag if any changes were requested
changed_data = cluster.config.data
if replace_filename:
after_editing, changed_data = apply_yaml_file({}, replace_filename)
if apply_filename:
after_editing, changed_data = apply_yaml_file(changed_data, apply_filename)
if kvpairs or pgkvpairs:
all_pairs = list(kvpairs) + [
"postgresql.parameters." + v.lstrip() for v in pgkvpairs
]
after_editing, changed_data = apply_config_changes(
before_editing, changed_data, all_pairs
)
# If no changes were specified on the command line invoke editor
if after_editing is None:
after_editing, changed_data = invoke_editor(before_editing, cluster_name)
if cluster.config.data == changed_data:
if not quiet:
click.echo("Not changed")
return
if not quiet:
show_diff(before_editing, after_editing)
if (apply_filename == "-" or replace_filename == "-") and not force:
click.echo("Use --force option to apply changes")
return
if force or click.confirm("Apply these changes?"):
if not dcs.set_config_value(
json.dumps(changed_data), cluster.config.modify_index
):
raise PatroniCtlException(
"Config modification aborted due to concurrent changes"
)
click.echo("Configuration changed")
|
https://github.com/zalando/patroni/issues/491
|
[root@postgres-5-2 ~]# patronictl -c /etc/patroni.yaml edit-config postgres-5
---
+++
@@ -11,4 +11,4 @@
use_pg_rewind: true
use_slots: true
retry_timeout: 10
-ttl: 30
+ttl: 31
Apply these changes? [y/N]: y
2017-07-28 23:27:53,965 - ERROR - Unhandled exception in connection loop
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python3.4/threading.py", line 911, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.4/threading.py", line 859, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 471, in zk_loop
if retry(self._connect_loop, retry) is STOP_CONNECTING:
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 488, in _connect_loop
status = self._connect_attempt(host, port, retry)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 541, in _connect_attempt
self._send_request(read_timeout, connect_timeout)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 445, in _send_request
self._submit(request, connect_timeout, xid)
File "/usr/lib/python3.4/site-packages/kazoo/protocol/connection.py", line 279, in _submit
b += request.serialize()
File "/usr/lib/python3.4/site-packages/kazoo/protocol/serialization.py", line 195, in serialize
b.extend(int_struct.pack(self.version))
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
2017-07-28 23:27:54,328 - ERROR - set_config_value
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/patroni/dcs/zookeeper.py", line 230, in set_config_value
self._client.retry(self._client.set, self.config_path, value.encode('utf-8'), version=index or -1)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 273, in _retry
return self._retry.copy()(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/retry.py", line 123, in __call__
return func(*args, **kwargs)
File "/usr/lib/python3.4/site-packages/kazoo/client.py", line 1219, in set
return self.set_async(path, value, version).get()
File "/usr/lib/python3.4/site-packages/kazoo/handlers/utils.py", line 72, in get
raise self._exception
kazoo.exceptions.ConnectionClosedError: Connection has been closed
Error: Config modification aborted due to concurrent changes
|
kazoo.exceptions.ConnectionClosedError
|
def is_failover_possible(self, cluster, leader, candidate):
if leader and (not cluster.leader or cluster.leader.name != leader):
return "leader name does not match"
if candidate:
members = [m for m in cluster.members if m.name == candidate]
if not members:
return "candidate does not exists"
else:
members = [
m for m in cluster.members if m.name != cluster.leader.name and m.api_url
]
if not members:
return (
"failover is not possible: cluster does not have members except leader"
)
for st in self.server.patroni.ha.fetch_nodes_statuses(members):
if st.failover_limitation() is None:
return None
return "failover is not possible: no good candidates have been found"
|
def is_failover_possible(self, cluster, leader, candidate):
if leader and (not cluster.leader or cluster.leader.name != leader):
return "leader name does not match"
if candidate:
members = [m for m in cluster.members if m.name == candidate]
if not members:
return "candidate does not exists"
else:
members = [
m for m in cluster.members if m.name != cluster.leader.name and m.api_url
]
if not members:
return (
"failover is not possible: cluster does not have members except leader"
)
for _, reachable, _, _, tags in self.server.patroni.ha.fetch_nodes_statuses(
members
):
if reachable and not tags.get("nofailover", False):
return None
return "failover is not possible: no good candidates have been found"
|
https://github.com/zalando/patroni/issues/488
|
Jul 28 12:35:31 postgres-5-2 patroni[1269]: 2017-07-28 12:35:31,258 INFO: received failover request with leader=postgres-5-2 candidate=postgres-5-3 scheduled_at=None
Jul 28 12:35:31 postgres-5-2 patroni[1269]: 2017-07-28 12:35:31,276 INFO: Got response from postgres-5-3 http://postgres-5-3:8008/patroni: b'{"role": "replica", "postmaster_start_time": "2017-07-28 12:31:09.295 UTC", "state": "running", "xlog": {"replayed_timestamp": "2017-07-28 12:31:09.208 UTC", "paused": false, "replayed_location": 369514424, "received_location": 369514424}, "server_version": 90603, "patroni": {"version": "1.3", "scope": "postgres-5"}, "database_system_identifier": "6447546693452231673"}'
Jul 28 12:35:31 postgres-5-2 patroni[1269]: 2017-07-28 12:35:31,367 INFO: Got response from postgres-5-3 http://postgres-5-3:8008/patroni: b'{"role": "replica", "postmaster_start_time": "2017-07-28 12:31:09.295 UTC", "state": "running", "xlog": {"replayed_timestamp": "2017-07-28 12:31:09.208 UTC", "paused": false, "replayed_location": 369514424, "received_location": 369514424}, "server_version": 90603, "patroni": {"version": "1.3", "scope": "postgres-5"}, "database_system_identifier": "6447546693452231673"}'
Jul 28 12:35:34 postgres-5-2 patroni[1269]: Traceback (most recent call last):
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib64/python3.4/socketserver.py", line 617, in process_request_thread
Jul 28 12:35:34 postgres-5-2 patroni[1269]: self.finish_request(request, client_address)
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib64/python3.4/socketserver.py", line 344, in finish_request
Jul 28 12:35:34 postgres-5-2 patroni[1269]: self.RequestHandlerClass(request, client_address, self)
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib64/python3.4/socketserver.py", line 673, in __init__
Jul 28 12:35:34 postgres-5-2 patroni[1269]: self.handle()
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib64/python3.4/http/server.py", line 401, in handle
Jul 28 12:35:34 postgres-5-2 patroni[1269]: self.handle_one_request()
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib64/python3.4/http/server.py", line 389, in handle_one_request
Jul 28 12:35:34 postgres-5-2 patroni[1269]: method()
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib/python3.4/site-packages/patroni/api.py", line 29, in wrapper
Jul 28 12:35:34 postgres-5-2 patroni[1269]: return func(handler)
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib/python3.4/site-packages/patroni/api.py", line 341, in do_POST_failover
Jul 28 12:35:34 postgres-5-2 patroni[1269]: data = self.is_failover_possible(cluster, leader, candidate)
Jul 28 12:35:34 postgres-5-2 patroni[1269]: File "/usr/lib/python3.4/site-packages/patroni/api.py", line 304, in is_failover_possible
Jul 28 12:35:34 postgres-5-2 patroni[1269]: for _, reachable, _, _, tags in self.server.patroni.ha.fetch_nodes_statuses(members):
Jul 28 12:35:34 postgres-5-2 patroni[1269]: ValueError: too many values to unpack (expected 5)
|
ValueError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.