def test_number_of_words_in_txt(self, mock1, mock2, open_mock): open_mock.return_value = StringIO( six.u('number_of_words=2\none two\nathree four\nfive\nsix\n')) with self.assertRaisesRegex( InitializationError, r"Invalid config: Phrase has 1 word\(s\) \(while number_of_words=2\) " r"at list u?'one' line 4: u?'five'"): _load_data('/data')
def test_max_length_in_txt(self, mock1, mock2, open_mock): # Valid option max_length open_mock.return_value = StringIO( six.u('max_length=5\nabcde\nabcdef\nabc\n')) with self.assertRaisesRegex( InitializationError, r"Invalid config: Word is too long " r"at list u?'one' line 3: u?'abcdef'"): _load_data('/data')
def test_load_data_failed_to_read_config(self, listdir_mock, isdir_mock, open_mock): # First call to open() should pass, # second call should raise OSError. class open_then_fail(object): def __init__(self): self.called = False def __call__(self, *x, **y): if self.called: raise OSError('BOOM!') self.called = True return StringIO(six.u('word')) open_mock.side_effect = open_then_fail() with self.assertRaisesRegex( InitializationError, "Failed to read config from " "/data/config.json: BOOM!"): _load_data('/data')
def test_load_data(self, listdir_mock, isdir_mock, open_mock, load_wordlist_mock, json_mock): listdir_mock.return_value = ['one.txt', 'two.txt'] isdir_mock.return_value = True lists = iter([['one', 'ichi'], ['two', 'ni']]) load_wordlist_mock.side_effect = lambda x, y: next(lists) json_mock.return_value = {'hello': 'world'} path = '/data' config, wordlists = _load_data(path) self.assertEqual(config, {'hello': 'world'}) self.assertEqual(wordlists, { 'one': ['one', 'ichi'], 'two': ['two', 'ni'], })
def test_load_data_no_dir(self): path = os.path.join(tempfile.gettempdir(), 'does', 'not', 'exist') with self.assertRaisesRegex(InitializationError, 'Directory not found: {}'.format(path)): _load_data(path)
def test_load_data_invalid_json(self, *args): with self.assertRaisesRegex( InitializationError, r"Invalid config: Invalid JSON: " r"((?:Expecting value|Unexpected 'w' at): line 1 column 1 \(char 0\)|" r"No JSON object could be decoded)"): _load_data('/data')
def test_load_data_os_error(self, listdir_mock, isdir_mock, open_mock): with self.assertRaisesRegex(InitializationError, r'Failed to read /data/one.txt: BOOM!'): _load_data('/data')