def test_connection_error(self): """Connecting to an unknown domain should raise a ConnectionError""" with pytest.raises(ConnectionError): requests.get("http://fooobarbangbazbing.httpbin.org") with pytest.raises(ConnectionError): requests.get("http://httpbin.org:1")
def test_circular_cone_flat(): """Conebeam geometry with circular acquisition and a flat 2D detector.""" # Parameters full_angle = np.pi apart = odl.uniform_partition(0, full_angle, 10) dpart = odl.uniform_partition([0, 0], [1, 1], [10, 10]) src_rad = 10 det_rad = 5 with pytest.raises(TypeError): odl.tomo.CircularConeFlatGeometry([0, 1], dpart, src_rad, det_rad) with pytest.raises(TypeError): odl.tomo.CircularConeFlatGeometry(apart, [0, 1], src_rad, det_rad) with pytest.raises(ValueError): odl.tomo.CircularConeFlatGeometry(apart, dpart, -1, det_rad) with pytest.raises(ValueError): odl.tomo.CircularConeFlatGeometry(apart, dpart, src_rad, -1) # Initialize geom = odl.tomo.CircularConeFlatGeometry(apart, dpart, src_rad, det_rad) assert all_almost_equal(geom.angles, apart.points().ravel()) with pytest.raises(ValueError): geom.det_refpoint(2 * full_angle) assert geom.ndim == 3 assert np.linalg.norm(geom.det_refpoint(0)) == det_rad assert np.linalg.norm(geom.src_position(np.pi)) == src_rad assert isinstance(geom.detector, odl.tomo.Flat2dDetector) # check str and repr work without crashing and return something assert str(geom) assert repr(geom)
def test_check_config(tmpdir, registry): test_path = str(tmpdir / "test.json") with open(test_path, "w+", encoding="utf-8") as f: f.write("") with pytest.raises(ApplianceError): Appliance(registry, "jkhj") with pytest.raises(ApplianceError): Appliance(registry, test_path) with open(test_path, "w+", encoding="utf-8") as f: f.write("{}") with pytest.raises(ApplianceError): Appliance(registry, test_path) with pytest.raises(ApplianceError): with open(test_path, "w+", encoding="utf-8") as f: f.write('{"registry_version": 42}') Appliance(registry, test_path) Appliance(registry, "tests/registry/appliances/microcore-linux.json")
def test_parse_provides_useful_errors(): with raises(LanguageError) as excinfo: parse("""{""") assert ( u'Syntax Error GraphQL (1:2) Expected Name, found EOF\n' u'\n' u'1: {\n' u' ^\n' u'' ) == excinfo.value.message assert excinfo.value.positions == [1] assert excinfo.value.locations == [SourceLocation(line=1, column=2)] with raises(LanguageError) as excinfo: parse("""{ ...MissingOn } fragment MissingOn Type """) assert 'Syntax Error GraphQL (2:20) Expected "on", found Name "Type"' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('{ field: {} }') assert 'Syntax Error GraphQL (1:10) Expected Name, found {' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('notanoperation Foo { field }') assert 'Syntax Error GraphQL (1:1) Unexpected Name "notanoperation"' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('...') assert 'Syntax Error GraphQL (1:1) Unexpected ...' in str(excinfo.value)
def test_connect_and_disconnect_container(self): net_name, net_id = self.create_network() container = self.client.create_container('busybox', 'top') self.tmp_containers.append(container) self.client.start(container) network_data = self.client.inspect_network(net_id) self.assertFalse(network_data.get('Containers')) self.client.connect_container_to_network(container, net_id) network_data = self.client.inspect_network(net_id) self.assertEqual( list(network_data['Containers'].keys()), [container['Id']]) with pytest.raises(docker.errors.APIError): self.client.connect_container_to_network(container, net_id) self.client.disconnect_container_from_network(container, net_id) network_data = self.client.inspect_network(net_id) self.assertFalse(network_data.get('Containers')) with pytest.raises(docker.errors.APIError): self.client.disconnect_container_from_network(container, net_id)
def test_save_store_fs_change_pootle_path_or_store(en_tutorial_po_fs_store): """You cant change a pootle_path if a store is associated unless you also remove the store association - and vice versa """ fs_store = en_tutorial_po_fs_store store = fs_store.store other_path = "/en/tutorial/other.po" fs_store.pootle_path = other_path with pytest.raises(ValidationError): fs_store.save() fs_store.store = None fs_store.save() assert fs_store.store is None assert fs_store.pootle_path == other_path fs_store.store = store with pytest.raises(ValidationError): fs_store.save() fs_store.pootle_path = store.pootle_path fs_store.save() assert fs_store.store == store assert fs_store.pootle_path == store.pootle_path
def test_getitem(self): c = caching_iter(range(20)) assert c[-1] == 19 with pytest.raises(IndexError): operator.getitem(c, -21) with pytest.raises(IndexError): operator.getitem(c, 21)
def test_nested_scope(self): from pandas.core.computation.ops import UndefinedVariableError engine = self.engine parser = self.parser # smoke test x = 1 # noqa result = pd.eval('x + 1', engine=engine, parser=parser) assert result == 2 df = DataFrame(np.random.randn(5, 3)) df2 = DataFrame(np.random.randn(5, 3)) # don't have the pandas parser with pytest.raises(SyntaxError): df.query('(@df>0) & (@df2>0)', engine=engine, parser=parser) with pytest.raises(UndefinedVariableError): df.query('(df>0) & (df2>0)', engine=engine, parser=parser) expected = df[(df > 0) & (df2 > 0)] result = pd.eval('df[(df > 0) & (df2 > 0)]', engine=engine, parser=parser) assert_frame_equal(expected, result) expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)] result = pd.eval('df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)]', engine=engine, parser=parser) assert_frame_equal(expected, result)
def test_relabel(): table = Table([(1, 2, 3), (12345, 123, 5123)], ['points', 'id']) table.relabel('id', 'todo') assert_equal(table, """ points | todo 1 | 12345 2 | 123 3 | 5123 """) table.relabel(1, 'yolo') assert_equal(table, """ points | yolo 1 | 12345 2 | 123 3 | 5123 """) table.relabel(['points', 'yolo'], ['red', 'blue']) assert_equal(table, """ red | blue 1 | 12345 2 | 123 3 | 5123 """) with(pytest.raises(ValueError)): table.relabel(['red', 'blue'], ['magenta', 'cyan', 'yellow']) with(pytest.raises(ValueError)): table.relabel(['red', 'green'], ['magenta', 'yellow'])
def test_sample_weights_ne1(table): """Tests that a series of weights with total != 1 is not accepted""" with pytest.raises(ValueError): table.sample(table.num_rows, weights=[1/4, 1/4, 1/4, 1/6]) with pytest.raises(ValueError): table.sample(table.num_rows, weights=[1/4, 1/4, 1/4, 1/2])
def test_pqueue_message_receive_and_delete(live_servicebus_config, partitioned_queue): client = ServiceBusClient( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key'], debug=True) queue_client = client.get_queue(partitioned_queue) with queue_client.get_sender() as sender: message = Message("Receive and delete test") sender.send(message) with queue_client.get_receiver(mode=ReceiveSettleMode.ReceiveAndDelete) as receiver: messages = receiver.fetch_next(timeout=10) assert len(messages) == 1 received = messages[0] print_message(received) with pytest.raises(MessageAlreadySettled): received.complete() with pytest.raises(MessageAlreadySettled): received.abandon() with pytest.raises(MessageAlreadySettled): received.defer() with pytest.raises(MessageAlreadySettled): received.dead_letter() with pytest.raises(MessageAlreadySettled): received.renew_lock() time.sleep(30) with queue_client.get_receiver() as receiver: messages = receiver.fetch_next(timeout=10) for m in messages: print_message(m) assert len(messages) == 0
def test_with_column(table): column_1 = [10, 20, 30, 40] column_2 = 'hello' table2 = table.with_column('new_col1', column_1) table3 = table2.with_column('new_col2', column_2) assert_equal(table, """ letter | count | points a | 9 | 1 b | 3 | 2 c | 3 | 2 z | 1 | 10 """) assert_equal(table2, """ letter | count | points | new_col1 a | 9 | 1 | 10 b | 3 | 2 | 20 c | 3 | 2 | 30 z | 1 | 10 | 40 """) assert_equal(table3, """ letter | count | points | new_col1 | new_col2 a | 9 | 1 | 10 | hello b | 3 | 2 | 20 | hello c | 3 | 2 | 30 | hello z | 1 | 10 | 40 | hello """) with(pytest.raises(ValueError)): table.append_column('bad_col', [1, 2]) with(pytest.raises(ValueError)): table.append_column(0, [1, 2, 3, 4])
def test_pqueue_by_servicebus_client_iter_messages_with_retrieve_deferred_not_found(live_servicebus_config, partitioned_queue): client = ServiceBusClient( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key'], debug=True) queue_client = client.get_queue(partitioned_queue) deferred_messages = [] with queue_client.get_receiver(idle_timeout=5, mode=ReceiveSettleMode.PeekLock) as receiver: with queue_client.get_sender() as sender: for i in range(3): message = Message("Deferred message no. {}".format(i)) message.partition_key = "MyPartitionKey" sender.send(message) count = 0 for message in receiver: deferred_messages.append(message.sequence_number) print_message(message) count += 1 message.defer() assert count == 3 with pytest.raises(ServiceBusError): deferred = queue_client.receive_deferred_messages([3, 4], mode=ReceiveSettleMode.PeekLock) with pytest.raises(ServiceBusError): deferred = queue_client.receive_deferred_messages([5, 6, 7], mode=ReceiveSettleMode.PeekLock)
def test_pqueue_message_expiry(live_servicebus_config, partitioned_queue): client = ServiceBusClient( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key'], debug=True) import uuid queue_client = client.get_queue(partitioned_queue) with queue_client.get_sender() as sender: content = str(uuid.uuid4()) message = Message(content) sender.send(message) with queue_client.get_receiver() as receiver: messages = receiver.fetch_next(timeout=10) assert len(messages) == 1 time.sleep(30) assert messages[0].expired with pytest.raises(MessageLockExpired): messages[0].complete() with pytest.raises(MessageLockExpired): messages[0].renew_lock() with queue_client.get_receiver() as receiver: messages = receiver.fetch_next(timeout=30) assert len(messages) == 1 print_message(messages[0]) assert messages[0].header.delivery_count > 0 messages[0].complete()
def test_pqueue_by_servicebus_client_iter_messages_simple(live_servicebus_config, partitioned_queue): client = ServiceBusClient( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key'], debug=True) queue_client = client.get_queue(partitioned_queue) with queue_client.get_receiver(idle_timeout=5, mode=ReceiveSettleMode.PeekLock) as receiver: with queue_client.get_sender() as sender: for i in range(10): message = Message("Iter message no. {}".format(i)) sender.send(message) count = 0 for message in receiver: print_message(message) message.complete() with pytest.raises(MessageAlreadySettled): message.complete() with pytest.raises(MessageAlreadySettled): message.renew_lock() count += 1 with pytest.raises(InvalidHandlerState): next(receiver) assert count == 10
def test_pqueue_by_servicebus_client_iter_messages_with_retrieve_deferred_receiver_deletemode(live_servicebus_config, partitioned_queue): client = ServiceBusClient( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key'], debug=True) queue_client = client.get_queue(partitioned_queue) deferred_messages = [] messages = [Message("Deferred message no. {}".format(i)) for i in range(10)] for m in messages: m.partition_key = "MyPartitionKey" results = queue_client.send(messages) assert all(result[0] for result in results) count = 0 receiver = queue_client.get_receiver(idle_timeout=5) for message in receiver: deferred_messages.append(message.sequence_number) print_message(message) count += 1 message.defer() assert count == 10 with queue_client.get_receiver(idle_timeout=5) as receiver: deferred = receiver.receive_deferred_messages(deferred_messages, mode=ReceiveSettleMode.ReceiveAndDelete) assert len(deferred) == 10 for message in deferred: assert isinstance(message, DeferredMessage) with pytest.raises(MessageAlreadySettled): message.complete() with pytest.raises(ServiceBusError): deferred = receiver.receive_deferred_messages(deferred_messages)
def test_UnitConverter_nodistance(): mywcs = WCS(hdr) convert = UnitConverter(mywcs) assert convert.ang_size.value == np.abs(hdr['CDELT2']) assert convert.ang_size.unit == mywcs.wcs.cunit[0] twopix_ang = np.abs(hdr['CDELT2']) * 2 * u.deg assert convert.to_pixel(twopix_ang).value == 2. assert convert.to_pixel_area(twopix_ang**2) == 4 * u.pix**2 assert convert.from_pixel(2 * u.pix, u.deg) == twopix_ang assert convert.to_angular(2 * u.pix, u.deg) == twopix_ang # Round trip assert convert.to_pixel(convert.from_pixel(2 * u.pix, u.deg)) == 2 * u.pix assert convert.to_pixel(convert.to_angular(2 * u.pix, u.deg)) == 2 * u.pix assert convert.from_pixel(convert.to_pixel(twopix_ang), u.deg) == twopix_ang assert convert.to_angular(convert.to_pixel(twopix_ang), u.deg) == twopix_ang # Physical conversions should fail with pytest.raises(AttributeError): convert.from_pixel(2 * u.pix, u.pc) with pytest.raises(AttributeError): assert convert.to_physical(2 * u.pix, u.pc)
def test_fetch_file(url, tmpdir): """Test URL retrieval.""" tempdir = str(tmpdir) archive_name = op.join(tempdir, "download_test") with catch_logging() as log: _fetch_file(url, archive_name, timeout=30., verbose='debug') log = log.getvalue() assert 'Resuming at' not in log with open(archive_name, 'rb') as fid: data = fid.read() stop = len(data) // 2 assert 0 < stop < len(data) with open(archive_name + '.part', 'wb') as fid: fid.write(data[:stop]) with catch_logging() as log: _fetch_file(url, archive_name, timeout=30., verbose='debug') log = log.getvalue() assert 'Resuming at %s' % stop in log with pytest.raises(Exception, match='unknown url type'): _fetch_file('NOT_AN_ADDRESS', op.join(tempdir, 'test'), verbose=False) resume_name = op.join(tempdir, "download_resume") # touch file with open(resume_name + '.part', 'w'): os.utime(resume_name + '.part', None) _fetch_file(url, resume_name, resume=True, timeout=30., verbose=False) with pytest.raises(ValueError, match='Bad hash value'): _fetch_file(url, archive_name, hash_='a', verbose=False) with pytest.raises(RuntimeError, match='Hash mismatch'): _fetch_file(url, archive_name, hash_='a' * 32, verbose=False)
def test_remove(registry, what2nick): what, whatid, nick = what2nick # remove by nickname assert what == registry.register(what, nick) assert registry.list() == [(nick, whatid)] registry.remove(nickname=nick) assert registry.list() == [] # remove by whatid assert what == registry.register(what, nick) assert registry.list() == [(nick, whatid)] registry.remove(what=what) assert registry.list() == [] # remove by both need to match the entry assert what == registry.register(what, nick) assert registry.list() == [(nick, whatid)] with pytest.raises(ValueError): registry.remove(what=what, nickname='NO') assert registry.list() == [(nick, whatid)] with pytest.raises(ValueError): registry.remove(what='NO()', nickname=nick) # remove does not accept None parameters with pytest.raises(ValueError) as excinfo: registry.remove() assert 'at least one of nickname or what must be provided' == str(excinfo.value)
def test_terminal_functions(terminal): terminal.flash() assert curses.flash.called terminal.getch() assert terminal.stdscr.getch.called with pytest.raises(RuntimeError): with terminal.no_delay(): raise RuntimeError() terminal.stdscr.nodelay.assert_any_call(0) terminal.stdscr.nodelay.assert_any_call(1) curses.endwin.reset_mock() curses.doupdate.reset_mock() with terminal.suspend(): pass assert curses.endwin.called assert curses.doupdate.called curses.endwin.reset_mock() curses.doupdate.reset_mock() with pytest.raises(RuntimeError): with terminal.suspend(): raise RuntimeError() assert curses.endwin.called assert curses.doupdate.called terminal.addch(terminal.stdscr, 3, 5, 'ch', 'attr') terminal.stdscr.addch.assert_called_with(3, 5, 'ch', 'attr')
def test_vel_transformation_obstime_err(): # TODO: replace after a final decision on PR #6280 from astropy.coordinates.sites import get_builtin_sites diff = r.CartesianDifferential([.1, .2, .3]*u.km/u.s) rep = r.CartesianRepresentation([1, 2, 3]*u.au, differentials=diff) loc = get_builtin_sites()['example_site'] aaf = AltAz(obstime='J2010', location=loc) aaf2 = AltAz(obstime=aaf.obstime + 3*u.day, location=loc) aaf3 = AltAz(obstime=aaf.obstime + np.arange(3)*u.day, location=loc) aaf4 = AltAz(obstime=aaf.obstime, location=loc) aa = aaf.realize_frame(rep) with pytest.raises(NotImplementedError) as exc: aa.transform_to(aaf2) assert 'cannot transform' in exc.value.args[0] with pytest.raises(NotImplementedError) as exc: aa.transform_to(aaf3) assert 'cannot transform' in exc.value.args[0] aa.transform_to(aaf4) aa.transform_to(ICRS())
def test_setitem_ndarray_1d(self): # GH5508 # len of indexer vs length of the 1d ndarray df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) # invalid def f(): df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) pytest.raises(ValueError, f) # valid df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) result = df.loc[df.index[2:6], 'bar'] expected = Series([2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name='bar') tm.assert_series_equal(result, expected) # dtype getting changed? df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) def f(): df[2:5] = np.arange(1, 4) * 1j pytest.raises(ValueError, f)
def test_cluster(some_clusters): """Test base functionality of :class:`~.db.Cluster`.""" # Test empty cluster attributes. cluster = Cluster() assert cluster.size == 0 assert cluster.size_urls == 0 assert cluster.frequency == 0 with pytest.raises(ValueError) as excinfo: cluster.span assert 'No urls' in str(excinfo.value) assert cluster.urls == [] # Test clusters from database. with session_scope() as session: assert session.query(Cluster).count() == 5 assert session.query(Cluster.sid).all() == \ [(i,) for i in some_clusters] assert session.query(Cluster).filter_by(sid=0).one().size == 0 assert session.query(Cluster).filter_by(sid=0).one().size_urls == 0 assert session.query(Cluster).filter_by(sid=0).one().frequency == 0 with pytest.raises(ValueError) as excinfo: session.query(Cluster).filter_by(sid=0).one().span assert 'No urls' in str(excinfo.value) assert session.query(Cluster).filter_by(sid=0).one().urls == [] assert session.query(Cluster).get(1).format_copy() == \ '1\t0\tFalse\ttest'
def test_client_badconf(self): config = {'host': 'localhost'} pytest.raises(KeyError, AnalysisClient, config) config['port'] = TESTING_CONFIG['port'] conn = AnalysisClient(config) conn.host == TESTING_CONFIG['host'] conn.port == TESTING_CONFIG['port']
def test_normal_function(self): i = [iter(range(100)) for x in range(3)] e = expandable_chain() e.extend(i) assert list(e) == list(range(100))*3 for x in i + [e]: pytest.raises(StopIteration, x.__next__)
def test_element_coerce_from(fx_test_doc): doc, _ = fx_test_doc doc.title_attr = 'coerce test' assert isinstance(doc.title_attr, TextElement) assert doc.title_attr.value == 'coerce test' with raises(TypeError): doc.title_attr = 123 doc.multi_attr = [TextElement(value='a'), 'b'] for e in doc.multi_attr: assert isinstance(e, TextElement) assert doc.multi_attr[0].value == 'a' assert doc.multi_attr[1].value == 'b' with raises(TypeError): doc.multi_attr = [TextElement(value='a'), 'b', 3] number = len(doc.multi_attr) doc.multi_attr.append('coerce test') assert len(doc.multi_attr) == number + 1 for e in doc.multi_attr: assert isinstance(e, TextElement) assert doc.multi_attr[-1].value == 'coerce test' with raises(TypeError): doc.multi_attr.append(123) doc.multi_attr[0] = 'coerce test' assert isinstance(doc.multi_attr[0], TextElement) assert doc.multi_attr[0].value == 'coerce test' with raises(TypeError): doc.multi_attr[1] = 123 doc.multi_attr[1:] = ['slice', 'test'] for e in doc.multi_attr: assert isinstance(e, TextElement) assert doc.multi_attr[1].value == 'slice' assert doc.multi_attr[2].value == 'test' with raises(TypeError): doc.multi_attr[1:] = ['slice test', 123]
def test_create_index_fails(self, sql): with pytest.raises(KeyError): create_index(sql, 'z', name='zidx') with pytest.raises(ValueError): create_index(sql, 'x') with pytest.raises(ValueError): create_index(sql, 'z')
def test_key2keys_value2keys(self): md = MultiKeyDict() md[1] = 7 md[2] = 7 md[3] = -4 md[4] = -4 md[-4] = 1 assert md.key2keys(1) == md.key2keys(2) == (1, 2) == md.value2keys(7) assert md.key2keys(3) == md.key2keys(4) == (3, 4) == md.value2keys(-4) assert md.key2keys(-4) == (-4,) == md.value2keys(1) assert len(md) == 3 del md[2] assert md.key2keys(1) == (1,) == md.value2keys(7) assert md.key2keys(3) == md.key2keys(4) == (3, 4) == md.value2keys(-4) assert md.key2keys(-4) == (-4,) == md.value2keys(1) assert len(md) == 3 with pytest.raises(KeyError): md.key2keys(2) del md[1] assert md.value2keys(7) == tuple() assert md.key2keys(3) == md.key2keys(4) == (3, 4) == md.value2keys(-4) assert md.key2keys(-4) == (-4,) == md.value2keys(1) assert len(md) == 2 with pytest.raises(KeyError): md.key2keys(1) with pytest.raises(KeyError): md.key2keys(2)
def test_strategy_attribute_replaced(self): sd = StrategyDict("sd") sd.strategy("add", "+", keep_name=True)(operator.add) sd.strategy("mul", "*", keep_name=True)(operator.mul) sd.strategy("sub", "-", keep_name=True)(operator.sub) # Replaces the strategy attribute, but keeps the strategy there sd.sub = 14 assert set(sd.keys()) == {("add", "+"), ("mul", "*"), ("sub", "-",)} assert sd["sub"](5, 4) == 1 assert sd.sub == 14 # Removes the strategy with replaced attribute, keeping the attribute del sd["sub"] # Removes the strategy assert sd.sub == 14 # Still there assert set(sd.keys()) == {("add", "+"), ("mul", "*"), ("-",)} # Removes the replaced attribute, keeping the strategy sd.add = None assert sd.add is None assert sd["add"](3, 7) == 10 del sd.add # Removes the attribute assert sd.add(4, 7) == 11 == sd["add"](4, 7) assert set(sd.keys()) == {("add", "+"), ("mul", "*"), ("-",)} # Removes the strategy whose attribute had been replaced del sd.add # Removes the strategy assert set(sd.keys()) == {("+",), ("mul", "*"), ("-",)} with pytest.raises(KeyError): sd["add"](5, 4) with pytest.raises(AttributeError): sd.add(5, 4)
def test_reset_twice_error(self): with self.getcapture() as cap: print("hello") out, err = cap.readouterr() pytest.raises(ValueError, cap.stop_capturing) assert out == "hello\n" assert not err
def test_cookies_are_readonly(session): with pytest.raises(AttributeError): session.cookies = 123
def test_create_input_feeder_with_config_inputs_not_in_network_inputs_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([{'name': 'data2', 'type': 'INPUT', 'value': '.'}], {'data': (1, 3, 10, 10)})
def test_transpose_non_default_axes(self): for obj in self.objs: with pytest.raises(ValueError, match=self.errmsg): obj.transpose(1) with pytest.raises(ValueError, match=self.errmsg): obj.transpose(axes=1)
def test_case_sensitivity(self, rf: RequestFactory): request = rf.get("/fake-url/") request.user = UserFactory(username="******") with pytest.raises(Http404): user_detail_view(request, username="******")
def test_wrong_delimiter(): """Test that an error is raised if a wrong delimiter is supplied.""" with pytest.raises(TypeError): Clumper.read_csv("tests/data/monopoly.csv", delimiter=", ")
def test_to_dict(): with pytest.raises(ValueError): to_dict([None, None], id)
def test_create_input_feeder_not_all_non_constant_inputs_in_config_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder( [{'name': '0', 'type': 'INPUT', 'value': '.'}], {'0': (1, 3, 10, 10), '1': (1, 3, 10, 10)} )
def test_create_input_feeder_with_only_image_info_in_network_inputs_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([{'name': 'info', 'type': 'IMAGE_INFO'}], {'info': (1, 3)})
def test_set_invalid_input_precision_for_image_info_input_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([{'name': 'im_info', 'type': 'IMAGE_INFO', 'precision': 'U2'}], {'input': (1, 3, 10, 10), 'im_info': (1, 3)})
def test_create_input_feeder_with_config_inputs_and_empty_network_inputs_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([{'name': 'const_data', 'type': 'CONST_INPUT', 'value': '[1, 1, 1, 1]'}], {})
def test_create_input_feeder_without_inputs_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([], {})
def test_set_invalid_input_precision_for_non_constant_input_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder([{'name': 'input', 'type': 'INPUT', 'precision': 'U2'}], {'input': (1, 3, 10, 10)})
def test_fill_non_constant_input_with_specific_mapping_not_match_raise_config_error(self): input_feeder = InputFeeder([{'name': 'input', 'type': 'INPUT', 'value': '1.'}], {'input': InputInfo_test(shape=(1, 3, 10, 10))}) with pytest.raises(ConfigError): input_feeder.fill_non_constant_inputs([DataRepresentation(np.zeros((10, 10, 3)), identifier='0')])
def test_set_invalid_input_precision_for_constant_input_raise_config_error(self): with pytest.raises(ConfigError): InputFeeder( [{'name': 'input_u8', 'type': 'CONST_INPUT', 'value': [1, 2, 3], 'precision': 'U2'}], {'input': (1, 3, 10, 10), 'input_u8': (3,)})
def test_non_found(mixer, user): """Shipping some non-shippable stuf ergo stuff without a registered shipment""" with pytest.raises(factory.ShipmentAlgorithmNotFound): factory.get(user)
def test_create_input_feeder_with_several_precision_info_in_wrong_format_raises_config_error(self): with pytest.raises(ConfigError): InputFeeder( [{'name': 'const_data', 'type': 'CONST_INPUT', 'value': [[1, 2, 3, 4]], 'precision': 'FP32'}], {'data': (1, 3, 10, 10), 'const_data': (1, 4)}, input_precisions_list=['U8', 'FP16'] )
def test_is_valid_block_bad_block_hash(last_block, block): block.hash = '000000000000000000000bbbabc' with pytest.raises(Exception, match='block hash must be correct'): Block.is_valid_block(last_block, block)
def test_load_missing_file(self, biosequence_data_set): """Check the error when trying to load missing file.""" pattern = r"Failed while loading data from data set BioSequenceDataSet\(.*\)" with pytest.raises(DataSetError, match=pattern): biosequence_data_set.load()
def test_is_valid_block_bad_last_hash(last_block, block): block.last_hash = 'evil_last_hash' with pytest.raises(Exception, match='last_hash must be correct'): Block.is_valid_block(last_block, block)
def test_is_valid_block_bad_proof_of_work(last_block, block): block.hash = 'fff' with pytest.raises(Exception, match='proof of work requirement was not met'): Block.is_valid_block(last_block, block)
async def test_custom_confirmation_message(gql): """Test custom confirmation message.""" print("Establish WebSocket GraphQL connections with a custom confirmation message.") expected_data = uuid.uuid4().hex expected_error = RuntimeError(uuid.uuid4().hex) client = gql( mutation=Mutation, subscription=Subscription, consumer_attrs={ "strict_ordering": True, "confirm_subscriptions": True, "subscription_confirmation_message": { "data": expected_data, "errors": [expected_error], }, }, ) await client.connect_and_init() print("Subscribe & check there is a subscription confirmation message.") sub_op_id = await client.send( msg_type="start", payload={ "query": "subscription op_name { on_trigger { is_ok } }", "operationName": "op_name", }, ) with pytest.raises(channels_graphql_ws.GraphqlWsResponseError) as error: await client.receive(assert_id=sub_op_id, assert_type="data") expected_errors = [ {"message": f"{type(expected_error).__name__}: {expected_error}"} ] assert error.errors == expected_errors, "Wrong confirmation errors received!" assert error.response == { "data": expected_data, "errors": expected_errors, }, "Wrong subscription confirmation message received!" print("Trigger the subscription.") mut_op_id = await client.send( msg_type="start", payload={ "query": """mutation op_name { trigger { is_ok } }""", "operationName": "op_name", }, ) await client.receive(assert_id=mut_op_id, assert_type="data") await client.receive(assert_id=mut_op_id, assert_type="complete") print("Check that subscription notification received.") resp = await client.receive(assert_id=sub_op_id, assert_type="data") assert resp["data"]["on_trigger"]["is_ok"] is True await client.assert_no_messages( "Unexpected message received at the end of the test!" ) await client.finalize()
def test_float_tensor_and_list_add(): x = Tensor(np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], dtype=np.float32)) y = [1, 2, 3] with pytest.raises(TypeError) as er: ret = x + y assert "For 'Add', the 1th input is a not support implicit conversion type: list" in str(er.value)
def test_numpy_transpose(self): for obj in self.objs: tm.assert_equal(np.transpose(obj), obj) with pytest.raises(ValueError, match=self.errmsg): np.transpose(obj, axes=1)
def test_request_closed_session(session): session.close() with pytest.raises(RuntimeError): yield from session.request('get', '/')
def test_util(): # coverage for some leftover functions in diofant.geometry.util assert intersection(Point(0, 0)) == [] pytest.raises(ValueError, lambda: intersection(Point(0, 0), 3)) pytest.raises(ValueError, lambda: convex_hull(Point(0, 0), 3))
def test_type_error(self): item = set() with pytest.raises(ValueError): boe_db.boe_diary_entry_query(item)
def test_polygon(): a, b, c = Point(0, 0), Point(2, 0), Point(3, 3) t = Triangle(a, b, c) assert Polygon(a) == a assert Polygon(a, 1, 1, n=4) == RegularPolygon(a, 1, 4, 1) assert Polygon(a, Point(1, 0), b, c) == t assert Polygon(Point(1, 0), b, c, a) == t assert Polygon(b, c, a, Point(1, 0)) == t # 2 "remove folded" tests assert Polygon(a, Point(3, 0), b, c) == t assert Polygon(a, b, Point(3, -1), b, c) == t pytest.raises(GeometryError, lambda: Polygon((0, 0), (1, 0), (0, 1), (1, 1))) # remove multiple collinear points assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15), Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15), Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15), Point(15, -3), Point(15, 10), Point(15, 15)) == \ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15)) p1 = Polygon( Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5), Point(2, 3), Point(0, 3)) p2 = Polygon( Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3), Point(2, 3), Point(4, 5)) p3 = Polygon( Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4)) p4 = Polygon( Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0)) p5 = Polygon( Point(0, 0), Point(4, 4), Point(0, 4)) p6 = Polygon( Point(-11, 1), Point(-9, 6.6), Point(-4, -3), Point(-8.4, -8.7)) r = Ray(Point(-9, 6.6), Point(-9, 5.5)) # # General polygon # assert p1 == p2 assert len(p1.args) == 6 assert len(p1.sides) == 6 assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8) assert p1.area == 22 assert not p1.is_convex() # ensure convex for both CW and CCW point specification assert p3.is_convex() assert p4.is_convex() dict5 = p5.angles assert dict5[Point(0, 0)] == pi / 4 assert dict5[Point(0, 4)] == pi / 2 assert p5.encloses_point(Point(x, y)) is None assert p5.encloses_point(Point(1, 3)) assert p5.encloses_point(Point(0, 0)) is False assert p5.encloses_point(Point(4, 0)) is False assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False p5.plot_interval('x') == [x, 0, 1] assert p5.distance( Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2) assert p5.distance( Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4 warnings.filterwarnings( "error", message="Polygons may intersect producing erroneous output") pytest.raises(UserWarning, lambda: Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance( Polygon(Point(0, 0), Point(0, 1), Point(1, 1)))) warnings.filterwarnings( "ignore", message="Polygons may intersect producing erroneous output") assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4))) assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5 assert p5 != Point(0, 4) assert Point(0, 1) in p5 assert p5.arbitrary_point('t').subs({Symbol('t', extended_real=True): 0}) == \ Point(0, 0) pytest.raises(ValueError, lambda: Polygon( Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x')) assert p6.intersection(r) == [Point(-9, 33/5), Point(-9, -84/13)] # # Regular polygon # p1 = RegularPolygon(Point(0, 0), 10, 5) p2 = RegularPolygon(Point(0, 0), 5, 5) pytest.raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0, 1), Point(1, 1))) pytest.raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2)) pytest.raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5)) assert p1 != p2 assert p1.interior_angle == 3*pi/5 assert p1.exterior_angle == 2*pi/5 assert p2.apothem == 5*cos(pi/5) assert p2.circumcenter == p1.circumcenter == Point(0, 0) assert p1.circumradius == p1.radius == 10 assert p2.circumcircle == Circle(Point(0, 0), 5) assert p2.incircle == Circle(Point(0, 0), p2.apothem) assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4) p2.spin(pi / 10) dict1 = p2.angles assert dict1[Point(0, 5)] == 3 * pi / 5 assert p1.is_convex() assert p1.rotation == 0 assert p1.encloses_point(Point(0, 0)) assert p1.encloses_point(Point(11, 0)) is False assert p2.encloses_point(Point(0, 4.9)) p1.spin(pi/3) assert p1.rotation == pi/3 assert p1.vertices[0] == Point(5, 5*sqrt(3)) for var in p1.args: if isinstance(var, Point): assert var == Point(0, 0) else: assert var == 5 or var == 10 or var == pi / 3 assert p1 != Point(0, 0) assert p1 != p5 # while spin works in place (notice that rotation is 2pi/3 below) # rotate returns a new object p1_old = p1 assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, 2*pi/3) assert p1 == p1_old assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5)) assert p1.length == 20*sqrt(-sqrt(5)/8 + 5/8) assert p1.scale(2, 2) == \ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation) assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3)) assert repr(p1) == str(p1) # # Angles # angles = p4.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) angles = p3.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) # # Triangle # p1 = Point(0, 0) p2 = Point(5, 0) p3 = Point(0, 5) t1 = Triangle(p1, p2, p3) t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4)))) t3 = Triangle(p1, Point(x1, 0), Point(0, x1)) s1 = t1.sides assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2) pytest.raises(GeometryError, lambda: Triangle(Point(0, 0))) # Basic stuff assert Triangle(p1, p1, p1) == p1 assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3) assert t1.area == Rational(25, 2) assert t1.is_right() assert t2.is_right() is False assert t3.is_right() assert p1 in t1 assert t1.sides[0] in t1 assert Segment((0, 0), (1, 0)) in t1 assert Point(5, 5) not in t2 assert t1.is_convex() assert feq(t1.angles[p1].evalf(), pi.evalf()/2) assert t1.is_equilateral() is False assert t2.is_equilateral() assert t3.is_equilateral() is False assert are_similar(t1, t2) is False assert are_similar(t1, t3) assert are_similar(t2, t3) is False assert t1.is_similar(Point(0, 0)) is False # Bisectors bisectors = t1.bisectors() assert bisectors[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) ic = (250 - 125*sqrt(2)) / 50 assert t1.incenter == Point(ic, ic) # Inradius assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2 assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6 assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1)) # Circumcircle assert t1.circumcircle.center == Point(2.5, 2.5) # Medians + Centroid m = t1.medians assert t1.centroid == Point(Rational(5, 3), Rational(5, 3)) assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2)) assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid] assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) # Perpendicular altitudes = t1.altitudes assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert altitudes[p2] == s1[0] assert altitudes[p3] == s1[2] assert t1.orthocenter == p1 t = Triangle(Point(Rational(100080156402737, 5000000000000), Rational(79782624633431, 500000000000)), Point(Rational(39223884078253, 2000000000000), Rational(156345163124289, 1000000000000)), Point(Rational(31241359188437, 1250000000000), Rational(338338270939941, 1000000000000000))) assert t.orthocenter == \ Point(Rational(-78066086905059984021699779471538701955848721853, 80368430960602242240789074233100000000000000), Rational(20151573611150265741278060334545897615974257, 160736861921204484481578148466200000000000)) # Ensure assert len(intersection(*bisectors.values())) == 1 assert len(intersection(*altitudes.values())) == 1 assert len(intersection(*m.values())) == 1 # Distance p1 = Polygon( Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)) p2 = Polygon( Point(0, Rational(5, 4)), Point(1, Rational(5, 4)), Point(1, Rational(9, 4)), Point(0, Rational(9, 4))) p3 = Polygon( Point(1, 2), Point(2, 2), Point(2, 1)) p4 = Polygon( Point(1, 1), Point(Rational(6, 5), 1), Point(1, Rational(6, 5))) pt1 = Point(half, half) pt2 = Point(1, 1) '''Polygon to Point''' assert p1.distance(pt1) == half assert p1.distance(pt2) == 0 assert p2.distance(pt1) == Rational(3, 4) assert p3.distance(pt2) == sqrt(2)/2 '''Polygon to Polygon''' # p1.distance(p2) emits a warning # First, test the warning warnings.filterwarnings("error", message="Polygons may intersect producing erroneous output") pytest.raises(UserWarning, lambda: p1.distance(p2)) # now test the actual output warnings.filterwarnings("ignore", message="Polygons may intersect producing erroneous output") assert p1.distance(p2) == half/2 assert p1.distance(p3) == sqrt(2)/2 assert p3.distance(p4) == 2*sqrt(2)/5
def test_none(self): with pytest.raises(ValueError): boe_db.boe_diary_entry_query(None)
def test_contamination(): X = [[1, 1], [1, 0]] clf = neighbors.LocalOutlierFactor(contamination=0.6) with pytest.raises(ValueError): clf.fit(X)
def test_ellipse_geom(): p1 = Point(0, 0) p2 = Point(1, 1) p4 = Point(0, 1) e1 = Ellipse(p1, 1, 1) e2 = Ellipse(p2, half, 1) e3 = Ellipse(p1, y1, y1) c1 = Circle(p1, 1) c2 = Circle(p2, 1) c3 = Circle(Point(sqrt(2), sqrt(2)), 1) pytest.raises(ValueError, lambda: Ellipse(Point3D(0, 0, 0), 1, 1)) pytest.raises(ValueError, lambda: e3.arbitrary_point(y1)) assert e1.ambient_dimension == 2 # Test creation with three points cen, rad = Point(3*half, 2), 5*half assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad) pytest.raises( GeometryError, lambda: Circle(Point(0, 0), Point(1, 1), Point(2, 2))) pytest.raises(ValueError, lambda: Ellipse(None, None, None, 1)) pytest.raises(GeometryError, lambda: Circle(Point(0, 0))) # Basic Stuff assert Ellipse(None, 1, 1).center == Point(0, 0) assert e1 == c1 assert e1 != e2 assert p4 in e1 assert p2 not in e2 assert e1.area == pi assert e2.area == pi/2 assert e3.area == pi*y1*abs(y1) assert c1.area == e1.area assert c1.circumference == e1.circumference assert e3.circumference == 2*pi*y1 assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi] assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi] assert Ellipse(None, 1, None, 1).circumference == 2*pi assert c1.minor == 1 assert c1.major == 1 assert c1.hradius == 1 assert c1.vradius == 1 # Private Functions assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1))) assert c1 in e1 assert (Line(p1, p2) in e1) is False # Encloses assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True assert e1.encloses(Line(p1, p2)) is False assert e1.encloses(Ray(p1, p2)) is False assert e1.encloses(e1) is False assert e1.encloses( Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True assert e1.encloses(RegularPolygon(p1, 5, 3)) is False assert e1.encloses(RegularPolygon(p2, 5, 3)) is False # with generic symbols, the hradius is assumed to contain the major radius M = Symbol('M') m = Symbol('m') c = Ellipse(p1, M, m).circumference _x = c.atoms(Dummy).pop() assert c == 4*M*Integral( sqrt((1 - _x**2*(M**2 - m**2)/M**2)/(1 - _x**2)), (_x, 0, 1)) assert e2.arbitrary_point() in e2 # Foci f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0) ef = Ellipse(Point(0, 0), 4, 2) assert ef.foci in [(f1, f2), (f2, f1)] # Tangents v = sqrt(2) / 2 p1_1 = Point(v, v) p1_2 = p2 + Point(half, 0) p1_3 = p2 + Point(0, 1) assert e1.tangent_lines(p4) == c1.tangent_lines(p4) assert e2.tangent_lines(p1_2) == [Line(Point(3/2, 1), Point(3/2, 1/2))] assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(5/4, 2))] assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))] assert c1.tangent_lines(p1) == [] assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1))) assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1))) assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2)))) assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False assert c1.is_tangent(e1) is False assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(77/25, 132/25)), Line(Point(0, 0), Point(33/5, 22/5))] assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \ [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))] assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \ [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))] assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))), Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ] e = Ellipse(Point(0, 0), 2, 1) assert e.normal_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))] assert e.normal_lines(Point(1, 0)) == \ [Line(Point(0, 0), Point(1, 0))] assert e.normal_lines((0, 1)) == \ [Line(Point(0, 0), Point(0, 1))] assert e.normal_lines(Point(1, 1), 2) == [ Line(Point(-51/26, -1/5), Point(-25/26, 17/83)), Line(Point(28/29, -7/8), Point(57/29, -9/2))] # test the failure of Poly.intervals and checks a point on the boundary p = Point(sqrt(3), Rational(1, 2)) assert p in e assert e.normal_lines(p, 2) == [ Line(Point(-341/171, -1/13), Point(-170/171, 5/64)), Line(Point(26/15, -1/2), Point(41/15, -43/26))] # be sure to use the slope that isn't undefined on boundary e = Ellipse((0, 0), 2, 2*sqrt(3)/3) assert e.normal_lines((1, 1), 2) == [ Line(Point(-64/33, -20/71), Point(-31/33, 2/13)), Line(Point(1, -1), Point(2, -4))] # general ellipse fails except under certain conditions e = Ellipse((0, 0), x, 1) assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))] pytest.raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1))) # Properties major = 3 minor = 1 e4 = Ellipse(p2, minor, major) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) # independent of orientation e4 = Ellipse(p2, major, minor) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) # Intersection l1 = Line(Point(1, -5), Point(1, 5)) l2 = Line(Point(-5, -1), Point(5, -1)) l3 = Line(Point(-1, -1), Point(1, 1)) l4 = Line(Point(-10, 0), Point(0, 10)) pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)] assert intersection(e2, l4) == [] assert intersection(c1, Point(1, 0)) == [Point(1, 0)] assert intersection(c1, l1) == [Point(1, 0)] assert intersection(c1, l2) == [Point(0, -1)] assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]] assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)] assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)] assert e1.intersection(l1) == [Point(1, 0)] assert e2.intersection(l4) == [] assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)] assert e1.intersection(Circle(Point(5, 0), 1)) == [] assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)] assert e1.intersection(Ellipse(Point(5, 0), 1, 1,)) == [] assert e1.intersection(Point(2, 0)) == [] assert e1.intersection(e1) == e1 # some special case intersections csmall = Circle(p1, 3) cbig = Circle(p1, 5) cout = Circle(Point(5, 5), 1) # one circle inside of another assert csmall.intersection(cbig) == [] # separate circles assert csmall.intersection(cout) == [] # coincident circles assert csmall.intersection(csmall) == csmall v = sqrt(2) t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0)) points = intersection(t1, c1) assert len(points) == 4 assert Point(0, 1) in points assert Point(0, -1) in points assert Point(v/2, v/2) in points assert Point(v/2, -v/2) in points circ = Circle(Point(0, 0), 5) elip = Ellipse(Point(0, 0), 5, 20) assert intersection(circ, elip) in \ [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]] assert elip.tangent_lines(Point(0, 0)) == [] elip = Ellipse(Point(0, 0), 3, 2) assert elip.tangent_lines(Point(3, 0)) == \ [Line(Point(3, 0), Point(3, -12))] e1 = Ellipse(Point(0, 0), 5, 10) e2 = Ellipse(Point(2, 1), 4, 8) a = 53/17 c = 2*sqrt(3991)/17 ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)] assert e1.intersection(e2) == ans e2 = Ellipse(Point(x, y), 4, 8) c = sqrt(3991) ans = [Point(-c/68 + a, 2*c/17 + a/2), Point(c/68 + a, -2*c/17 + a/2)] assert [p.subs({x: 2, y: 1}) for p in e1.intersection(e2)] == ans # Combinations of above assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0]) e = Ellipse((1, 2), 3, 2) assert e.tangent_lines(Point(10, 0)) == \ [Line(Point(10, 0), Point(1, 0)), Line(Point(10, 0), Point(14/5, 18/5))] # encloses_point e = Ellipse((0, 0), 1, 2) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False e = Ellipse((0, 0), 2, 1) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False assert c1.encloses_point(Point(1, 0)) is False assert c1.encloses_point(Point(0.3, 0.4)) is True assert e.scale(2, 3) == Ellipse((0, 0), 4, 3) assert e.scale(3, 6) == Ellipse((0, 0), 6, 6) assert e.rotate(pi) == e assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1) pytest.raises(NotImplementedError, lambda: e.rotate(pi/3)) # Circle rotation tests (issue sympy/sympy#11743) cir = Circle(Point(1, 0), 1) assert cir.rotate(pi/2) == Circle(Point(0, 1), 1) assert cir.rotate(pi/3) == Circle(Point(Rational(1, 2), sqrt(3)/2), 1) assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1) assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(Rational(1, 2) + sqrt(3)/2, Rational(1, 2) + sqrt(3)/2), 1) # transformations c = Circle((1, 1), 2) assert c.scale(-1) == Circle((-1, 1), 2) assert c.scale(y=-1) == Circle((1, -1), 2) assert c.scale(2) == Ellipse((2, 1), 4, 2)