def test_address_save_without_address(self, mock_save): request = MagicMock() request.user.is_authenticated.return_value = False request.session = {} request.POST = dict(NEW_ADDRESS, method='dummy_shipping') request.session = {STORAGE_SESSION_KEY: {}} group = MagicMock() group.address = None storage = {'address': NEW_ADDRESS} step = ShippingStep(request, storage, group) self.assertTrue(step.forms_are_valid(), "Forms don't validate.") step.save() self.assertEqual(mock_save.call_count, 0) self.assertTrue(isinstance(storage['address'], dict), 'dict expected')
def test_get_session_var(self): """ Ensure get_session_var function is working properly. """ from garage.session import get_session_var self._msg("test", "get_session_var", first=True) key = "abc" val = "123" request = MagicMock() my_dict = {key: val} def getitem(name): return my_dict[name] def setitem(name, val): my_dict[name] = val request.session = MagicMock(spec_set=dict) request.session.__getitem__.side_effect = getitem request.session.__setitem__.side_effect = setitem result = get_session_var(request, key) self.assertEqual(result, val) self._msg("key", key) self._msg("val", val) self._msg("result", result) val = "foo" my_dict[key] = val result = get_session_var(request, key) self.assertEqual(result, val) self._msg("key", key) self._msg("val", val) self._msg("result", result)
def assert_expire_in_extended(self, req_path, should_expire_in, should_extend, headers=None, query_string=None): request = MagicMock(path=req_path) request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True thirty_mins_ago = (datetime.datetime.now() - datetime.timedelta(minutes=30)).strftime("%Y-%m-%dT%H:%M:%S.%f") request.session = {"_session_security": thirty_mins_ago} if headers: request.META = headers if query_string: request.REQUEST = query_string before_response = {} response = self.middleware.process_response(request, before_response) self.assertIsNotNone(response.get("Session-Expires-In")) self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in - 30, delta=1.0) self.middleware.process_request(request) response2 = self.middleware.process_response(request, before_response) self.assertIsNotNone(response2.get("Session-Expires-In")) if should_extend: self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in, delta=1.0) else: self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in - 30, delta=1.0)
def req(): """XXX: Very simple mock request, improve this""" req = MagicMock() req.header = ["0", "1", "2", "3", "4", "5"] req.session = {} req.params = {} return req
def test_copy(self, computed_md5_mock): # the md5sum of the file being copied md5sum = 'd41d8cd98f00b204e9800998ecf84eee' # patch the compute_md5 function in vos to return the above value computed_md5_mock.return_value = md5sum #mock the props of the corresponding node props = MagicMock() props.get.return_value = md5sum #add props to the mocked node node = MagicMock(spec=Node) node.props = props # mock one by one the chain of connection.session.response.headers conn = MagicMock(spec=Connection) session = MagicMock() response = MagicMock() headers = MagicMock() headers.get.return_value = md5sum response.headers = headers session.get.return_value = response conn.session = session test_client = Client() # use the mocked connection instead of the real one test_client.conn = conn get_node_url_mock = Mock( return_value=['http://cadc.ca/test', 'http://cadc.ca/test']) test_client.get_node_url = get_node_url_mock #patch Client.get_node to return our mocked node get_node_mock = Mock(return_value=node) test_client.get_node = get_node_mock # time to test... vospaceLocation = 'vos://test/foo' osLocation = '/tmp/foo' # copy from vospace test_client.copy(vospaceLocation, osLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, method='GET', cutout=None, view='data') computed_md5_mock.assert_called_once_with(osLocation) get_node_mock.assert_called_once_with(vospaceLocation) # copy to vospace get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() test_client.copy(osLocation, vospaceLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, 'PUT') computed_md5_mock.assert_called_once_with(osLocation) # error tests - md5sum mismatch computed_md5_mock.return_value = '000bad000' with self.assertRaises(OSError): test_client.copy(vospaceLocation, osLocation) with self.assertRaises(OSError): test_client.copy(osLocation, vospaceLocation)
def test_other_results(self, m_inspect): m_session = MagicMock() ret = MagicMock() ret.session = m_session m_inspect.return_value = ret res = self.fw.other_results self.assertEqual(res, m_session.query().join().filter().order_by().all())
def test_copy(self, computed_md5_mock): # the md5sum of the file being copied md5sum = 'd41d8cd98f00b204e9800998ecf84eee' # patch the compute_md5 function in vos to return the above value computed_md5_mock.return_value = md5sum #mock the props of the corresponding node props = MagicMock() props.get.return_value = md5sum #add props to the mocked node node = MagicMock(spec=Node) node.props = props # mock one by one the chain of connection.session.response.headers conn = MagicMock(spec=Connection) session = MagicMock() response = MagicMock() headers = MagicMock() headers.get.return_value = md5sum response.headers = headers session.get.return_value = response conn.session = session test_client = Client() # use the mocked connection instead of the real one test_client.conn = conn get_node_url_mock = Mock(return_value=['http://cadc.ca/test', 'http://cadc.ca/test']) test_client.get_node_url = get_node_url_mock #patch Client.get_node to return our mocked node get_node_mock = Mock(return_value=node) test_client.get_node = get_node_mock # time to test... vospaceLocation = 'vos://test/foo' osLocation = '/tmp/foo' # copy from vospace test_client.copy(vospaceLocation, osLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, method='GET', cutout=None, view='data') computed_md5_mock.assert_called_once_with(osLocation) get_node_mock.assert_called_once_with(vospaceLocation) # copy to vospace get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() test_client.copy(osLocation, vospaceLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, 'PUT') computed_md5_mock.assert_called_once_with(osLocation) # error tests - md5sum mismatch computed_md5_mock.return_value = '000bad000' with self.assertRaises(OSError): test_client.copy(vospaceLocation, osLocation) with self.assertRaises(OSError): test_client.copy(osLocation, vospaceLocation)
def test_set_session_var_error(self): """ set_session_var should bypass setting request.session raises exception. """ from garage.session import set_session_var self._msg("test", "set_session_var error", first=True) request = MagicMock() my_dict = {} def getitem(name): return my_dict[name] def setitem(name, val): my_dict[name] = "AttributeError" raise AttributeError request.session = MagicMock(spec_set=dict) request.session.__getitem__.side_effect = getitem request.session.__setitem__.side_effect = setitem set_session_var(request, "key", "val") result = my_dict.get("key") self.assertEqual(result, "AttributeError") self._msg("result", result) request = MagicMock() my_dict = {} def getitem(name): return my_dict[name] def setitem(name, val): my_dict[name] = "TypeError" raise TypeError request.session = MagicMock(spec_set=dict) request.session.__getitem__.side_effect = getitem request.session.__setitem__.side_effect = setitem set_session_var(request, "key", "val") result = my_dict.get("key") self.assertEqual(result, "TypeError") self._msg("result", result)
def test_get_session_var_error(self): """ get_session_var should return default value if getting key raises exception. """ from garage.session import get_session_var self._msg("test", "get_session_var error", first=True) request = MagicMock() my_dict = {} def getitem(name): raise AttributeError def setitem(name, val): my_dict[name] = val request.session = MagicMock(spec_set=dict) request.session.__getitem__.side_effect = getitem request.session.__setitem__.side_effect = setitem result = get_session_var(request, "key", default="AttributeError") calls = request.session.mock_calls self._msg("calls", calls) self.assertEqual(result, "AttributeError") self._msg("result", result) request = MagicMock() my_dict = {} def getitem(name): raise TypeError def setitem(name, val): my_dict[name] = val request.session = MagicMock(spec_set=dict) request.session.__getitem__.side_effect = getitem request.session.__setitem__.side_effect = setitem result = get_session_var(request, "key", default="TypeError") calls = request.session.mock_calls self._msg("calls", calls) self.assertEqual(result, "TypeError") self._msg("result", result)
def request(self, lti_launch={"custom_canvas_api_domain": TEST_DOMAIN}, get_params={}): request = MagicMock() session = {"oauth_return_uri": self.TEST_DOMAIN} if lti_launch: session["LTI_LAUNCH"] = lti_launch request.session = session request.GET = get_params request.user.oauthtoken.updated_on = TEST_TIME return request
def mock_request(self, authed, path='/'): mock_request = MagicMock() mock_request.method = 'GET' mock_request.user.is_authenticated.return_value = authed mock_request.POST = {} mock_request.META = {} mock_request.session = {} mock_request.build_absolute_uri.return_value = path mock_request.get_full_path.return_value = path return mock_request
def test_process_response_logged_in_with_session_but_invalid_session_security_key(self): request = MagicMock(path="/") request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True request.session = {"_session_security": u"cantp😺 😸 😻 😽 😼 🙀 😿 😹 😾arsethisasadate"} before_response = {} with self.assertRaises(UnicodeEncodeError): self.middleware.process_response(request, before_response)
def shell(): """ Create fake shell. """ base = MagicMock() base.session = hashlib.sha256(str(time.time()).encode("utf-8")).hexdigest() base.client = MagicMock() base.client.activationkey = MagicMock() base.do_activationkey_list = MagicMock(return_value="do_activation_list") return base
def test_process_response_logged_in_with_session_but_valid_session_security_key(self): request = MagicMock(path="/") request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True request.session = {"_session_security": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")} before_response = {} response = self.middleware.process_response(request, before_response) self.assertIsNotNone(response.get("Session-Expires-In")) self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), EXPIRE_AFTER // 60, delta=1.0)
def test_address_save_with_address_in_group(self, mock_save): request = MagicMock() request.user.is_authenticated.return_value = False request.session = {} request.POST = dict(NEW_ADDRESS, method='dummy_shipping') group = MagicMock() group.address = NEW_ADDRESS storage = {'address': NEW_ADDRESS} step = ShippingStep(request, storage, group) self.assertTrue(step.forms_are_valid(), "Forms don't validate.") step.save() self.assertEqual(mock_save.call_count, 0)
def test_validate_url(self): resolwe = MagicMock(spec=Resolwe) message = "Server url must start with .*" with self.assertRaisesRegex(ValueError, message): Resolwe._validate_url(resolwe, "starts.without.http") resolwe.session = MagicMock( get=MagicMock(side_effect=requests.exceptions.ConnectionError()) ) message = "The site can't be reached: .*" with self.assertRaisesRegex(ValueError, message): Resolwe._validate_url(resolwe, "http://invalid.url")
def test_address_save_with_address_in_checkout(self, mock_save): request = MagicMock() request.user.is_authenticated.return_value = False request.session = {} request.POST = dict(NEW_ADDRESS, method='dummy_shipping') original_billing_address = {'name': 'Change Me', 'id': 10} group = MagicMock() group.address = None storage = {'address': original_billing_address} step = ShippingStep(request, storage, group) self.assertTrue(step.forms_are_valid(), "Forms don't validate.") step.save() self.assertEqual(mock_save.call_count, 0) self.assertEqual(storage['address'], NEW_ADDRESS)
def test_process_response_logged_in_with_session_but_invalid_session_security_key( self): request = MagicMock(path="/") request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True request.session = { "_session_security": u"cantp😺 😸 😻 😽 😼 🙀 😿 😹 😾arsethisasadate" } before_response = {} with self.assertRaises(UnicodeEncodeError): self.middleware.process_response(request, before_response)
def get_test_request(self): """ Sets up a mock request object """ request = MagicMock() request.LTI = dict(DEFAULT_LTI_PARAMS) request.method = "POST" request.lti_initial_request = True request.lti_authentication_successful = True request.POST = { "lti_message_type": "basic-lti-launch-request", "custom_component_display_name": "Not Scored Assignment" } request.session = {} request.user = self.get_test_user() return request
def test_create_page_after_confirmation(self): """ This method tests the ability of the create view to recognise once a user has completed the pattern creation process. The expected result of this test is for the view to be recognise this state correctly. """ # Set up a request to test the post-confirmation logic class session_dict(dict): def invalidate(self): pass request = MagicMock() d = session_dict() d["confirmed"] = "true" request.session = d response = create_view(request) # Assert that the 'user' has been rerouted to the beginning of the process assert isinstance(response, HTTPFound)
def test_process_response_logged_in_with_session_but_valid_session_security_key( self): request = MagicMock(path="/") request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True request.session = { "_session_security": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f") } before_response = {} response = self.middleware.process_response(request, before_response) self.assertIsNotNone(response.get("Session-Expires-In")) self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), EXPIRE_AFTER // 60, delta=1.0)
def test_args_args(self): """ Test args option. """ shell = MagicMock() shell.help_api = MagicMock() shell.client = MagicMock() shell.client.call = MagicMock(return_value=["one", "two", "three"]) shell.session = "session" log = MagicMock() out = helpers.FileHandleMock() with patch("spacecmd.api.open", out, create=True) as mop, \ patch("spacecmd.api.logging", log) as mlog: api.do_api(shell, "call -A first,second,123 -o /tmp/spacecmd.log") assert shell.client.call.called assert shell.client.call.call_args_list[0][0] == ('session', 'first', 'second', 123) assert out._closed
def assert_expire_in_extended(self, req_path, should_expire_in, should_extend, headers=None, query_string=None): request = MagicMock(path=req_path) request.method = "GET" request.user = MagicMock() request.user.is_authenticated.return_value = True thirty_mins_ago = ( datetime.datetime.now() - datetime.timedelta(minutes=30)).strftime("%Y-%m-%dT%H:%M:%S.%f") request.session = {"_session_security": thirty_mins_ago} if headers: request.META = headers if query_string: request.REQUEST = query_string before_response = {} response = self.middleware.process_response(request, before_response) self.assertIsNotNone(response.get("Session-Expires-In")) self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in - 30, delta=1.0) self.middleware.process_request(request) response2 = self.middleware.process_response(request, before_response) self.assertIsNotNone(response2.get("Session-Expires-In")) if should_extend: self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in, delta=1.0) else: self.assertIsAlmostEqualMinutes(response.get("Session-Expires-In"), should_expire_in - 30, delta=1.0)
def test_copy(self, computed_md5_mock): # the md5sum of the file being copied md5sum = 'd41d8cd98f00b204e9800998ecf84eee' # patch the compute_md5 function in vos to return the above value computed_md5_mock.return_value = md5sum # mock the props of the corresponding node props = MagicMock() props.get.return_value = md5sum # add props to the mocked node node = MagicMock(spec=Node) node.props = props # mock one by one the chain of connection.session.response.headers conn = MagicMock(spec=Connection) session = MagicMock() response = MagicMock() headers = MagicMock() headers.get.return_value = md5sum response.headers = headers session.get.return_value = response conn.session = session test_client = Client() # use the mocked connection instead of the real one test_client.conn = conn get_node_url_mock = Mock( return_value=['http://cadc.ca/test', 'http://cadc.ca/test']) test_client.get_node_url = get_node_url_mock mock_update = Mock() test_client.update = mock_update # patch Client.get_node to return our mocked node get_node_mock = Mock(return_value=node) test_client.get_node = get_node_mock # time to test... vospaceLocation = 'vos://test/foo' osLocation = '/tmp/foo' if os.path.isfile(osLocation): os.remove(osLocation) # copy from vospace test_client.copy(vospaceLocation, osLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, method='GET', cutout=None, view='data') computed_md5_mock.assert_called_once_with(osLocation) assert get_node_mock.called # repeat - local file and vospace file are now the same -> only # get_node is called to get the md5 of remote file get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() get_node_mock.reset_mock() test_client.copy(vospaceLocation, osLocation) assert not get_node_url_mock.called computed_md5_mock.assert_called_once_with(osLocation) get_node_mock.assert_called_once_with(vospaceLocation) # change the content of local files to trigger a new copy get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() computed_md5_mock.side_effect = ['d002233', md5sum] get_node_mock.reset_mock() test_client.copy(vospaceLocation, osLocation) get_node_url_mock.assert_called_once_with(vospaceLocation, method='GET', cutout=None, view='data') computed_md5_mock.assert_called_with(osLocation) get_node_mock.assert_called_once_with(vospaceLocation) # copy to vospace when md5 sums are the same -> only update occurs get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() computed_md5_mock.side_effect = None computed_md5_mock.return_value = md5sum test_client.copy(osLocation, vospaceLocation) mock_update.assert_called_once() assert not get_node_url_mock.called # make md5 different get_node_url_mock.reset_mock() get_node_url_mock.return_value =\ ['http://cadc.ca/test', 'http://cadc.ca/test'] computed_md5_mock.reset_mock() mock_update.reset_mock() props.get.side_effect = ['d00223344', md5sum] test_client.copy(osLocation, vospaceLocation) assert not mock_update.called get_node_url_mock.assert_called_once_with(vospaceLocation, 'PUT') computed_md5_mock.assert_called_once_with(osLocation) # copy 0 size file -> delete and create on client but no bytes # transferred get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() computed_md5_mock.return_value = vos.ZERO_MD5 props.get.side_effect = [md5sum] mock_delete = Mock() mock_create = Mock() test_client.delete = mock_delete test_client.create = mock_create test_client.copy(osLocation, vospaceLocation) mock_create.assert_called_once_with(vospaceLocation) mock_delete.assert_called_once_with(vospaceLocation) assert not get_node_url_mock.called # copy new 0 size file -> reate on client but no bytes transferred get_node_url_mock.reset_mock() computed_md5_mock.reset_mock() mock_delete.reset_mock() mock_create.reset_mock() computed_md5_mock.return_value = vos.ZERO_MD5 props.get.side_effect = [None] mock_delete = Mock() mock_create = Mock() test_client.delete = mock_delete test_client.create = mock_create test_client.copy(osLocation, vospaceLocation) mock_create.assert_called_once_with(vospaceLocation) assert not mock_delete.called assert not get_node_url_mock.called # error tests - md5sum mismatch props.get.side_effect = [md5sum] computed_md5_mock.return_value = '000bad000' with self.assertRaises(OSError): test_client.copy(vospaceLocation, osLocation) with self.assertRaises(OSError): test_client.copy(osLocation, vospaceLocation) # requests just the headers props.get.side_effect = [None] get_node_url_mock = Mock( return_value=['http://cadc.ca/test', 'http://cadc.ca/test']) test_client.get_node_url = get_node_url_mock computed_md5_mock.reset_mock() computed_md5_mock.side_effect = ['d002233', md5sum] get_node_mock.reset_mock() test_client.copy(vospaceLocation, osLocation, head=True) get_node_url_mock.assert_called_once_with(vospaceLocation, method='GET', cutout=None, view='header')