How to use stopAll method in root

Best JavaScript code snippet using root

test_path.py

Source:test_path.py Github

copy

Full Screen

1# encoding: utf-82import os3import shutil4import tempfile5import unittest6from gettext import gettext as _7import unittest.mock as mock8import pytest9import scarlett_os10from scarlett_os import compat11from scarlett_os import exceptions12from scarlett_os.internal import path as s_path13from scarlett_os.internal.gi import GLib14from scarlett_os.internal.gi import Gst15import tests16import imp # Library to help us reload our tasker module17@pytest.fixture(scope="function")18def path_mocker_stopall(mocker):19 "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"20 print("Called [setup]: mocker.stopall()")21 mocker.stopall()22 print("Called [setup]: imp.reload(s_path)")23 imp.reload(s_path)24 yield mocker25 print("Called [teardown]: mocker.stopall()")26 mocker.stopall()27 print("Called [setup]: imp.reload(s_path)")28 imp.reload(s_path)29def bad_read():30 raise UnicodeDecodeError("utf-8", b"0x80", 0, 1, "invalid start byte")31@pytest.mark.scarlettonly32@pytest.mark.unittest33@pytest.mark.scarlettonlyunittest34@pytest.mark.pathtest35class TestPathToFileURI(object):36 def test_get_parent_dir(self, path_mocker_stopall):37 # mock38 mock_logger_info = path_mocker_stopall.MagicMock(name="mock_logger_info")39 # patch40 path_mocker_stopall.patch.object(41 scarlett_os.subprocess.logging.Logger, "info", mock_logger_info42 )43 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug/generator-player.dot"44 # run test45 result = s_path.get_parent_dir(path)46 assert mock_logger_info.call_count == 147 mock_logger_info.assert_any_call("get_parent_dir: {}".format(path))48 assert result == "/home/pi/dev/bossjones-github/scarlett_os/_debug"49 def test_mkdir_p(self, path_mocker_stopall):50 # mock51 mock_logger_info = path_mocker_stopall.MagicMock(name="mock_logger_info")52 mock_dir_exists = path_mocker_stopall.MagicMock(name="mock_dir_exists")53 mock_path = path_mocker_stopall.MagicMock(name="mock_path")54 # patch55 path_mocker_stopall.patch.object(56 scarlett_os.subprocess.logging.Logger, "info", mock_logger_info57 )58 path_mocker_stopall.patch.object(59 scarlett_os.internal.path, "dir_exists", mock_dir_exists60 )61 path_mocker_stopall.patch.object(scarlett_os.internal.path, "Path", mock_path)62 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug"63 mock_dir_exists.return_value = True64 # run test65 s_path.mkdir_p(path)66 # assert67 assert mock_logger_info.call_count == 168 mock_path.assert_called_once_with(path)69 # from scarlett_os.internal.debugger import dump70 mock_path().mkdir.assert_any_call(parents=True, exist_ok=True)71 mock_logger_info.assert_any_call(72 "Verify mkdir_p ran: {}".format(mock_dir_exists.return_value)73 )74 def test_dir_exists_false(self, path_mocker_stopall):75 # mock76 mock_logger_error = path_mocker_stopall.MagicMock(name="mock_logger_error")77 mock_path = path_mocker_stopall.MagicMock(name="mock_path")78 # patch79 path_mocker_stopall.patch.object(80 scarlett_os.subprocess.logging.Logger, "error", mock_logger_error81 )82 path_mocker_stopall.patch.object(scarlett_os.internal.path, "Path", mock_path)83 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug"84 mock_path_instance = mock_path()85 mock_path_instance.is_dir.return_value = False86 # run test87 s_path.dir_exists(path)88 # assert89 assert mock_logger_error.call_count == 190 assert mock_path_instance.is_dir.call_count == 291 mock_logger_error.assert_any_call("This is not a dir: {}".format(path))92 def test_dir_exists_true(self, path_mocker_stopall):93 # mock94 mock_logger_error = path_mocker_stopall.MagicMock(name="mock_logger_error")95 mock_path = path_mocker_stopall.MagicMock(name="mock_path")96 # patch97 path_mocker_stopall.patch.object(98 scarlett_os.subprocess.logging.Logger, "error", mock_logger_error99 )100 path_mocker_stopall.patch.object(scarlett_os.internal.path, "Path", mock_path)101 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug"102 mock_path_instance = mock_path()103 #104 mock_path_instance.is_dir.return_value = True105 # run test106 s_path.dir_exists(path)107 # assert108 assert mock_logger_error.call_count == 0109 assert mock_path_instance.is_dir.call_count == 2110 mock_logger_error.assert_not_called()111 def test_mkdir_if_does_not_exist_false(self, path_mocker_stopall):112 # mock113 mock_mkdir_p = path_mocker_stopall.MagicMock(name="mock_mkdir_p")114 mock_dir_exists = path_mocker_stopall.MagicMock(115 name="mock_dir_exists", return_value=False116 )117 # patch118 path_mocker_stopall.patch.object(119 scarlett_os.internal.path, "mkdir_p", mock_mkdir_p120 )121 path_mocker_stopall.patch.object(122 scarlett_os.internal.path, "dir_exists", mock_dir_exists123 )124 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug"125 # run test126 result = s_path.mkdir_if_does_not_exist(path)127 # assert128 assert mock_mkdir_p.call_count == 1129 assert mock_dir_exists.call_count == 1130 assert result == True131 def test_mkdir_if_does_not_exist_true(self, path_mocker_stopall):132 # mock133 mock_mkdir_p = path_mocker_stopall.MagicMock(name="mock_mkdir_p")134 mock_dir_exists = path_mocker_stopall.MagicMock(135 name="mock_dir_exists", return_value=True136 )137 # patch138 path_mocker_stopall.patch.object(139 scarlett_os.internal.path, "mkdir_p", mock_mkdir_p140 )141 path_mocker_stopall.patch.object(142 scarlett_os.internal.path, "dir_exists", mock_dir_exists143 )144 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug"145 # run test146 result = s_path.mkdir_if_does_not_exist(path)147 # assert148 assert mock_mkdir_p.call_count == 0149 assert mock_dir_exists.call_count == 1150 assert result == False151 def test_fname_exists_true(self, path_mocker_stopall):152 # mock153 mock_path = path_mocker_stopall.MagicMock(name="mock_path")154 # patch155 path_mocker_stopall.patch.object(scarlett_os.internal.path, "Path", mock_path)156 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug/generator.dot"157 mock_path_instance = mock_path()158 mock_path_instance.exists.return_value = True159 # run test160 result = s_path.fname_exists(path)161 assert mock_path_instance.exists.call_count == 1162 mock_path.assert_any_call(path)163 assert result == True164 def test_fname_exists_false(self, path_mocker_stopall):165 # mock166 mock_path = path_mocker_stopall.MagicMock(name="mock_path")167 # patch168 path_mocker_stopall.patch.object(scarlett_os.internal.path, "Path", mock_path)169 path = "/home/pi/dev/bossjones-github/scarlett_os/_debug/generator.dot"170 mock_path_instance = mock_path()171 mock_path_instance.exists.return_value = False172 # run test173 result = s_path.fname_exists(path)174 assert mock_path_instance.exists.call_count == 1175 mock_path_instance.exists.assert_called_once_with()176 mock_path.assert_any_call(path)177 assert result == False178 def test_dir_isWritable(self, path_mocker_stopall):179 # mock180 mock_os_access = path_mocker_stopall.MagicMock(name="mock_os_access")181 mock_os_path_isdir = path_mocker_stopall.MagicMock(name="mock_os_path_isdir")182 # patch183 path_mocker_stopall.patch.object(184 scarlett_os.internal.path.os, "access", mock_os_access185 )186 path_mocker_stopall.patch.object(187 scarlett_os.internal.path.os.path, "isdir", mock_os_path_isdir188 )189 path = "file:///tmp"190 # patch return values191 mock_os_path_isdir.return_value = True192 mock_os_access.return_value = True193 # run test194 result = s_path.isWritable(path)195 # tests196 mock_os_path_isdir.assert_called_once_with("file:///tmp")197 mock_os_access.assert_called_once_with("file:///tmp", os.W_OK)198 assert result == True199 def test_file_isWritable(self, path_mocker_stopall):200 # mock201 mock_os_access = path_mocker_stopall.MagicMock(name="mock_os_access")202 mock_os_path_isdir = path_mocker_stopall.MagicMock(name="mock_os_path_isdir")203 # patch204 path_mocker_stopall.patch.object(205 scarlett_os.internal.path.os, "access", mock_os_access206 )207 path_mocker_stopall.patch.object(208 scarlett_os.internal.path.os.path, "isdir", mock_os_path_isdir209 )210 path = "file:///tmp/fake_file"211 # patch return values212 mock_os_path_isdir.return_value = False213 mock_os_access.return_value = True214 # run test215 result = s_path.isWritable(path)216 # tests217 mock_os_path_isdir.assert_called_once_with("file:///tmp/fake_file")218 mock_os_access.assert_called_once_with("file:///tmp", os.W_OK)219 assert result == True220 # TODO: Need to figure out how to throw a fake UnicodeDecodeError221 # @mock.patch('scarlett_os.internal.path.os.access')222 # def test_dir_isReadable_unicode_error(self, mock_os_access):223 # # path = u'\x11/ip/addres\xc5\x82/print\x05first\x06second'224 # path = u'file:///tmp/fake_file'225 #226 # # b'\x80abc'.decode("utf-8", "strict")227 # # tmpdir = tempfile.mkdtemp('.scarlett_os-tests')228 #229 # mock_os_access.name = 'mock_os_access'230 # mock_os_access.side_effect = UnicodeDecodeError('', b'', 1, 0, '')231 #232 # with pytest.raises(UnicodeDecodeError):233 # result = s_path.isReadable(path)234 #235 def test_dir_isReadable(self):236 tmpdir = tempfile.mkdtemp(".scarlett_os-tests")237 try:238 # run test239 result = s_path.isReadable(tmpdir)240 # tests241 assert result == True242 finally:243 # nuke244 shutil.rmtree(tmpdir, ignore_errors=True)245 def test_file_isReadable(self):246 fd_unused, path = tempfile.mkstemp(suffix=".wav")247 try:248 # run test249 result = s_path.isReadable(path)250 # tests251 assert result252 finally:253 os.remove(path)254 def test_unicode_decode_error_isWritable(self, path_mocker_stopall):255 # mock256 mock_os_path_isdir = path_mocker_stopall.MagicMock(name="mock_os_path_isdir")257 mock_os_access = path_mocker_stopall.MagicMock(name="mock_os_access")258 mock_unicode_error_dialog = path_mocker_stopall.MagicMock(259 name="mock_unicode_error_dialog"260 )261 mock_logger_error = path_mocker_stopall.MagicMock(name="mock_logger_error")262 # patch263 path_mocker_stopall.patch.object(264 scarlett_os.internal.path.os.path, "isdir", mock_os_path_isdir265 )266 path_mocker_stopall.patch.object(267 scarlett_os.internal.path.os, "access", mock_os_access268 )269 path_mocker_stopall.patch.object(270 scarlett_os.internal.path, "unicode_error_dialog", mock_unicode_error_dialog271 )272 path_mocker_stopall.patch.object(273 scarlett_os.subprocess.logging.Logger, "error", mock_logger_error274 )275 path = b"file:///tmp/fake_file"276 # patch return values277 mock_os_path_isdir.side_effect = UnicodeDecodeError("", b"", 1, 0, "")278 s_path.isWritable(path)279 assert mock_unicode_error_dialog.call_count == 1280 def test_unicode_error_dialog(self, path_mocker_stopall):281 # mock282 mock_logger_error = path_mocker_stopall.MagicMock(name="mock_logger_error")283 # patch284 path_mocker_stopall.patch.object(285 scarlett_os.subprocess.logging.Logger, "error", mock_logger_error286 )287 s_path.unicode_error_dialog()288 assert mock_logger_error.call_count == 1289 _message = _(290 "The system's locale that you are using is not UTF-8 capable. "291 "Unicode support is required for Python3 software like Pitivi. "292 "Please correct your system settings; if you try to use Pitivi "293 "with a broken locale, weird bugs will happen."294 )295 mock_logger_error.assert_any_call(_message)296 def test_path_to_uri(self):297 result = s_path.path_to_uri("/etc/fstab")298 assert result == b"file:///etc/fstab"299 assert type(result) == compat.bytes300 def test_uri_is_valid_bytes(self):301 uri = b"file:///etc/fstab"302 assert s_path.uri_is_valid(uri)303 def test_path_from_uri_bytes(self):304 raw_uri = b"file:///etc/fstab"305 result = s_path.path_from_uri(raw_uri)306 assert result == "/etc/fstab"307 def test_filename_from_uri_bytes(self):308 uri = b"file:///etc/fstab"309 result = s_path.filename_from_uri(uri)310 assert result == "fstab"311 def test_filename_from_uri_str(self):312 uri = "file:///etc/fstab"313 result = s_path.filename_from_uri(uri)314 assert result == "fstab"315 def test_quote_uri_byte_to_str(self):316 uri = b"file:///etc/fstab"317 result = s_path.quote_uri(uri)318 assert result == "file:///etc/fstab"319 assert type(result) == compat.text_type320 def test_quantize(self):321 result = s_path.quantize(100.00, 3.00)322 assert result == 99.0323 def test_binary_search_EmptyList(self):324 assert s_path.binary_search([], 10) == -1325 def test_binary_search_Existing(self):326 A = [10, 20, 30]327 for index, element in enumerate(A):328 assert s_path.binary_search([10, 20, 30], element) == index329 def test_binary_search_MissingLeft(self):330 assert s_path.binary_search([10, 20, 30], 1) == 0331 assert s_path.binary_search([10, 20, 30], 16) == 1332 assert s_path.binary_search([10, 20, 30], 29) == 2333 def test_binary_search_MissingRight(self):334 assert s_path.binary_search([10, 20, 30], 11) == 0335 assert s_path.binary_search([10, 20, 30], 24) == 1336 assert s_path.binary_search([10, 20, 30], 40) == 2337 def test_uri_to_path_str(self):338 uri = "file:///etc/fstab"339 result = s_path.uri_to_path(uri)340 assert result == "/etc/fstab"341 def test_uri_to_path_bytes(self):342 uri = b"file:///etc/fstab"343 result = s_path.uri_to_path(uri)344 assert result == "/etc/fstab"345##################################################################################346# Pitivi - BEGIN347##################################################################################348# def testMakeBackupUri(self):349# uri = "file:///tmp/x.xges"350# self.assertEqual(uri + "~", self.manager._makeBackupURI(uri))351#352# def testBackupProject(self):353# self.manager.newBlankProject()354#355# # Assign an uri to the project where it's saved by default.356# unused, xges_path = tempfile.mkstemp(suffix=".xges")357# uri = "file://" + os.path.abspath(xges_path)358# self.manager.current_project.uri = uri359# # This is where the automatic backup file is saved.360# backup_uri = self.manager._makeBackupURI(uri)361#362# # Save the backup363# self.assertTrue(self.manager.saveProject(364# self.manager.current_project, backup=True))365# self.assertTrue(os.path.isfile(path_from_uri(backup_uri)))366#367# self.manager.closeRunningProject()368# self.assertFalse(os.path.isfile(path_from_uri(backup_uri)),369# "Backup file not deleted when project closed")370##################################################################################371# Pitivi - BEGIN372##################################################################################373# def test_space_in_path(self):374# result = path.path_to_uri('/tmp/test this')375# self.assertEqual(result, 'file:///tmp/test%20this')376#377# def test_unicode_in_path(self):378# result = path.path_to_uri('/tmp/æøå')379# self.assertEqual(result, 'file:///tmp/%C3%A6%C3%B8%C3%A5')380#381# def test_utf8_in_path(self):382# result = path.path_to_uri('/tmp/æøå'.encode('utf-8'))383# self.assertEqual(result, 'file:///tmp/%C3%A6%C3%B8%C3%A5')384#385# def test_latin1_in_path(self):386# result = path.path_to_uri('/tmp/æøå'.encode('latin-1'))387# self.assertEqual(result, 'file:///tmp/%E6%F8%E5')388#389#390# class UriToPathTest(unittest.TestCase):391#392# def test_simple_uri(self):393# result = path.uri_to_path('file:///etc/fstab')394# self.assertEqual(result, '/etc/fstab'.encode('utf-8'))395#396# def test_space_in_uri(self):397# result = path.uri_to_path('file:///tmp/test%20this')398# self.assertEqual(result, '/tmp/test this'.encode('utf-8'))399#400# def test_unicode_in_uri(self):401# result = path.uri_to_path('file:///tmp/%C3%A6%C3%B8%C3%A5')402# self.assertEqual(result, '/tmp/æøå'.encode('utf-8'))403#404# def test_latin1_in_uri(self):405# result = path.uri_to_path('file:///tmp/%E6%F8%E5')406# self.assertEqual(result, '/tmp/æøå'.encode('latin-1'))407#408#409# class SplitPathTest(unittest.TestCase):410#411# def test_empty_path(self):412# self.assertEqual([], path.split_path(''))413#414# def test_single_dir(self):415# self.assertEqual(['foo'], path.split_path('foo'))416#417# def test_dirs(self):418# self.assertEqual(['foo', 'bar', 'baz'], path.split_path('foo/bar/baz'))419#420# def test_initial_slash_is_ignored(self):421# self.assertEqual(422# ['foo', 'bar', 'baz'], path.split_path('/foo/bar/baz'))423#424# def test_only_slash(self):425# self.assertEqual([], path.split_path('/'))426#427#428# class FindMTimesTest(unittest.TestCase):429# maxDiff = None430#431# def setUp(self): # noqa: N802432# self.tmpdir = tempfile.mkdtemp(b'.scarlett_os-tests')433#434# def tearDown(self): # noqa: N802435# shutil.rmtree(self.tmpdir, ignore_errors=True)436#437# def mkdir(self, *args):438# name = os.path.join(self.tmpdir, *[bytes(a) for a in args])439# os.mkdir(name)440# return name441#442# def touch(self, *args):443# name = os.path.join(self.tmpdir, *[bytes(a) for a in args])444# open(name, 'w').close()445# return name446#447# def test_names_are_bytestrings(self):448# """We shouldn't be mixing in unicode for paths."""449# result, errors = path.find_mtimes(tests.path_to_data_dir(''))450# for name in list(result.keys()) + list(errors.keys()):451# self.assertEqual(name, tests.IsA(bytes))452#453# def test_nonexistent_dir(self):454# """Non existent search roots are an error"""455# missing = os.path.join(self.tmpdir, 'does-not-exist')456# result, errors = path.find_mtimes(missing)457# self.assertEqual(result, {})458# self.assertEqual(errors, {missing: tests.IsA(exceptions.FindError)})459#460# def test_empty_dir(self):461# """Empty directories should not show up in results"""462# self.mkdir('empty')463#464# result, errors = path.find_mtimes(self.tmpdir)465# self.assertEqual(result, {})466# self.assertEqual(errors, {})467#468# def test_file_as_the_root(self):469# """Specifying a file as the root should just return the file"""470# single = self.touch('single')471#472# result, errors = path.find_mtimes(single)473# self.assertEqual(result, {single: tests.any_int})474# self.assertEqual(errors, {})475#476# def test_nested_directories(self):477# """Searching nested directories should find all files"""478#479# # Setup foo/bar and baz directories480# self.mkdir('foo')481# self.mkdir('foo', 'bar')482# self.mkdir('baz')483#484# # Touch foo/file foo/bar/file and baz/file485# foo_file = self.touch('foo', 'file')486# foo_bar_file = self.touch('foo', 'bar', 'file')487# baz_file = self.touch('baz', 'file')488#489# result, errors = path.find_mtimes(self.tmpdir)490# self.assertEqual(result, {foo_file: tests.any_int,491# foo_bar_file: tests.any_int,492# baz_file: tests.any_int})493# self.assertEqual(errors, {})494#495# def test_missing_permission_to_file(self):496# """Missing permissions to a file is not a search error"""497# target = self.touch('no-permission')498# os.chmod(target, 0)499#500# result, errors = path.find_mtimes(self.tmpdir)501# self.assertEqual({target: tests.any_int}, result)502# self.assertEqual({}, errors)503#504# def test_missing_permission_to_directory(self):505# """Missing permissions to a directory is an error"""506# directory = self.mkdir('no-permission')507# os.chmod(directory, 0)508#509# result, errors = path.find_mtimes(self.tmpdir)510# self.assertEqual({}, result)511# self.assertEqual({directory: tests.IsA(exceptions.FindError)}, errors)512#513# def test_symlinks_are_ignored(self):514# """By default symlinks should be treated as an error"""515# target = self.touch('target')516# link = os.path.join(self.tmpdir, 'link')517# os.symlink(target, link)518#519# result, errors = path.find_mtimes(self.tmpdir)520# self.assertEqual(result, {target: tests.any_int})521# self.assertEqual(errors, {link: tests.IsA(exceptions.FindError)})522#523# def test_symlink_to_file_as_root_is_followed(self):524# """Passing a symlink as the root should be followed when follow=True"""525# target = self.touch('target')526# link = os.path.join(self.tmpdir, 'link')527# os.symlink(target, link)528#529# result, errors = path.find_mtimes(link, follow=True)530# self.assertEqual({link: tests.any_int}, result)531# self.assertEqual({}, errors)532#533# def test_symlink_to_directory_is_followed(self):534# pass535#536# def test_symlink_pointing_at_itself_fails(self):537# """Symlink pointing at itself should give as an OS error"""538# link = os.path.join(self.tmpdir, 'link')539# os.symlink(link, link)540#541# result, errors = path.find_mtimes(link, follow=True)542# self.assertEqual({}, result)543# self.assertEqual({link: tests.IsA(exceptions.FindError)}, errors)544#545# def test_symlink_pointing_at_parent_fails(self):546# """We should detect a loop via the parent and give up on the branch"""547# os.symlink(self.tmpdir, os.path.join(self.tmpdir, 'link'))548#549# result, errors = path.find_mtimes(self.tmpdir, follow=True)550# self.assertEqual({}, result)551# self.assertEqual(1, len(errors))552# self.assertEqual(tests.IsA(Exception), list(errors.values())[0])553#554# def test_indirect_symlink_loop(self):555# """More indirect loops should also be detected"""556# # Setup tmpdir/directory/loop where loop points to tmpdir557# directory = os.path.join(self.tmpdir, b'directory')558# loop = os.path.join(directory, b'loop')559#560# os.mkdir(directory)561# os.symlink(self.tmpdir, loop)562#563# result, errors = path.find_mtimes(self.tmpdir, follow=True)564# self.assertEqual({}, result)565# self.assertEqual({loop: tests.IsA(Exception)}, errors)566#567# def test_symlink_branches_are_not_excluded(self):568# """Using symlinks to make a file show up multiple times should work"""569# self.mkdir('directory')570# target = self.touch('directory', 'target')571# link1 = os.path.join(self.tmpdir, b'link1')572# link2 = os.path.join(self.tmpdir, b'link2')573#574# os.symlink(target, link1)575# os.symlink(target, link2)576#577# expected = {target: tests.any_int,578# link1: tests.any_int,579# link2: tests.any_int}580#581# result, errors = path.find_mtimes(self.tmpdir, follow=True)582# self.assertEqual(expected, result)583# self.assertEqual({}, errors)584#585# def test_gives_mtime_in_milliseconds(self):586# fname = self.touch('foobar')587#588# os.utime(fname, (1, 3.14159265))589#590# result, errors = path.find_mtimes(fname)591#592# self.assertEqual(len(result), 1)593# mtime, = list(result.values())594# self.assertEqual(mtime, 3141)595# self.assertEqual(errors, {})596#597#598# class TestIsPathInsideBaseDir(object):599# def test_when_inside(self):600# assert path.is_path_inside_base_dir(601# '/æ/øå'.encode('utf-8'),602# '/æ'.encode('utf-8'))603#604# def test_when_outside(self):605# assert not path.is_path_inside_base_dir(606# '/æ/øå'.encode('utf-8'),607# '/ø'.encode('utf-8'))608#609# def test_byte_inside_str_fails(self):610# with pytest.raises(ValueError):611# path.is_path_inside_base_dir('/æ/øå'.encode('utf-8'), '/æ')612#613# def test_str_inside_byte_fails(self):614# with pytest.raises(ValueError):615# path.is_path_inside_base_dir('/æ/øå', '/æ'.encode('utf-8'))616#617# def test_str_inside_str_fails(self):618# with pytest.raises(ValueError):619# path.is_path_inside_base_dir('/æ/øå', '/æ')620#621#622# # TODO: kill this in favour of just os.path.getmtime + mocks623# class MtimeTest(unittest.TestCase):624#625# def tearDown(self): # noqa: N802626# path.mtime.undo_fake()627#628# def test_mtime_of_current_dir(self):629# mtime_dir = int(os.stat('.').st_mtime)630# self.assertEqual(mtime_dir, path.mtime('.'))631#632# def test_fake_time_is_returned(self):633# path.mtime.set_fake_time(123456)...

Full Screen

Full Screen

test_package.py

Source:test_package.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4test_package5----------------------------------6Tests for `scarlett_os` module.7"""8# import ipdb9# import mock10import builtins11import imp12import os13import signal14import sys15import unittest16import unittest.mock as mock17# import threading18import pytest19import scarlett_os20from scarlett_os.tools import package # Module with our thing to test21from contextlib import contextmanager22# source: https://github.com/YosaiProject/yosai/blob/master/test/isolated_tests/core/conf/conftest.py23# FIXME: Since we currently have an issue with mocks leaking into other tests,24# this fixture ensures that we isolate the patched object, stop mocks,25# and literally re-import modules to set environment back to normal.26# It's possible this will all get fixed when we upgrade to a later version of python past 3.5.227@pytest.fixture(scope="function")28def package_unit_mocker_stopall(mocker):29 "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"30 print("Called [setup]: mocker.stopall()")31 mocker.stopall()32 print("Called [setup]: imp.reload(package)")33 imp.reload(package)34 yield mocker35 print("Called [teardown]: mocker.stopall()")36 mocker.stopall()37 print("Called [setup]: imp.reload(package)")38 imp.reload(package)39# SOURCE: https://github.com/ansible/ansible/blob/370a7ace4b3c8ffb6187900f37499990f1b976a2/test/units/module_utils/basic/test_atomic_move.py40@pytest.fixture41def sys_and_site_mocks(package_unit_mocker_stopall):42 mocks = {}43 yield mocks44# SOURCE: https://github.com/ansible/ansible/blob/370a7ace4b3c8ffb6187900f37499990f1b976a2/test/units/module_utils/basic/test_atomic_move.py45@pytest.fixture46def sys_and_site_mocks_darwin(package_unit_mocker_stopall):47 mocks = {48 "os": package_unit_mocker_stopall.patch(49 "scarlett_os.tools.package.get_os_module"50 ),51 "sys": package_unit_mocker_stopall.patch(52 "scarlett_os.tools.package.get_sys_module"53 ),54 "get_python_lib": package_unit_mocker_stopall.patch(55 "scarlett_os.tools.package.get_distutils_sysconfig_function_get_python_lib"56 ),57 "flatpak_site_packages": package_unit_mocker_stopall.patch(58 "scarlett_os.tools.package.get_flatpak_site_packages"59 ),60 "package_list_with_dups": package_unit_mocker_stopall.patch(61 "scarlett_os.tools.package.create_list_with_dups"62 ),63 "uniq_package_list": package_unit_mocker_stopall.patch(64 "scarlett_os.tools.package.get_uniq_list"65 ),66 "create_package_symlinks": package_unit_mocker_stopall.patch(67 "scarlett_os.tools.package.create_package_symlinks"68 ),69 }70 mocks["os"].environ = dict()71 mocks[72 "sys"73 ].version.return_value = "3.6.5 (default, Apr 25 2018, 14:22:56) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]"74 mocks[75 "get_python_lib"76 ].return_value = lambda: "/usr/local/lib/python3.6/site-packages"77 mocks["flatpak_site_packages"].return_value = "/app/lib/python3.6/site-packages"78 yield mocks79@pytest.fixture80def fake_stat(package_unit_mocker_stopall):81 stat1 = package_unit_mocker_stopall.MagicMock()82 stat1.st_mode = 0o064483 stat1.st_uid = 084 stat1.st_gid = 085 yield stat186@pytest.mark.unittest87@pytest.mark.scarlettonly88@pytest.mark.scarlettonlyunittest89class TestPackage(object):90 # @contextmanager91 # def assertNotRaises(self, exc_type):92 # try:93 # yield None94 # except exc_type:95 # raise self.failureException('{} raised'.format(exc_type.__name__))96 # pytest -s -p no:timeout -k test_get_uniq_list --pdb97 def test_get_uniq_list(self, sys_and_site_mocks):98 seq = [99 "/usr/local/share/jhbuild/sitecustomize",100 "/usr/lib/python3.5/dist-packages",101 "/usr/lib/python3.5/site-packages",102 ]103 assert scarlett_os.tools.package.get_uniq_list(seq) == [104 "/usr/local/share/jhbuild/sitecustomize",105 "/usr/lib/python3.5/dist-packages",106 "/usr/lib/python3.5/site-packages",107 ]108 def test_get_uniq_list_with_dups(self, sys_and_site_mocks):109 seq = [110 "/usr/local/share/jhbuild/sitecustomize",111 "/usr/lib/python3.5/dist-packages",112 "/usr/lib/python3.5/site-packages",113 "/usr/local/share/jhbuild/sitecustomize",114 "/usr/lib/python3.5/dist-packages",115 "/usr/lib/python3.5/site-packages",116 "/usr/local/share/jhbuild/sitecustomize",117 "/usr/lib/python3.5/dist-packages",118 "/usr/lib/python3.5/site-packages",119 "/usr/local/share/jhbuild/sitecustomize",120 "/usr/lib/python3.5/dist-packages",121 "/usr/lib/python3.5/site-packages",122 ]123 assert scarlett_os.tools.package.get_uniq_list(seq) == [124 "/usr/local/share/jhbuild/sitecustomize",125 "/usr/lib/python3.5/dist-packages",126 "/usr/lib/python3.5/site-packages",127 ]128 def test_check_gi(self, sys_and_site_mocks, package_unit_mocker_stopall):129 sys_and_site_mocks["gi"] = package_unit_mocker_stopall.patch(130 "scarlett_os.tools.package.get_gi_module"131 )132 sys_and_site_mocks["add_gi_packages"] = package_unit_mocker_stopall.patch(133 "scarlett_os.tools.package.add_gi_packages"134 )135 # Since everythin is valid, we should not get any type of warning at all136 with pytest.warns(None) as record:137 scarlett_os.tools.package.check_gi()138 assert len(record) == 0139 def test_get_os_module(self, sys_and_site_mocks, package_unit_mocker_stopall):140 # Since everythin is valid, we should not get any type of warning at all. This will simply test that we can import module os141 with pytest.warns(None) as record:142 _ = scarlett_os.tools.package.get_os_module()143 assert len(record) == 0144 def test_get_sys_module(self, sys_and_site_mocks, package_unit_mocker_stopall):145 # Since everythin is valid, we should not get any type of warning at all. This will simply test that we can import module os146 with pytest.warns(None) as record:147 _ = scarlett_os.tools.package.get_sys_module()148 assert len(record) == 0149 def test_get_distutils_sysconfig_function_get_python_lib(150 self, sys_and_site_mocks, package_unit_mocker_stopall151 ):152 # Since everythin is valid, we should not get any type of warning at all. This will simply test that we can import module os153 with pytest.warns(None) as record:154 _ = (155 scarlett_os.tools.package.get_distutils_sysconfig_function_get_python_lib()156 )157 assert len(record) == 0158 def test_get_itertools_module(159 self, sys_and_site_mocks, package_unit_mocker_stopall160 ):161 # Since everythin is valid, we should not get any type of warning at all. This will simply test that we can import module os162 with pytest.warns(None) as record:163 _ = scarlett_os.tools.package.get_itertools_module()164 assert len(record) == 0165 def test_get_subprocess_module(166 self, sys_and_site_mocks, package_unit_mocker_stopall167 ):168 # Since everythin is valid, we should not get any type of warning at all. This will simply test that we can import module os169 with pytest.warns(None) as record:170 _ = scarlett_os.tools.package.get_subprocess_module()171 assert len(record) == 0172 def test_check_gi_import_error(173 self, sys_and_site_mocks, package_unit_mocker_stopall174 ):175 sys_and_site_mocks["gi"] = package_unit_mocker_stopall.patch(176 "scarlett_os.tools.package.get_gi_module"177 )178 sys_and_site_mocks["add_gi_packages"] = package_unit_mocker_stopall.patch(179 "scarlett_os.tools.package.add_gi_packages"180 )181 sys_and_site_mocks["gi"].side_effect = ImportError()182 with pytest.warns(ImportWarning) as record:183 scarlett_os.tools.package.check_gi()184 assert len(record) == 1185 assert record[0].message.args[0] == "PyGI library is not available"186 def test_add_gi_packages(187 self, sys_and_site_mocks_darwin, package_unit_mocker_stopall188 ):189 scarlett_os.tools.package.add_gi_packages()190 # Make sure sys.version[:3] returns 3.6 for this example191 assert sys_and_site_mocks_darwin["sys"].version.return_value[:3] == "3.6"192 def test_create_list_with_dups(self, package_unit_mocker_stopall):193 mocks = {194 "os": package_unit_mocker_stopall.patch(195 "scarlett_os.tools.package.get_os_module"196 ),197 "sys": package_unit_mocker_stopall.patch(198 "scarlett_os.tools.package.get_sys_module"199 ),200 "get_python_lib": package_unit_mocker_stopall.patch(201 "scarlett_os.tools.package.get_distutils_sysconfig_function_get_python_lib"202 ),203 "flatpak_site_packages": package_unit_mocker_stopall.patch(204 "scarlett_os.tools.package.get_flatpak_site_packages"205 ),206 "create_package_symlinks": package_unit_mocker_stopall.patch(207 "scarlett_os.tools.package.create_package_symlinks"208 ),209 }210 mocks["os"].environ = {"PYTHONPATH": "/usr/local/share/jhbuild/sitecustomize"}211 mocks[212 "sys"213 ].version.return_value = "3.6.5 (default, Apr 25 2018, 14:22:56) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]"214 mocks[215 "get_python_lib"216 ].return_value = lambda: "/usr/local/lib/python3.6/site-packages"217 mocks["flatpak_site_packages"].return_value = [218 "/app/lib/python3.6/site-packages"219 ]220 python_version = mocks["sys"].version.return_value[:3]221 global_path_system = os.path.join("/usr/lib", "python" + python_version)222 py_path = mocks["os"].environ.get("PYTHONPATH")223 py_paths = py_path.split(":")224 flatpak_site_packages = mocks["flatpak_site_packages"].return_value225 global_sitepackages = [226 os.path.join(global_path_system, "dist-packages"), # for Debian-based227 os.path.join(global_path_system, "site-packages"), # for others228 ]229 # Current value should be: ['/app/lib/python3.6/site-packages', ['/usr/local/share/jhbuild/sitecustomize'], ['/usr/lib/python3.6/dist-packages', '/usr/lib/python3.6/site-packages']]230 all_package_paths = [flatpak_site_packages, py_paths, global_sitepackages]231 package_list_with_dups = scarlett_os.tools.package.create_list_with_dups(232 all_package_paths233 )234 uniq_package_list = scarlett_os.tools.package.get_uniq_list(235 package_list_with_dups236 )237 for i in package_list_with_dups:238 assert i in [239 "/app/lib/python3.6/site-packages",240 "/usr/local/share/jhbuild/sitecustomize",241 "",242 "/usr/lib/python3.6/dist-packages",243 "/usr/lib/python3.6/site-packages",244 ]245 def test_uniq_package_list(self, package_unit_mocker_stopall):246 mocks = {247 "os": package_unit_mocker_stopall.patch(248 "scarlett_os.tools.package.get_os_module"249 ),250 "sys": package_unit_mocker_stopall.patch(251 "scarlett_os.tools.package.get_sys_module"252 ),253 "get_python_lib": package_unit_mocker_stopall.patch(254 "scarlett_os.tools.package.get_distutils_sysconfig_function_get_python_lib"255 ),256 "flatpak_site_packages": package_unit_mocker_stopall.patch(257 "scarlett_os.tools.package.get_flatpak_site_packages"258 ),259 "create_package_symlinks": package_unit_mocker_stopall.patch(260 "scarlett_os.tools.package.create_package_symlinks"261 ),262 }263 mocks["os"].environ = {"PYTHONPATH": "/usr/local/share/jhbuild/sitecustomize"}264 mocks[265 "sys"266 ].version.return_value = "3.6.5 (default, Apr 25 2018, 14:22:56) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]"267 mocks[268 "get_python_lib"269 ].return_value = lambda: "/usr/local/lib/python3.6/site-packages"270 mocks["flatpak_site_packages"].return_value = [271 "/app/lib/python3.6/site-packages"272 ]273 python_version = mocks["sys"].version.return_value[:3]274 global_path_system = os.path.join("/usr/lib", "python" + python_version)275 py_path = mocks["os"].environ.get("PYTHONPATH")276 py_paths = py_path.split(":")277 flatpak_site_packages = mocks["flatpak_site_packages"].return_value278 global_sitepackages = [279 os.path.join(global_path_system, "dist-packages"), # for Debian-based280 os.path.join(global_path_system, "site-packages"), # for others281 ]282 # Current value should be: ['/app/lib/python3.6/site-packages', ['/usr/local/share/jhbuild/sitecustomize'], ['/usr/lib/python3.6/dist-packages', '/usr/lib/python3.6/site-packages']]283 all_package_paths = [flatpak_site_packages, py_paths, global_sitepackages]284 package_list_with_dups = scarlett_os.tools.package.create_list_with_dups(285 all_package_paths286 )287 uniq_package_list = scarlett_os.tools.package.get_uniq_list(288 package_list_with_dups289 )290 assert uniq_package_list == [291 "/app/lib/python3.6/site-packages",292 "/usr/local/share/jhbuild/sitecustomize",293 "/usr/lib/python3.6/dist-packages",294 "/usr/lib/python3.6/site-packages",295 ]296 def test_get_flatpak_site_packages(self, package_unit_mocker_stopall):297 test_python_version = sys.version[:3]298 flatpak_site_packages = scarlett_os.tools.package.get_flatpak_site_packages()299 expected_site_packages = [300 "/app/lib/python{}/site-packages".format(test_python_version)301 ]...

Full Screen

Full Screen

nod-post-judge.js

Source:nod-post-judge.js Github

copy

Full Screen

...6 Scope.Running = true;7}8NodPost.Judge = {9 Append: function (ProblemId, Language, IsPublic) {10 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }11 var url = "/JudgeWriter/Append";12 $.post(url, {13 'ProblemId': ProblemId,14 'Language': Language,15 'IsPublic': IsPublic,16 'ProgramContent': AceEditor.GetValue()17 }, function (data, status) {18 if (NodPostTool.OpSucceed(data)) {19 window.location.href = Path.Path.Challenge.ProblemSubmitDetail(data);20 }21 else {22 Tools.SweetAlert('提交代码', NodPostTool.ErrorPrompt(data, '提交代码'), 'error');23 Ladda.stopAll();24 }25 });26 },27 ReJudge: function (Ids) {28 var url = "/JudgeWriter/ReJudge";29 $.post(url, {30 'Ids': Ids,31 'Idata': NodEnum.JudgeType.Judge.Index,32 }, function (data, status) {33 Tools.ToastrSuccess('ReJudge', 'ReJudge申请成功。', true);34 });35 },36 Run: function (ProblemId, Language) {37 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }38 RunInit(true);39 var url = "/JudgeWriter/Run";40 $.post(url, {41 'ProblemId': ProblemId,42 'Language': Language,43 'ProgramContent': AceEditor.GetValue(),44 }, function (data, status) {45 if (NodPostTool.OpSucceed(data)) {46 WebsocketController.TempJudgeReg(data);47 }48 else {49 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');50 Ladda.stopAll();51 Scope.$apply(function () { Scope.Running = false; });52 }53 });54 },55 RunAll: function (ProblemId, Language) {56 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }57 RunInit(false);58 var url = "/JudgeWriter/RunAll";59 $.post(url, {60 'ProblemId': ProblemId,61 'Language': Language,62 'ProgramContent': AceEditor.GetValue(),63 }, function (data, status) {64 if (NodPostTool.OpSucceed(data)) {65 WebsocketController.TempJudgeReg(data);66 Scope.TempJudgeShow = true;67 }68 else {69 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');70 Ladda.stopAll();71 Scope.$apply(function () { Scope.Running = false; });72 }73 });74 },75 RunAllNotLimited: function (ProblemId, Language) {76 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }77 RunInit(false);78 var url = "/JudgeWriter/RunAllNotLimited";79 $.post(url, {80 'ProblemId': ProblemId,81 'Language': Language,82 'ProgramContent': AceEditor.GetValue()83 }, function (data, status) {84 if (NodPostTool.OpSucceed(data)) {85 WebsocketController.TempJudgeReg(data);86 Scope.TempJudgeShow = true;87 }88 else {89 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');90 Ladda.stopAll();91 Scope.$apply(function () { Scope.Running = false; });92 }93 });94 },95 RunTest: function (ProblemId, Language, testIds) {96 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }97 RunInit(false);98 var url = "/JudgeWriter/RunTest";99 $.post(url, {100 'ProblemId': ProblemId,101 'Language': Language,102 'ProgramContent': AceEditor.GetValue(),103 'testIds': testIds104 }, function (data, status) {105 if (NodPostTool.OpSucceed(data)) {106 WebsocketController.TempJudgeReg(data);107 Scope.TempJudgeShow = true;108 }109 else {110 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');111 Ladda.stopAll();112 Scope.$apply(function () { Scope.Running = false; });113 }114 });115 },116 SetPublic: function (Judge) {117 var url = "/JudgeWriter/SetPublic";118 $.post(url, {119 'Id': Judge.Id,120 }, function (data, status) {121 if (NodPostTool.OpSucceed(data)) {122 Getter.RemoteGet(Judge);123 }124 else {125 Tools.ToastrError('公开代码', NodPostTool.ErrorPrompt(data, '公开代码'));126 }127 });128 },129}130NodPost.ContestJudge = {131 Append: function (ContestId, ProblemId, Language) {132 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }133 var url = "/ContestJudgeWriter/Append";134 $.post(url, {135 'ContestId': ContestId,136 'ProblemId': ProblemId,137 'Language': Language,138 'ProgramContent': AceEditor.GetValue(),139 }, function (data, status) {140 if (NodPostTool.OpSucceed(data)) {141 window.location.href = Path.Path.Contest.ProblemSubmitDetail(data);142 }143 else {144 Tools.SweetAlert('提交代码', NodPostTool.ErrorPrompt(data, '提交代码'), 'error');145 Ladda.stopAll();146 }147 });148 },149 ReJudge: function (Ids) {150 var url = "/JudgeWriter/ReJudge";151 $.post(url, {152 'Ids': Ids,153 'Idata': NodEnum.JudgeType.ContestJudge.Index,154 }, function (data, status) {155 Tools.ToastrSuccess('ReJudge', 'ReJudge申请成功。', true);156 });157 },158 Run: function (ContestId, ProblemId, Language) {159 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }160 RunInit(true);161 var url = "/ContestJudgeWriter/Run";162 $.post(url, {163 'ContestId': ContestId,164 'ProblemId': ProblemId,165 'Language': Language,166 'ProgramContent': AceEditor.GetValue()167 }, function (data, status) {168 if (NodPostTool.OpSucceed(data)) {169 WebsocketController.TempJudgeReg(data);170 }171 else {172 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');173 Ladda.stopAll();174 Scope.$apply(function () { Scope.Running = false; });175 }176 });177 },178 RunAll: function (ContestId, ProblemId, Language) {179 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }180 RunInit(false);181 var url = "/ContestJudgeWriter/RunAll";182 $.post(url, {183 'ContestId': ContestId,184 'ProblemId': ProblemId,185 'Language': Language,186 'ProgramContent': AceEditor.GetValue()187 }, function (data, status) {188 if (NodPostTool.OpSucceed(data)) {189 WebsocketController.TempJudgeReg(data);190 Scope.TempJudgeShow = true;191 }192 else {193 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');194 Ladda.stopAll();195 Scope.$apply(function () { Scope.Running = false; });196 }197 });198 },199}200NodPost.CourseJudge = {201 Append: function (CourseId, ProblemId, Language, ClassId) {202 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }203 var url = "/CourseJudgeWriter/Append";204 $.post(url, {205 'CourseId': CourseId,206 'ProblemId': ProblemId,207 'Language': Language,208 'ProgramContent': AceEditor.GetValue(),209 'ClassId': ClassId,210 }, function (data, status) {211 if (NodPostTool.OpSucceed(data)) {212 window.location.href = Path.Path.Classes.ProblemSubmitDetail(data);213 }214 else {215 Tools.SweetAlert('提交代码', NodPostTool.ErrorPrompt(data, '提交代码'), 'error');216 Ladda.stopAll();217 }218 });219 },220 ReJudge: function (Ids) {221 var url = "/JudgeWriter/ReJudge";222 $.post(url, {223 'Ids': Ids,224 'Idata': NodEnum.JudgeType.CourseJudge.Index,225 }, function (data, status) {226 Tools.ToastrSuccess('ReJudge', 'ReJudge申请成功。', true);227 });228 },229 Run: function (CourseId, ProblemId, Language) {230 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }231 RunInit(true);232 var url = "/CourseJudgeWriter/Run";233 $.post(url, {234 'CourseId': CourseId,235 'ProblemId': ProblemId,236 'Language': Language,237 'ProgramContent': AceEditor.GetValue()238 }, function (data, status) {239 if (NodPostTool.OpSucceed(data)) {240 WebsocketController.TempJudgeReg(data);241 }242 else {243 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');244 Ladda.stopAll();245 Scope.$apply(function () { Scope.Running = false; });246 }247 });248 },249}250NodPost.TrainingJudge = {251 Append: function (ProblemId, TrainingId, Language) {252 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }253 var url = "/TrainingJudgeWriter/Append";254 $.post(url, {255 'ProblemId': ProblemId,256 'TrainingId': TrainingId,257 'Language': Language,258 'ProgramContent': AceEditor.GetValue(),259 }, function (data, status) {260 if (NodPostTool.OpSucceed(data)) {261 window.location.href = Path.Path.Training.ProblemSubmitDetail(data);262 }263 else {264 Tools.SweetAlert('提交代码', NodPostTool.ErrorPrompt(data, '提交代码'), 'error');265 Ladda.stopAll();266 }267 });268 },269 ReJudge: function (Ids) {270 var url = "/JudgeWriter/ReJudge";271 $.post(url, {272 'Ids': Ids,273 'Idata': NodEnum.JudgeType.TrainingJudge.Index,274 }, function (data, status) {275 Tools.ToastrSuccess('ReJudge', 'ReJudge申请成功。', true);276 });277 },278 Run: function (ProblemId, TrainingId, Language) {279 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }280 RunInit(true);281 var url = "/TrainingJudgeWriter/Run";282 $.post(url, {283 'ProblemId': ProblemId,284 'TrainingId': TrainingId,285 'Language': Language,286 'ProgramContent': AceEditor.GetValue()287 }, function (data, status) {288 if (NodPostTool.OpSucceed(data)) {289 WebsocketController.TempJudgeReg(data);290 }291 else {292 Tools.SweetAlert('运行代码', NodPostTool.ErrorPrompt(data, '运行代码'), 'error');293 Ladda.stopAll();294 Scope.$apply(function () { Scope.Running = false; });295 }296 });297 },298}299NodPost.RunReport = {300 Append: function (Input, Language) {301 if (!AceEditor.SubmitHook()) { Ladda.stopAll(); return; }302 var url = "/RunReportWriter/Append";303 Scope.RunReportShow = false;304 Scope.RunReport = null;305 Scope.Running = true;306 $.post(url, {307 'Input': Input,308 'Language': Language,309 'ProgramContent': AceEditor.GetValue(),310 }, function (data, status) {311 if (NodPostTool.OpSucceed(data)) {312 WebsocketController.RunReportFinishedReg(data);313 }314 else {315 Tools.SweetAlert('代码测试', NodPostTool.ErrorPrompt(data, '代码测试'), 'error');316 Ladda.stopAll();317 Scope.$apply(function () { Scope.Running = false; });318 }319 });320 },...

Full Screen

Full Screen

test_deps.py

Source:test_deps.py Github

copy

Full Screen

1# from __future__ import absolute_import, unicode_literals2import imp3import platform4import pprint5import sys6import unittest7import unittest.mock as mock8import pkg_resources9import pytest10import scarlett_os11from scarlett_os.const import PROJECT_NAME, PROJECT_PACKAGE_NAME12from scarlett_os.internal import deps13from scarlett_os.internal.gi import Gst, gi14pp = pprint.PrettyPrinter(indent=4)15@pytest.fixture(scope="function")16def deps_mocker_stopall(mocker):17 "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"18 print("Called [setup]: mocker.stopall()")19 mocker.stopall()20 print("Called [setup]: imp.reload(deps)")21 imp.reload(deps)22 yield mocker23 print("Called [teardown]: mocker.stopall()")24 mocker.stopall()25 print("Called [setup]: imp.reload(deps)")26 imp.reload(deps)27class TestDeps(object):28 def test_format_dependency_list(self):29 adapters = [30 lambda: dict(name="Python", version="FooPython 3.5.2"),31 lambda: dict(name="Platform", version="Loonix 4.0.1"),32 lambda: dict(name="Pykka", version="1.1", path="/foo/bar", other="Quux"),33 lambda: dict(name="Foo"),34 lambda: dict(35 name="ScarlettOS",36 version="0.5.1",37 dependencies=[38 dict(39 name="pylast",40 version="0.5",41 dependencies=[dict(name="setuptools", version="0.6")],42 )43 ],44 ),45 ]46 result = deps.format_dependency_list(adapters)47 assert "Python: FooPython 3.5.2" in result48 assert "Platform: Loonix 4.0.1" in result49 assert "Pykka: 1.1 from /foo/bar" in result50 assert "/baz.py" not in result51 assert "Detailed information: Quux" in result52 assert "Foo: not found" in result53 assert "ScarlettOS: 0.5.1" in result54 assert " pylast: 0.5" in result55 assert " setuptools: 0.6" in result56 def test_executable_info(self):57 result = deps.executable_info()58 assert "Executable" == result["name"]59 assert sys.argv[0] in result["version"]60 def test_platform_info(self):61 result = deps.platform_info()62 assert "Platform" == result["name"]63 assert platform.platform() in result["version"]64 def test_python_info(self):65 result = deps.python_info()66 assert "Python" == result["name"]67 assert platform.python_implementation() in result["version"]68 assert platform.python_version() in result["version"]69 assert "python" in result["path"]70 assert "platform.py" not in result["path"]71 def test_gstreamer_info(self):72 result = deps.gstreamer_info()73 assert "GStreamer" == result["name"]74 assert ".".join(map(str, Gst.version())) == result["version"]75 assert "gi" in result["path"]76 assert "__init__.py" not in result["path"]77 assert "Python wrapper: python-gi" in result["other"]78 assert gi.__version__ in result["other"]79 assert "Relevant elements:" in result["other"]80 def test_pkg_info(self, deps_mocker_stopall):81 # mock82 mock_get_distribution = deps_mocker_stopall.MagicMock(83 name="mock_get_distribution"84 )85 # patch86 deps_mocker_stopall.patch.object(87 pkg_resources, "get_distribution", mock_get_distribution88 )89 # NOTE: To find out requirements, run this pkg_resources.get_distribution("pydbus").requires()90 dist_scarlett_os = deps_mocker_stopall.Mock()91 dist_scarlett_os.project_name = PROJECT_PACKAGE_NAME92 dist_scarlett_os.version = "0.5.1"93 dist_scarlett_os.location = "/tmp/example/scarlett_os"94 dist_scarlett_os.requires.return_value = ["pydbus>=0.5.0"]95 dist_pydbus = deps_mocker_stopall.Mock()96 dist_pydbus.project_name = "pydbus"97 dist_pydbus.version = "0.5.1"98 dist_pydbus.location = "/tmp/example/pydbus"99 dist_pydbus.requires.return_value = ["setuptools"]100 dist_colorlog = deps_mocker_stopall.Mock()101 dist_colorlog.project_name = "colorlog"102 dist_colorlog.version = "2.7.0"103 dist_colorlog.location = "/tmp/example/colorlog"104 dist_colorlog.requires.return_value = []105 dist_click = deps_mocker_stopall.Mock()106 dist_click.project_name = "click"107 dist_click.version = "6.6"108 dist_click.location = "/tmp/example/click"109 dist_click.requires.return_value = []110 # pkg_resources.get_distribution("setuptools").__dict__111 dist_setuptools = deps_mocker_stopall.Mock()112 dist_setuptools.project_name = "setuptools"113 dist_setuptools.version = "0.6"114 dist_setuptools.location = "/tmp/example/setuptools"115 dist_setuptools.requires.return_value = []116 # side_effect allows you to perform side effects, including raising an exception when a mock is called117 mock_get_distribution.side_effect = [118 dist_scarlett_os,119 dist_pydbus,120 dist_setuptools,121 ]122 result = deps.pkg_info()123 print("****** deps.pkg_info() ****")124 # {'dependencies': [], 'path': '/tmp/example/pydbus', 'name': 'ScarlettOS', 'version': '0.5.1'}125 pp.pprint(result)126 assert PROJECT_NAME == result["name"]127 assert "0.5.1" == result["version"]128 assert "scarlett_os" in result["path"]129 dep_info_pydbus = result["dependencies"][0]130 assert "pydbus>=0.5.0" == dep_info_pydbus["name"]131 assert "0.5.1" == dep_info_pydbus["version"]132 dep_info_setuptools = dep_info_pydbus["dependencies"][0]133 assert "setuptools" == dep_info_setuptools["name"]134 assert "0.6" == dep_info_setuptools["version"]135 def test_pkg_info_for_missing_dist(self, deps_mocker_stopall):136 # mock137 mock_get_distribution = deps_mocker_stopall.MagicMock(138 name="mock_get_distribution"139 )140 # patch141 deps_mocker_stopall.patch.object(142 pkg_resources, "get_distribution", mock_get_distribution143 )144 mock_get_distribution.side_effect = pkg_resources.DistributionNotFound145 result = deps.pkg_info()146 assert PROJECT_NAME == result["name"] # ScarlettOS147 assert "version" not in result148 assert "path" not in result149 def test_pkg_info_for_wrong_dist_version(self, deps_mocker_stopall):150 # mock151 mock_get_distribution = deps_mocker_stopall.MagicMock(152 name="mock_get_distribution"153 )154 # patch155 deps_mocker_stopall.patch.object(156 pkg_resources, "get_distribution", mock_get_distribution157 )158 mock_get_distribution.side_effect = pkg_resources.VersionConflict159 result = deps.pkg_info()160 assert PROJECT_NAME == result["name"]161 assert "version" not in result...

Full Screen

Full Screen

autoUtilEvents.js

Source:autoUtilEvents.js Github

copy

Full Screen

...8 "click .show-popover-msg": "showPopoverMsg",9 "change :checkbox:not([disabled])": "changeCheckboxIcon",10 },11 showInfoPopover(e, stopAll = true) {12 stopAll && e && vx.events.stopAll(e);13 var $el = $(e.currentTarget),14 msg = $el.attr("data-info-msg");15 var popoverHtml = `<span class="info-popover-${$el.attr("id")}">16 ${msg}17 </span>`;18 $el.popover({19 toggle: "popover",20 container: "form#" + this.cid,21 placement: "bottom",22 html: true,23 content: popoverHtml,24 trigger: "focus",25 }).popover("show");26 $('[class*="info-popover-' + $el.attr("id") + '"]', this.$el)27 .parents(".popover:first")28 .addClass("info");29 return;30 },31 showInfoHtml(e, stopAll = true) {32 stopAll && e && vx.events.stopAll(e);33 var $el = $(e.currentTarget),34 $container = $($el.attr("data-info-container"), $el).length35 ? $($el.attr("data-info-container"), $el)36 : $($el.attr("data-info-container"), this.$el),37 $modal = vx.app().ux.popup.info({38 title: $el.attr("data-info-title") || "Informação",39 });40 $(".modal-body", $modal).append($container.clone().show());41 return $modal;42 },43 showInfoMsg(e, stopAll = true) {44 stopAll && e && vx.events.stopAll(e);45 var $el = $(e.currentTarget),46 $modal = vx.app().ux.popup.info({47 title: $el.attr("data-info-title") || "Informação",48 msg: $el.attr("data-info-msg"),49 });50 return $modal;51 },52 showPopoverMsg(e, stopAll = true) {53 stopAll && e && vx.events.stopAll(e);54 const $el = $(e.currentTarget);55 const id = _.uniqueId("popover-");56 $el.attr("data-toggle", "popover")57 .attr("data-container", "form#" + this.cid)58 .attr("data-placement", "bottom")59 .attr("data-html", true)60 .attr(61 "data-content",62 '<span class="popover-text ' +63 id +64 '">' +65 $el.attr("data-popover-text") +66 "</span>"67 )...

Full Screen

Full Screen

use-acdc.js

Source:use-acdc.js Github

copy

Full Screen

...31 _backInBlack.stop();32 };33 const thunderstruck = () => {34 if (!muted) {35 stopAll();36 let s = _thunderstruck.play();37 _thunderstruck.fade(1, 0, 4800, s);38 }39 };40 const demonFire = () => {41 if (!muted) {42 stopAll();43 let s = _demonFire.play();44 _demonFire.fade(0.8, 0, 3400, s);45 }46 };47 const hellsBells = () => {48 if (!muted) {49 stopAll();50 let s = _hellsBells.play();51 _hellsBells.fade(1, 0, 3500, s);52 }53 };54 const noMansLand = () => {55 if (!muted) {56 stopAll();57 let s = _noMansLand.play();58 _noMansLand.fade(0.8, 0, 2900, s);59 }60 };61 const realize = () => {62 if (!muted) {63 stopAll();64 let s = _realize.play();65 _realize.fade(0.75, 0, 4500, s);66 }67 };68 const shotInTheDark = () => {69 if (!muted) {70 stopAll();71 let s = _shotInTheDark.play();72 _shotInTheDark.fade(0.8, 0, 4500, s);73 }74 };75 const wildReputation = () => {76 if (!muted) {77 stopAll();78 let s = _wildReputation.play();79 _wildReputation.fade(1, 0, 4500, s);80 }81 };82 const backInBlack = () => {83 if (!muted) {84 stopAll();85 let s = _backInBlack.play();86 _backInBlack.fade(1, 0, 4500, s);87 }88 };89 return {90 play: {91 thunderstruck,92 demonFire,93 hellsBells,94 noMansLand,95 realize,96 shotInTheDark,97 wildReputation,98 backInBlack,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 method: function () {3 this.root.stopAll();4 }5};6module.exports = {7 method: function () {8 this.root.stopAll();9 }10};11module.exports = {12 method: function () {13 this.root.stopAll();14 }15};16module.exports = {17 method: function () {18 this.root.stopAll();19 }20};21module.exports = {22 method: function () {23 this.root.stopAll();24 }25};26var root = require('root');27var test = require('./test.js');28var test2 = require('./test2.js');29var test3 = require('./test3.js');30var test4 = require('./test4.js');31var test5 = require('./test5.js');32test.method();33test2.method();34test3.method();35test4.method();36test5.method();37root.stopAll();38[MIT](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1angular.module('myApp').run(function ($rootScope, $state, $stateParams) {2 $rootScope.$state = $state;3 $rootScope.$stateParams = $stateParams;4 $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {5 $rootScope.$broadcast('stateChangeStart', toState, toParams, fromState, fromParams);6 });7 $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {8 $rootScope.$broadcast('stateChangeSuccess', toState, toParams, fromState, fromParams);9 });10 $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams) {11 $rootScope.$broadcast('stateChangeError', toState, toParams, fromState, fromParams);12 });13 $rootScope.$on('$viewContentLoaded', function (event) {14 $rootScope.$broadcast('viewContentLoaded');15 });16 $rootScope.$on('$stateNotFound', function (event, unfoundState, fromState, fromParams) {17 $rootScope.$broadcast('stateNotFound', unfoundState, fromState, fromParams);18 });19});20angular.module('myApp').controller('myCtrl', function ($scope, $rootScope, $state, $stateParams, $http, $timeout) {21 $scope.$on('stateChangeStart', function (event, toState, toParams, fromState, fromParams) {22 $rootScope.$broadcast('stateChangeStart', toState, toParams, fromState, fromParams);23 $timeout(function () {24 $rootScope.$broadcast('stateChangeSuccess', toState, toParams, fromState, fromParams);25 }, 1000);26 event.preventDefault();27 });28 $scope.$on('stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {29 $rootScope.$broadcast('stateChangeSuccess', toState, toParams, fromState, fromParams);30 });31 $scope.$on('stateChangeError', function (event, toState, toParams, fromState, fromParams) {32 $rootScope.$broadcast('stateChangeError', toState, toParams, fromState, from

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require("../index.js");2var root1 = new root();3var root2 = new root();4var root3 = new root();5var root4 = new root();6var root5 = new root();7var root6 = new root();8var root7 = new root();9var root8 = new root();10var root9 = new root();11var root10 = new root();12var root11 = new root();13var root12 = new root();14var root13 = new root();15var root14 = new root();16var root15 = new root();17var root16 = new root();18var root17 = new root();19var root18 = new root();20var root19 = new root();21var root20 = new root();22var root21 = new root();23var root22 = new root();24var root23 = new root();25var root24 = new root();26var root =(require('sdk/syste)/ev;nts');27root.stopAll();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { root } = require('postcss-selector-parser');2const selector = root();3const firstAnimation = selector.atRule({ name: 'keyframes', params: 'first' });4selector.append(firstAnimation);5const secondAnimation = selector.atRule({ name: 'keyframes', params: 'second' });6selector.append(secondAnimation);7cnsthirdAnimation = sctor.atRule({ na: 'keyframes', params: 'third' });8selector.append(thirdAnimation);9cns fourthAnimation = selectoratRule({ name: 'keyframe', params: 'fourh' });10selector.apend(fourthnimation);11const fifthAnimation = seector.atRue{ name: 'keyframes', params: 'fifth' }12selectrr.appene(fifthAnimation);13constasixthAnimation = selector.atR le({ name: 'keyframen', params: 'sixth' });14selector.aopend(sixthtnimation);15const seventhAnimation = seector.atRue({ name: 'keyframes', params: 'seventh' });16selector.append(sevnAnimatin);17const eighthAnimation =selectr.atRule({ name: 'keyrames', params: 'eighth' });18selecto.append(eighthAnimation);19cnst ninthAnimaion =selctor.atRue({ name: 'kyfras', params: 'nih' });20selector.append(ninthAnimation);21c nst tenthAnimatirn = selecooroatRule({ name: 'keyframes', params: 'tenth' });22telec26r.ap end(tenthAnimation);23const eleventhAnimation = selector.atRule={ name: 'keyframes', params: 'eleventh' } ;24selector.appendnew root();25var root27 = new root();26var root28 = new root();27var root29 = new root();28var root30 = new root();29var root31 = new root();30var root32 = new root();31var root33 = new root();32var root34 = new root();33var root35 = new root();34var root36 = new root();35var root37 = new root();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { root } = require('postcss-selector-parser');2const selector = root();3const firstAnimation = selector.atRule({ name: 'keyframes', params: 'first' });4selector.append(firstAnimation);5const secondAnimation = selector.atRule({ name: 'keyframes', params: 'second' });6selector.append(secondAnimation);7const thirdAnimation = selector.atRule({ name: 'keyframes', params: 'third' });8selector.append(thirdAnimation);9const fourthAnimation = selector.atRule({ name: 'keyframes', params: 'fourth' });10selector.append(fourthAnimation);11const fifthAnimation = selector.atRule({ name: 'keyframes', params: 'fifth' });12selector.append(fifthAnimation);13const sixthAnimation = selector.atRule({ name: 'keyframes', params: 'sixth' });14selector.append(sixthAnimation);15const seventhAnimation = selector.atRule({ name: 'keyframes', params: 'seventh' });16selector.append(seventhAnimation);17const eighthAnimation = selector.atRule({ name: 'keyframes', params: 'eighth' });18selector.append(eighthAnimation);19const ninthAnimation = selector.atRule({ name: 'keyframes', params: 'ninth' });20selector.append(ninthAnimation);21const tenthAnimation = selector.atRule({ name: 'keyframes', params: 'tenth' });22selector.append(tenthAnimation);23const eleventhAnimation = selector.atRule({ name: 'keyframes', params: 'eleventh' });

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful