本文整理汇总了Python中pytest.raises函数的典型用法代码示例。如果您正苦于以下问题:Python raises函数的具体用法?Python raises怎么用?Python raises使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了raises函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
开发者ID:RRedwards,项目名称:requests,代码行数:7,代码来源:test_requests.py
示例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)
开发者ID:AliyunContainerService,项目名称:docker-py,代码行数:25,代码来源:network_test.py
示例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__)
开发者ID:radhermit,项目名称:snakeoil,代码行数:7,代码来源:test_iterables.py
示例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])
开发者ID:bobjacobsen,项目名称:datascience,代码行数:7,代码来源:test_tables.py
示例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)
开发者ID:bashtage,项目名称:pandas,代码行数:28,代码来源:test_query_eval.py
示例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()
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:30,代码来源:test_partitioned_queues.py
示例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])
开发者ID:bobjacobsen,项目名称:datascience,代码行数:31,代码来源:test_tables.py
示例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
开发者ID:EdgarChen,项目名称:servo,代码行数:7,代码来源:test_capture.py
示例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')
开发者ID:CaptainAL,项目名称:Spyder,代码行数:7,代码来源:test_sql.py
示例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']
开发者ID:CJ-Wright,项目名称:analysisstore,代码行数:7,代码来源:test_conn_pool.py
示例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]
开发者ID:hodduc,项目名称:libearth,代码行数:34,代码来源:schema_test.py
示例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)
开发者ID:danilobellini,项目名称:audiolazy,代码行数:32,代码来源:test_core.py
示例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)
开发者ID:danilobellini,项目名称:audiolazy,代码行数:29,代码来源:test_core.py
示例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)
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:33,代码来源:test_partitioned_queues.py
示例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())
开发者ID:MaxNoe,项目名称:astropy,代码行数:27,代码来源:test_transformations.py
示例16: test_pqueue_by_servicebus_client_iter_messages_with_retrieve_deferred_not_found
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)
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:31,代码来源:test_partitioned_queues.py
示例17: test_setitem_ndarray_1d
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)
开发者ID:cpcloud,项目名称:pandas,代码行数:33,代码来源:test_indexing.py
示例18: test_pqueue_message_receive_and_delete
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
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:35,代码来源:test_partitioned_queues.py
示例19: test_remove
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)
开发者ID:sdvillal,项目名称:whatami,代码行数:29,代码来源:test_registry.py
示例20: test_relabel
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'])
开发者ID:bobjacobsen,项目名称:datascience,代码行数:27,代码来源:test_tables.py
注:本文中的pytest.raises函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论