Testing Class Material

This commit is contained in:
Lisa Schwetlick 2024-08-26 13:54:13 +02:00
commit 05b1f6cdd5
85 changed files with 102796 additions and 0 deletions

View file

@ -0,0 +1,30 @@
>>> from smtplib import SMTP
>>> mock_smtp = Mock(spec=SMTP)
>>> isinstance(mock_smtp, SMTP)
True
>>> mock_smtp.<TAB>
mock_smtp.assert_any_call mock_smtp.attach_mock mock_smtp.call_args
mock_smtp.assert_called_once_with mock_smtp.auth mock_smtp.call_args_list
mock_smtp.assert_called_with mock_smtp.auth_cram_md5 mock_smtp.call_count >
mock_smtp.assert_has_calls mock_smtp.auth_login mock_smtp.called
mock_smtp.assert_not_called mock_smtp.auth_plain mock_smtp.close
>>> mock_smtp.bogus
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-4856e93b6e10> in <module>()
----> 1 mock_smtp.bogus
/Users/pberkes/miniconda3/envs/gnode/lib/python3.5/unittest/mock.py in __getattr__(self, name)
576 elif self._mock_methods is not None:
577 if name not in self._mock_methods or name in _all_magics:
--> 578 raise AttributeError("Mock object has no attribute %r" % name)
579 elif _is_magic(name):
580 raise AttributeError(name)
AttributeError: Mock object has no attribute 'bogus'

View file

@ -0,0 +1,64 @@
##### Mock basic
m = Mock()
m.x = 3
m.x
m.f(1,2,3)
m.whatever(3, key=2)
m
m.f
m.g
##### special attributes and assert methods
mock=Mock()
mock.f(2,3)
mock.f('a')
mock.f.called
mock.add.called
mock.f.called
mock.f.call_args
mock.f.call_count
mock.f.call_args_list
mock.f.assert_called_with('a')
mock.f.assert_called_once_with('a')
mock.f.assert_called_with(2, 3)
mock.f.assert_any_call(2, 3)
mock.f.assert_has_calls(['a', (2,3)])
#### return_value and side_effect
mock.g.return_value = 7
mock.g(32)
mock.g('r')
# useful to simulate file errors or server errors
mock.g.side_effect = Exception('Noooo')
mock.g(2)
mock.g.side_effect = lambda x: x.append(2)
a=[1]
mock.g(a)
a
mock.g.side_effect = [1, 4, 5]
mock.g()
mock.g()
mock.g()
mock.g()
#####
mock = Mock()
mock.f(3,4)
mock.g('a')
mock.f.a()
mock.method_calls
result = m.h(32)
result(1)
m.mock_calls
##### spec
from chaco.api import Plot
m2 = Mock(spec=Plot)
isinstance(m2, Plot)
m2.add
m2.add(12,'asdfasd')
m2.aaa

View file

@ -0,0 +1,41 @@
report_template = """
Report
======
The experiment was a {judgment}!
Let's do this again, with a bigger budget.
"""
def send_report(result, smtp):
if result > 0.5:
judgment = 'big success'
else:
judgment = 'total failure'
report = report_template.format(judgment=judgment)
smtp.send_message(
report,
from_addr='pony@magicpony.com',
to_addrs=['ferenc@magicpony.com'],
)
from unittest.mock import Mock
def test_send_report_success():
smtp = Mock()
send_report(0.6, smtp)
assert smtp.send_message.call_count == 1
pos_args, kw_args = smtp.send_message.call_args
message = pos_args[0]
assert 'success' in message
smtp.reset_mock()
send_report(0.4, smtp)
assert smtp.send_message.call_count == 1
args, kwargs = smtp.send_message.call_args
message = args[0]
assert 'failure' in message

View file

@ -0,0 +1,13 @@
def connect(address):
import time
time.sleep(5)
return '1'
def get_angle(address):
return 0.0
def set_angle(address, angle):
if angle < 0 or angle > 1.40:
raise IOError('Telescope jammed -- please call technical support')
return True

View file

@ -0,0 +1,30 @@
import telescope_driver
class TelescopeModel(object):
# Minimum safe elevation angle (see handbook).
MIN_ANGLE = 0.0
# Maximum safe elevation angle (see handbook).
MAX_ANGLE = 80.0
def __init__(self, address):
self.address = address
# Connect to telescope
self.connection = telescope_driver.connect(address)
# Get initial state of telescope.
self.current_angle = telescope_driver.get_angle(self.connection)
def set_elevation_angle(self, angle):
""" Set the elevation angle of the telescope (in rad).
If the angle is outside the range allowed by the manufacturer,
raise a ValueError.
"""
if angle < self.MIN_ANGLE or angle > self.MAX_ANGLE:
raise ValueError('Unsafe elevation angle: {}'.format(angle))
telescope_driver.set_angle(self.connection, angle)
self.current_angle = angle

View file

@ -0,0 +1,12 @@
import numpy as np
from py.test import raises
from telescope_model import TelescopeModel
def test_unsafe_elevation_angle():
telescope = TelescopeModel(address='10.2.1.1')
elevation_angle = np.pi / 2.0
with raises(ValueError):
telescope.set_elevation_angle(elevation_angle)

View file

@ -0,0 +1,29 @@
from unittest import mock
import numpy as np
from py.test import raises
from telescope_model import TelescopeModel
def test_unsafe_elevation_angle():
with mock.patch('telescope_model.telescope_driver'):
telescope = TelescopeModel(address='10.2.1.1')
elevation_angle = np.pi / 2.0
with raises(ValueError):
telescope.set_elevation_angle(elevation_angle)
def test_model_initialization():
connection_id = 'bogus_connection'
initial_angle = 1.23
with mock.patch('telescope_model.telescope_driver') as driver:
driver.connect.return_value = connection_id
driver.get_angle.return_value = initial_angle
telescope = TelescopeModel(address='10.2.1.1')
assert telescope.connection == connection_id
assert driver.connect.call_count == 1
assert telescope.current_angle == initial_angle