本文整理汇总了Python中pytest.raises函数的典型用法代码示例。如果您正苦于以下问题:Python raises函数的具体用法?Python raises怎么用?Python raises使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了raises函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_connection_error
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")
示例2: test_connect_and_disconnect_container
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)
示例3: test_normal_function
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__)
示例4: test_sample_weights_ne1
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])
示例5: test_nested_scope
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)
示例6: test_pqueue_message_expiry
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()
示例7: test_with_column
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])
示例8: test_reset_twice_error
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
示例9: test_create_index_fails
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')
示例10: test_client_badconf
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']
示例11: test_element_coerce_from
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]
示例12: test_strategy_attribute_replaced
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)
示例13: test_key2keys_value2keys
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)
示例14: test_pqueue_by_servicebus_client_iter_messages_with_retrieve_deferred_receiver_deletemode
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)
示例15: test_vel_transformation_obstime_err
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())