def test_it_should_get_the_saved_scheduled_item(self): self.scriptter.state['scheduled'] = '3d13091cf3f811e4a8edc82a1417f375' ensure( self.scriptter.get_scheduled_item ).called_with().is_( self.schedule.by_id['3d13091cf3f811e4a8edc82a1417f375'] )
def test_find_should_(self): for name in ('find', 'detect'): find = getattr(funk, name) ensure(find).called_with( funk.greater_than(3), [1, 2, 3, 4, 5, 6] ).equals(4)
def test_it_should_get_a_situation_by_relative_address(self): current_situation = self.plot.by_name['foo'].by_name['bar'] ensure( self.plot.get_situation_by_address("baz", current_situation) ).is_( self.plot.by_name['foo'].by_name['baz'] )
def test_it_should_have_fields(self): from nonobvious import entities class MyEntity(entities.Entity): pass ensure(MyEntity).has_attribute('fields')
def test_it_should_log_an_error_if_it_cant_get_a_scheduled_item(self): self.scriptter.state['scheduled'] = 'foo' with mock.patch('scriptter.logger.error') as patched: ensure( self.scriptter.get_scheduled_item ).called_with().is_none() ensure(patched.call_count).equals(1)
def test_add_directive_returns_directive_factory(self): from storyline import factories self.state.add_series('foo') self.state.add_situation('foo') directive = self.state.add_directive('bar') ensure(directive).is_a(factories.DirectiveFactory) ensure(self.state.directive).is_(directive)
def test_should_capture_exceptions(self): def f(arg): raise TypeError() ensure(f).called_with('foo').raises(TypeError) handled = funk.handle_errors(f) ensure(handled).called_with('foo').is_a(TypeError)
def step_impl(context, element, attribute): parsed = et.fromstring(str(context.response.text)) # get elements: elementlist = parsed.findall('.//'+str(get_UwsName(element))) for elem in elementlist: # check if attribute exists in list of attributes: ensure(attribute).is_in(elem.attrib)
def test_it_should_parse_addresses_relative_to_current_situation(self): current_situation = self.plot.by_name['foo'].by_name['baz'] ensure( self.plot.parse_address("bar", current_situation) ).equals( ('foo', 'bar') )
def test_it_should_load_default_options(self): loader = scriptter.ScheduleLoader( DATA / 'schedule_without_defaults.yaml' ) options = loader.options ensure(options).is_a(dict) ensure(options).equals(scriptter.DEFAULTS)
def test_it_should_write_changes_to_state(self): self.loader.state['next'] = 'foo' self.loader.write_state() new_loader = scriptter.StateLoader(self.state_path) ensure(new_loader.state).has_key('next' # noqa ).whose_value.equals('foo')
def test_it_should_parse_directives_with_target_as_anchor_text_when_anchor_text_directive_is_present(self): self.factory.add_directive('anchor text') md_link = self.factory.parse_directive('anchor text', '!') ensure(md_link).equals('[anchor text](anchor+text)') ensure(self.factory.directives).has_length(1)
def test_it_should_execute_its_content(self): from storyline import entities directive = entities.Directive( name = 'foo', content = '{% for arg in args %}{{ arg }} {% endfor %}', ) ensure(directive.execute).called_with({}, 'foo', 'bar', 'baz').equals("foo bar baz ")
def test_switch_should_pick_a_function_based_on_a_predicate(self): switch = funk.switch([ (funk.is_an(int), lambda x: x ** 2), (funk.is_a(str), lambda x: x + x) ]) ensure(switch).called_with(4).equals(16) ensure(switch).called_with('foo').equals('foofoo')
def test_it_should_dump_a_stream_of_documents_to_a_string(self): result = scriptter.yaml_dump_all( [ ['foo'], ['bar'], ] ) ensure(result).equals(self.docs.text())
def test_it_should_wrap_methods_returning_None_with_empty_string_as_return_value(self): from storyline import contexts class ContextDict(contexts.ContextMixin, dict): pass d = ContextDict() ensure(d.clear()).equals('')
def test_it_should_get_the_next_item_after(self): item = self.schedule.by_id['36292ccff3f811e4889bc82a1417f375'] expected = self.schedule.by_id['3d13091cf3f811e4a8edc82a1417f375'] ensure( self.scriptter.get_next_item_after ).called_with( item ).is_(expected)
def test_it_should_have_defaults(self): from nonobvious import fields class MyEntity(dict): foo = fields.Field(default='bar') entity = MyEntity() ensure(entity.foo).equals("bar")
def test_it_should_not_wrap_around_when_repeat_is_False(self): self.schedule.options['repeat'] = False self.schedule.index() # This will honor the new option ensure( self.schedule.next_after_id.__getitem__ ).called_with( '4156347af3f811e4a134c82a1417f375' ).raises(KeyError)
def test_add_directive_returns_directive_and_extends_situation_directives(self): from storyline import factories directive = self.factory.add_directive("foo") ensure(directive).is_a(factories.DirectiveFactory) ensure(directive.name).equals("foo") ensure(directive.situation_name).equals(self.factory.name) ensure(self.factory.directives).has_length(1) ensure(self.factory.directives['foo']).is_(directive)
def test_it_should_get_the_scheduled_run_time_for_the_default_object_when_none_set(self): # noqa utcnaw = dt.datetime(2015, 12, 25, 13, 57) expected = self.schedule.get_timezone().localize( dt.datetime(2015, 12, 26, 8, 0) ) item = self.schedule.items[0] result = self.scriptter.get_scheduled_run_time(item, now=utcnaw) ensure(result).equals(expected)
def test_should_create_around_decorators(self): @funk.around def maybe(func, value): if value is not None: return func(value) ensure(maybe(double)(2)).equals(4) ensure(maybe(double)(None)).is_none()
def test_it_should_be_a_descriptor(self): from nonobvious import fields class MyEntity(dict): foo = fields.Field(key='foo') entity = MyEntity(foo="bar") ensure(entity.foo).equals("bar")
def test_it_should_get_a_template(self): from storyline import templates class MyObject(templates.Renderable): content = "foo bar" obj = MyObject() ensure(obj.template).is_a(jinja2.Template)
def test_it_should_parse_a_series_address_with_a_current_situation(self): current_situation = self.plot.by_name['foo'].by_name['baz'] ensure( self.plot.parse_address("blah", current_situation) ).equals( ('blah', None) )
def test_it_should_render_a_template(self): from storyline import templates class MyObject(templates.Renderable): content = "foo bar {{ what }}" obj = MyObject() ensure(obj.render).called_with({'what': 'baz'}).equals('foo bar baz')
def test_it_should_save_the_next_scheduled_item(self): item = self.schedule.by_id['3d13091cf3f811e4a8edc82a1417f375'] self.scriptter.set_next(item) ensure( self.scriptter.state ).has_key('scheduled').whose_value.equals( # noqa '4156347af3f811e4a134c82a1417f375' )
def step_impl(context, element, values): values = [value.strip() for value in values.split(',')] parsed = et.fromstring(str(context.response.text)) # find all elements, anywhere in the tree elementlist = parsed.findall('.//'+str(get_UwsName(element))) #raise NotImplementedError('%r, %r' % (elementlist, uwselement)) for elem in elementlist: ensure(elem.text).is_in(values)
def test_it_should_save_None_if_no_more_scheduled_items(self): self.schedule.options['repeat'] = False self.schedule.index() # This will honor the new option item = self.schedule.by_id['4156347af3f811e4a134c82a1417f375'] self.scriptter.set_next(item) ensure( self.scriptter.state ).has_key('scheduled').whose_value.is_none() # noqa
def test_filter_should_(self): for name in ('filter', 'select'): filter = getattr(funk, name) ensure( list( filter( funk.greater_than(3), [1, 2, 3, 4, 5, 6])) ).equals([4, 5, 6])
def __init__(self, sock_type: int, sockaddr: str): # Internal only communication. url = urlparse(sockaddr) scheme = url.scheme ensure(scheme).is_in(['ipc', 'inproc', 'tcp']) self.address_out = sockaddr self.sock_connected = False self.sock_type = sock_type self.pid = os.getpid() self._sock_out = None
def proxy(self): """Starts a forwarding proxy between input and output channels Raises: NotConnected: channels were not binded """ if not (self.cin.sock_connected and self.cout.sock_connected): raise NotConnected("channels have not binded nor connected") ensure(self.cin.address_in).is_not_equal_to(self.cout.address_out) zmq.proxy(self.cin.sock_in, self.cout.sock_out) self.close()
def rotate(self, angle, x=None, y=None): if x is None and y is None: self.rotate(angle, self._parse_string_dimension(self.width) / 2, self._parse_string_dimension(self.height) / 2) # height then width quad_shift, quad_dims = get_quad_shift_and_dims(self.width, self.height, angle) figure = type(self)(quad_dims[0], quad_dims[1], self) figure.move(*quad_shift) return figure else: ensure(x).is_numeric() ensure(y).is_numeric() return super(Element, self).rotate(angle, x, y)
def test_it_should_represent_itself_nicely(self): text = textwrap.dedent(""" - foo - bar - baz """) source = utils.get_text_source(text, 'foo', filename='foo.txt') (ensure(repr(source)) .equals("foo.txt, Line 2, Column 2 (index 3): 'foo' ('foo')"))
def convert(self): lfmt = "xml" ifmt = "jpg" res = ensure.ensure(self.directory, ifmt, lfmt) if res == "OK": print("Everything loooks good!") #main.convert(self.directory) else: print(res)
def test_init(self): print("\nTesting Method :" + inspect.stack()[0][3]) ensure(self.tur).is_a(SimpleTuringMachine) ensure(self.tur.tape).is_a(list).of(str) ensure(self.tur.state_table).is_a(dict).of(tuple).to(tuple) # see Turing machine executing 25 iterations (there is no halt state) print('\n'.join(self.tur.simulate(self.tur.state_table, 25)))
def poll(self, poller, exit_condition: SystemEvent, timeout=-1, poll_timeout=50): """polls input socket for data received Note: this method returns as soon as it receives data or halt event is set. Args: poller: normally `motiv.channel.zeromq.Poller`. exit_condition: halt event to set to give back control to caller. timeout: maximum time to wait for a message. poll_timeout: how long to wait for messages on each iteration. Raises: NotConnected: channel was not connected. ValueError: wrong values (e.g. timeout < poll_timeout). TimeoutError: operation timed out. """ if not self.sock_connected: raise NotConnected("channel has not binded nor connected") if poll_timeout > timeout >= 0: raise ValueError(f"timeout({timeout}) can't be" " less than poll_timeout({poll_timeout})") ensure(exit_condition).is_a(SystemEvent) if self.sock_in not in poller: poller.register_channel(self) if timeout >= 0: return self._poll_timeout(poller, exit_condition, timeout, poll_timeout) return self._poll_naive(poller, exit_condition, poll_timeout)
def convert(self): self.progress.grid(row=6, column=1) self.progress.start(5) lfmt = "xml" ifmt = "jpg" res = ensure.ensure(self.directory, ifmt, lfmt) if res == "OK": print("Everything loooks good!") main.update_cat_names(self.directory) main.convert(self.directory) print("Here") self.progressingBar() else: print(res) self.yolo.configure(state="normal")
def get_var(context, variable, value): ensure(getattr(context, variable)).equals(value)
def attr_should_be_n_step_impl(context, attr, n): ensure(getattr(context.item, attr)).equals(n)
def attr_should_be_less_n_step_impl(context, attr, n): ensure(getattr(context.item, attr)).equals(getattr(context, "initial_" + attr) + n)
def response_status_in(context, statuses): ensure(context.response.status_code).is_in( [int(s) for s in statuses.split(',')])
def response_body_contains(context, content): ensure(content).is_in(context.response.content.decode('utf-8'))
def json_should_be(context): ensure(context.response.json()).equals( json.loads(context.data.decode('utf-8')))
def json_at_path_inline(context, jsonpath, value): json_value = json.loads(value) ensure(jpath.get(jsonpath, context.response.json())).equals(json_value)
def get_context_var_json_value(context, variable): ensure(context.template_data[variable]).equals( json.loads(context.data.decode('utf-8')))
def test_stuff(self): ensure(1).equals(1)
def get_var(context, variable, value): #ensure(getattr(context, variable)).equals(value) ensure(context.template_data[variable]).equals(value)
def response_status(context, status): ensure(context.response.status_code).equals(int(status))
def test_it_should_get_the_line(self): (ensure(utils.get_line).called_with( self.text, 5).equals(" baz blah blargh\n"))
def check_header_inline(context, var, value): ensure(context.response.headers[var].encode('ascii')).equals( value.encode('ascii'))
def test_it_should_get_a_blank_str_for_bad_line(self): (ensure(utils.get_line).called_with(self.text, 99).equals(""))
def json_array_len_at_path_inline(context, jsonpath, value): length = int(json.loads(value)) ensure(jpath.get(jsonpath, context.response.json())).has_length(length)
def test_returns_line_and_column_at_start_of_line(self): match = re.search('foo', self.text) start = match.start() (ensure(utils.get_coords_of_str_index).called_with( self.text, start).equals(Pos(start, 3, 0)))
def json_at_path(context, jsonpath): ensure(jpath.get(jsonpath, context.response.json())).equals( json.loads(context.data.decode('utf-8')))
def test_returns_line_and_column_of_midline_text(self): match = re.search('blah', self.text) start = match.start() (ensure(utils.get_coords_of_str_index).called_with( self.text, start).equals(Pos(start, 5, 12)))
def get_context_var_json_value_inline(context, variable, value): ensure(context.template_data[variable]).equals(json.loads(value))
def test_returns_last_line_and_first_column_of_bad_index(self): (ensure(utils.get_coords_of_str_index).called_with( self.text, len(self.text) + 5).equals(Pos(len(self.text), 6, 0)))
def placeat(self, element, x, y): ensure(element).is_an(Element) ensure(x).is_numeric() ensure(y).is_numeric() super(Element, self).__init__(self.width, self.height, self, element.move(x, y))
def test_basic_ensure_statements(self): ensure(range(10)).contains(5) with self.assertRaises(EnsureError): ensure(range(10)).contains(-1) ensure("abc").is_in("abcdef") with self.assertRaises(EnsureError): ensure(range(10)).is_in(-1) ensure("abc").matches("(abc|def)") with self.assertRaises(EnsureError): ensure(range(10)).is_in(-1) x = {x: x for x in range(10)} ok_clauses = ( 'Ensure(x).contains(0)', 'Ensure(x).contains_all_of(range(10))', 'Ensure(x).contains_no(str)', 'Ensure(x).contains_none_of(range(20, 30))', 'Ensure(x).contains_one_of(range(1))', 'Ensure(x).contains_some_of(range(2))', 'Ensure(x).contains_only(range(10))', 'Ensure(x).does_not_contain(-1)', 'Ensure(x).does_not_equal(range(10))', 'Ensure(x).has_attribute("__iter__")', 'Ensure(x).has_length(10).also.is_nonempty()', 'Ensure(x).has_length(length=10, min=9, max=10)', 'Ensure(x).has_length(max=99.9)', 'Ensure(x).is_nonempty().also.has_length(10)', 'Ensure(x).is_a(collections.Mapping)', 'Ensure(x).is_a_dict_of(int).to(int)', 'Ensure(x).is_a(collections.Mapping).of(int).to(int)', 'Ensure(6).is_greater_than(5)', 'Ensure(6).exceeds(5)', 'Ensure(1.1).is_greater_than_or_equal_to(1.1)', 'Ensure(1.1).is_less_than_or_equal_to(1.1)', 'Ensure(1).is_less_than(1.1)', 'Ensure(1).is_positive()', 'Ensure(1.1).is_a_positive(float)', 'Ensure(-1).is_negative()', 'Ensure(-1).is_a_negative(int)', 'Ensure(0).is_nonnegative()', 'Ensure(0).is_a_nonnegative(int)', 'Ensure(1).is_a_positive(int).which.equals(1.0)', 'Ensure((collections.namedtuple("Thing", ["x"]))(x={})).has_attribute("x").which.is_a(dict)', 'Ensure({1:"a"}).has_key(1).whose_value.has_length(1)', 'Ensure({1: "a", 2: "b", 3: "c"}).has_keys((1, 2))', 'Ensure({1: "a", 2: "b", 3: "c"}).has_only_keys((1, 2, 3))', 'Ensure({}).is_empty()', 'Ensure(os.path.join).called_with("a", "b").returns(os.path.join("a", "b"))', 'Ensure(int).called_with("1100101", base=2).returns(101)', 'Ensure.each_of([1,2,3]).is_an(int)', 'Ensure.each_of([lambda x: x, lambda y: y]).called_with(1).returns(1)', 'Ensure(True).is_none_or.is_an(int)', # See https://www.python.org/dev/peps/pep-0285/ (section 6) 'Ensure(None).is_none_or.is_a_negative(int)', 'Ensure(-5).is_none_or.is_a_negative(int)', 'Ensure({"a": "b"}).is_none_or.has_key("a")', 'Ensure("A").satisfies(str.isupper)', 'Ensure("A").satisfies(".isupper")', 'Ensure("ABC").satisfies(str.startswith, "AB")', 'Ensure("ABC").satisfies(".startswith", "AB")', 'Ensure(3).satisfies(lambda x, y: x < y, y=4)') for clause in ok_clauses: print("Testing OK clause", clause) eval(clause) if 'each_of' not in clause: for sub in r'Check\1.otherwise(Exception)', r'Check\1.or_raise(Exception)', r'Check\1.or_call(self.assertTrue, False)': print("Testing OK clause", re.sub(r'^Ensure(.+)', sub, clause)) eval(re.sub(r'^Ensure(.+)', sub, clause)) bad_clauses = ( 'Ensure(x).contains(-1)', 'Ensure(x).has_length(10).also.is_empty()', 'Ensure(x).contains_all_of(range(20))', 'Ensure(x).contains_no(int)', 'Ensure(x).contains_none_of(range(0, 30))', 'Ensure(x).contains_one_of(range(2))', 'Ensure(x).contains_some_of(range(20, 30))', 'Ensure(x).contains_only(range(11))', 'Ensure(x).does_not_contain(1)', 'Ensure(x).does_not_equal(x)', 'Ensure(x).does_not_equal(copy.deepcopy(x))', 'Ensure(x).has_attribute("y")', 'Ensure(x).has_length(1)', 'Ensure(x).has_length(length=1, min=9, max=10)', 'Ensure(x).has_length(min=11)', 'Ensure(x).has_length(max=1.1)', 'Ensure(x).is_a(str)', 'Ensure(x).is_empty()', 'Ensure(6).is_greater_than(7)', 'Ensure(6).exceeds(7)', 'Ensure(1).is_greater_than_or_equal_to(1.1)', 'Ensure(None).is_greater_than_or_equal_to(1.1)', 'Ensure(5).is_less_than_or_equal_to(1)', 'Ensure(1).is_less_than(None)', 'Ensure(0).is_positive()', 'Ensure(1).is_a_positive(float)', 'Ensure(1).is_negative()', 'Ensure(-0).is_a_negative(int)', 'Ensure(-0.1).is_nonnegative()', 'Ensure(None).is_a_nonnegative(int)', 'Ensure({1: "a"}).has_key(1).whose_value.has_length(2)', 'Ensure({1: "a"}).has_keys((1, 2))', 'Ensure({1: "a", 2: "b"}).has_only_keys([1])', 'Ensure({1: "a", 2: "b"}).has_only_keys([1, 2, 3])', 'Ensure([1, 2, 3]).has_only_keys([1, 2, 3])', 'Ensure(os.path.join).called_with("a", "b").returns(None)', 'Ensure(1).is_a_positive(int).which.equals(1.2)', 'Ensure.each_of([lambda x: x, lambda y: y]).called_with(2).returns(1)', 'Ensure(5).is_none_or.is_a_negative(int)', 'Ensure(None).is_a_negative(int)', 'Ensure("a").satisfies(str.isupper)', 'Ensure("a").satisfies(".isupper")', 'Ensure("ABC").satisfies(str.startswith, "Z")', 'Ensure("ABC").satisfies(".startswith", "Z")', 'Ensure(5).satisfies(str.isupper)', 'Ensure(5).satisfies(".isupper")') for clause in bad_clauses: print("Testing bad clause", clause) with self.assertRaises(EnsureError): eval(clause) if 'each_of' not in clause: for sub in r'Check\1.otherwise(Exception)', r'Check\1.or_raise(Exception)', r'Check\1.or_call(self.assertTrue, False)': with self.assertRaises(Exception): print("Testing bad clause", re.sub(r'^Ensure(.+)', sub, clause)) eval(re.sub(r'^Ensure(.+)', sub, clause)) with self.assertRaises(EnsureError): Ensure(x).is_a_dict_of(int).to(str) with self.assertRaises(EnsureError): Ensure(x).is_a_dict_of(str).to(int) with self.assertRaises(EnsureError): Ensure(x).called_with().is_an(int) Ensure(lambda: True).is_callable() Ensure("1.1").is_a_numeric_string() with self.assertRaises(EnsureError): Ensure(b"1").is_a_numeric_string() with self.assertRaises(EnsureError): Ensure("").is_a_numeric_string() with self.assertRaises(EnsureError): Ensure(None).is_a_numeric_string() Ensure(b"1").is_a_numeric_bytestring() Ensure(b"1.1").is_a_numeric_bytestring() with self.assertRaises(EnsureError): Ensure("1").is_a_numeric_bytestring() with self.assertRaises(EnsureError): Ensure(b"").is_a_numeric_bytestring() with self.assertRaises(EnsureError): Ensure(None).is_a_numeric_bytestring() Ensure("1").is_an_integer_string() with self.assertRaises(EnsureError): Ensure("1.1").is_an_integer_string() Ensure(b"1").is_an_integer_bytestring() with self.assertRaises(EnsureError): Ensure(b"1.1").is_an_integer_bytestring() with self.assertRaises(EnsureError): Ensure("1").is_an_integer_bytestring() with self.assertRaises(EnsureError): Ensure(b"").is_an_integer_bytestring() with self.assertRaises(EnsureError): Ensure(None).is_an_integer_bytestring()