def test_login(self, logger: MagicMock): username = "******" password = "******" email = "*****@*****.**" user = BaseUser(username=username, password=password, email=email) user.save().run_sync() # Test correct password authenticated = BaseUser.login_sync(username, password) self.assertTrue(authenticated == user.id) # Test incorrect password authenticated = BaseUser.login_sync(username, "blablabla") self.assertTrue(authenticated is None) # Test ultra long password malicious_password = secrets.token_urlsafe(1000) authenticated = BaseUser.login_sync(username, malicious_password) self.assertTrue(authenticated is None) self.assertEqual( logger.method_calls, [call.warning("Excessively long password provided.")], ) # Test ulta long username logger.reset_mock() malicious_username = secrets.token_urlsafe(1000) authenticated = BaseUser.login_sync(malicious_username, password) self.assertTrue(authenticated is None) self.assertEqual( logger.method_calls, [call.warning("Excessively long username provided.")], )
def test_unknown_but_tolerated_category(self, val): with patch('n6lib.auth_db.fields.LOGGER') as LOGGER_mock: self._test_proper_values(CriteriaCategory, {'category': val}, expecting_stripped_string=True) self.assertEqual(LOGGER_mock.mock_calls, [ call.warning(CategoryCustomizedField.warning_msg_template, val.strip()), ])
def test_hashed_password_error(self, logger: MagicMock): with self.assertRaises(ValueError) as manager: BaseUser.create_user_sync(username="******", password="******") self.assertEqual(manager.exception.__str__(), "Do not pass a hashed password.") self.assertEqual( logger.method_calls, [ call.warning( "Tried to create a user with an already hashed password.") ], )
def test_query_no_properties(self, mock_logger): features = [{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [1, 2] } }] store = WfsDatastore({}) store.response = type('MockResponse', (object, ), {'json': lambda: { 'features': features }}) self.assertListEqual(features, list(store.query(None))) mock_logger.assert_has_calls( [call.warning("WFS feature does not contain 'properties' key")])
def test_assembling_decoder_mix_in_warning(): encoding = "utf-8" data_bytes = "🐷🐶.".encode(encoding) adm = AssemblingDecoderMixIn() with patch("datalad.runner.utils.logger") as logger_mock: result = adm.decode(1, data_bytes[0:1], encoding) assert_equal(result, '') del adm assert_in( call.warning("unprocessed data in AssemblingDecoderMixIn"), logger_mock.mock_calls) assert_in( call.debug( "unprocessed data in AssemblingDecoderMixIn:\n" "fd: 1, data: b'\\xf0'\n"), logger_mock.mock_calls)
def test_start_call_sequence(self, pdaemonize, prun): pidfile_mock = MagicMock() logger = MagicMock() logger.warning = MagicMock() self.simple_instance.pidfile = pidfile_mock self.simple_instance.logger = logger manager = MagicMock() manager.attach_mock(pdaemonize, "daemonize") manager.attach_mock(logger.warning, "warning") manager.attach_mock(prun, "run") self.simple_instance.start() msg = self.simple_instance._starting_message expected_calls = [ call.daemonize(pidfile_mock), call.warning(msg), call.run() ] manager.assert_has_calls(expected_calls)
# setuid used (at least number of times) expected_setuid_calls = [call.__enter__()] * expected_setuid_calls_count set_effective_root_uid_mock.assert_has_calls(expected_setuid_calls, any_order=True) @patch('wca.resctrl.SetEffectiveRootUid') @patch('os.makedirs') @pytest.mark.parametrize('side_effect, log_call', [ (OSError(errno.E2BIG, 'other'), call.error('Could not write pid to resctrl (%r): Unexpected errno %r.', '/sys/fs/resctrl/tasks', 7)), (OSError(errno.ESRCH, 'no such proc'), call.warning( 'Could not write pid to resctrl (%r): Process probably does not exist. ', '/sys/fs/resctrl/tasks')), (OSError(errno.EINVAL, 'no such proc'), call.error('Could not write pid to resctrl (%r): Invalid argument %r.', '/sys/fs/resctrl/tasks')), ]) def test_resgroup_add_pids_invalid(makedirs_mock, set_effective_root_uid_mock, side_effect, log_call): resgroup = ResGroup(name='') writes_mock = { '/sys/fs/resctrl/tasks': Mock(return_value=Mock(write=Mock(side_effect=side_effect))), '/sys/fs/resctrl/mon_groups/c1/tasks': MagicMock() } with patch('builtins.open', new=create_open_mock(writes_mock)), patch(
def test_scan_file(self): """Test analysis of a single file. """ from os import stat_result from os.path import join from ..census import scan_file mock_os = Mock() fd = join(self.data_dir, 'test.module') intlink = join(self.data_dir, 'test.module.link') extlink = '/foo/bar/t/test.module' s = stat_result((33188, 83865343, 16777220, 1, 501, 20, 973, 1491428112, 1446143268, 1462630505)) # # Simulate a simple file. # calls = [ call.debug("os.stat('{0}')".format(fd)), call.warning("{0} does not have correct group id!".format(fd)) ] mock_log = Mock() with patch('desiutil.log.get_logger') as mock_get_logger: with patch.dict('sys.modules', { 'os': mock_os, 'os.path': mock_os.path }): mock_get_logger.return_value = mock_log mock_os.environ = dict() mock_os.stat.return_value = s mock_os.path.islink.return_value = False mock_os.path.join.return_value = fd f = scan_file(self.data_dir, 'test.module', 12345) self.assertListEqual(mock_log.mock_calls, calls) self.assertEqual(f.filename, fd) self.assertEqual(f.size, 973) self.assertEqual(f.year, 2016) # # Simulate an internal link. # calls = [ call.debug("os.stat('{0}')".format(fd)), call.warning("{0} does not have correct group id!".format(fd)), call.debug("os.lstat('{0}')".format(fd)), call.warning("{0} does not have correct group id!".format(fd)), call.debug("Found internal link {0} -> {0}.link.".format(fd)) ] mock_log = Mock() with patch('desiutil.log.get_logger') as mock_get_logger: with patch.dict('sys.modules', { 'os': mock_os, 'os.path': mock_os.path }): mock_get_logger.return_value = mock_log mock_os.environ = dict() mock_os.stat.return_value = s mock_os.lstat.return_value = s mock_os.path.commonpath.return_value = self.data_dir mock_os.path.islink.return_value = True mock_os.path.join.return_value = fd mock_os.path.realpath.return_value = intlink f = scan_file(self.data_dir, 'test.module', 12345) self.assertListEqual(mock_log.mock_calls, calls) self.assertEqual(f.filename, fd) self.assertEqual(f.size, 973) self.assertTrue(f.islink) self.assertFalse(f.isexternal) self.assertEqual(f.linkname, intlink) # # Simulate an external link. # calls = [ call.debug("os.stat('{0}')".format(fd)), call.warning("{0} does not have correct group id!".format(fd)), call.debug("os.lstat('{0}')".format(fd)), call.warning("{0} does not have correct group id!".format(fd)), call.debug("Found external link {0} -> {1}.".format(fd, extlink)) ] mock_log = Mock() with patch('desiutil.log.get_logger') as mock_get_logger: with patch.dict('sys.modules', { 'os': mock_os, 'os.path': mock_os.path }): mock_get_logger.return_value = mock_log mock_os.environ = dict() mock_os.stat.return_value = s mock_os.lstat.return_value = s mock_os.path.commonpath.return_value = '/' mock_os.path.islink.return_value = True mock_os.path.join.return_value = fd mock_os.path.realpath.return_value = extlink f = scan_file(self.data_dir, 'test.module', 12345) self.assertListEqual(mock_log.mock_calls, calls) self.assertEqual(f.filename, fd) self.assertEqual(f.size, 973) self.assertTrue(f.islink) self.assertTrue(f.isexternal) self.assertEqual(f.linkname, extlink)