Best Python code snippet using lisa_python
console.py
Source:console.py
...74 expected[test] = ''75 else:76 expected[test] += line + '\n'77 return expected78def _execute(func, strip_trailing_space=True, input=None):79 _in = sys.stdin80 _err = sys.stderr81 _out = sys.stdout82 try:83 if input:84 sys.stdin = StringIO(input.encode('utf-8'))85 sys.stdin.encoding = 'utf-8' # fake input encoding86 sys.stderr = sys.stdout = out = StringIO()87 out.encoding = 'utf-8' # fake output encoding88 retval = func()89 value = out.getvalue()90 if isinstance(value, str): # reverse what print_listing did91 value = value.decode('utf-8')92 if strip_trailing_space:93 return retval, STRIP_TRAILING_SPACE.sub('', value)94 else:95 return retval, value96 finally:97 sys.stdin = _in98 sys.stderr = _err99 sys.stdout = _out100def execute_cmd(tracadmin, cmd, strip_trailing_space=True, input=None):101 def func():102 try:103 return tracadmin.onecmd(cmd)104 except SystemExit:105 return None106 return _execute(func, strip_trailing_space, input)107def execute_run(args):108 def func():109 try:110 return _run(args)111 except SystemExit:112 return None113 return _execute(func)114class TracAdminTestCaseBase(unittest.TestCase):115 expected_results_file = os.path.join(os.path.dirname(__file__),116 'console-tests.txt')117 expected_results = load_expected_results(expected_results_file,118 '===== (test_[^ ]+) =====')119 def _execute(self, cmd, strip_trailing_space=True, input=None):120 return execute_cmd(self._admin, cmd,121 strip_trailing_space=strip_trailing_space,122 input=input)123 def assertExpectedResult(self, output, args=None):124 test_name = inspect.stack()[1][3]125 expected_result = self.expected_results[test_name]126 if args is not None:127 expected_result %= args128 self.assertEqual(expected_result, output)129 def assertEqual(self, expected_results, output, msg=None):130 """:deprecated: since 1.0.2, use `assertExpectedResult` instead."""131 if not (isinstance(expected_results, basestring) and132 isinstance(output, basestring)):133 return unittest.TestCase.assertEqual(self, expected_results,134 output, msg)135 def diff():136 # Create a useful delta between the output and the expected output137 output_lines = ['%s\n' % x for x in output.split('\n')]138 expected_lines = ['%s\n' % x for x in expected_results.split('\n')]139 return ''.join(difflib.unified_diff(expected_lines, output_lines,140 'expected', 'actual'))141 if '[...]' in expected_results:142 m = re.match('.*'.join(map(re.escape,143 expected_results.split('[...]'))) +144 '\Z',145 output, re.DOTALL)146 unittest.TestCase.assertTrue(self, m,147 "%r != %r\n%s" % (expected_results,148 output, diff()))149 else:150 unittest.TestCase.assertEqual(self, expected_results, output,151 "%r != %r\n%s" % (expected_results,152 output, diff()))153class TracadminTestCase(TracAdminTestCaseBase):154 """155 Tests the output of trac-admin and is meant to be used with156 .../trac/tests.py.157 """158 def setUp(self):159 self.env = EnvironmentStub(default_data=True, enable=('trac.*',),160 disable=('trac.tests.*',))161 self._admin = TracAdmin()162 self._admin.env_set('', self.env)163 self.environ = os.environ.copy()164 # Set test date to 11th Jan 2004165 self._test_date = '2004-01-11'166 def tearDown(self):167 self.env = None168 for name in set(os.environ) - set(self.environ):169 del os.environ[name]170 os.environ.update(self.environ)171 @property172 def _datetime_format_hint(self):173 return get_datetime_format_hint(get_console_locale(self.env))174 def _get_command_help(self, *args):175 docs = AdminCommandManager(self.env).get_command_help(list(args))176 self.assertEqual(1, len(docs))177 return docs[0][2]178 def _complete_command(self, *args):179 return AdminCommandManager(self.env).complete_command(list(args))180 def test_python_with_optimizations_returns_error(self):181 """Error is returned when a command is executed in interpreter182 with optimizations enabled.183 """184 proc = Popen((sys.executable, '-O', '-m', 'trac.admin.console',185 'help'), stdin=PIPE, stdout=PIPE, stderr=PIPE,186 close_fds=close_fds)187 stdout, stderr = proc.communicate(input='')188 for f in (proc.stdin, proc.stdout, proc.stderr):189 f.close()190 self.assertEqual(2, proc.returncode)191 self.assertEqual("Python with optimizations is not supported.",192 stderr.strip())193 # Help test194 def test_help_ok(self):195 """196 Tests the 'help' command in trac-admin. Since the 'help' command197 has no command arguments, it is hard to call it incorrectly. As198 a result, there is only this one test.199 """200 rv, output = self._execute('help')201 self.assertEqual(0, rv, output)202 self.assertExpectedResult(output, {203 'version': self.env.trac_version,204 'date_format_hint': get_date_format_hint()205 })206 self.assertTrue(all(len(line) < 80 for line in output.split('\n')),207 "Lines should be less than 80 characters in length.")208 # Locale test209 def _test_get_console_locale_with_babel(self):210 from babel.core import Locale, UnknownLocaleError211 locales = get_available_locales()212 en_US = Locale.parse('en_US')213 de = Locale.parse('de')214 def unset_locale_envs():215 for name in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):216 if name in os.environ:217 del os.environ[name]218 if 'de' in locales:219 unset_locale_envs()220 self.assertEqual(None, get_console_locale(None, None))221 self.assertEqual(de, get_console_locale(None, 'de_DE.UTF8'))222 self.env.config.set('trac', 'default_language', 'de')223 self.assertEqual(de, get_console_locale(self.env, None))224 self.assertEqual(de, get_console_locale(self.env, 'C'))225 self.env.config.set('trac', 'default_language', 'en_US')226 self.assertEqual(en_US, get_console_locale(self.env, None))227 self.assertEqual(en_US, get_console_locale(self.env, 'C'))228 self.assertEqual(de, get_console_locale(self.env,229 'de_DE.UTF8'))230 self.env.config.set('trac', 'default_language', 'de')231 os.environ['LANG'] = 'POSIX' # unavailable locale in Trac232 self.assertEqual(None, get_console_locale())233 self.assertEqual(de, get_console_locale(self.env))234 os.environ['LANG'] = '****' # invalid locale235 self.assertEqual(None, get_console_locale())236 self.assertEqual(de, get_console_locale(self.env))237 os.environ['LANG'] = 'en_US.utf-8'238 self.assertEqual(en_US, get_console_locale())239 self.assertEqual(en_US, get_console_locale(self.env))240 os.environ['LC_MESSAGES'] = 'de_DE.utf-8'241 self.assertEqual(de, get_console_locale())242 self.assertEqual(de, get_console_locale(self.env))243 os.environ['LC_ALL'] = 'en_US.utf-8'244 self.assertEqual(en_US, get_console_locale())245 self.assertEqual(en_US, get_console_locale(self.env))246 os.environ['LANGUAGE'] = 'de_DE:en_US:en'247 self.assertEqual(de, get_console_locale())248 self.assertEqual(de, get_console_locale(self.env))249 if not locales: # compiled catalog is missing250 unset_locale_envs()251 self.assertEqual(None, get_console_locale(None, 'de_DE.UTF8'))252 self.env.config.set('trac', 'default_language', 'de')253 self.assertEqual(None, get_console_locale(self.env, None))254 self.assertEqual(None, get_console_locale(self.env, 'C'))255 self.assertEqual(None, get_console_locale(self.env,256 'de_DE.UTF8'))257 os.environ['LANG'] = 'en_US.utf-8'258 os.environ['LC_MESSAGES'] = 'de_DE.utf-8'259 os.environ['LC_ALL'] = 'en_US.utf-8'260 os.environ['LANGUAGE'] = 'de_DE:en_US'261 self.assertEqual(en_US, get_console_locale())262 self.assertEqual(en_US, get_console_locale(self.env))263 def _test_get_console_locale_without_babel(self):264 os.environ['LANG'] = 'en_US.utf-8'265 os.environ['LC_MESSAGES'] = 'de_DE.utf-8'266 os.environ['LC_ALL'] = 'en_US.utf-8'267 os.environ['LANGUAGE'] = 'de_DE:en_US'268 self.assertEqual(None, get_console_locale(None, 'en_US.UTF8'))269 self.env.config.set('trac', 'default_language', '')270 self.assertEqual(None, get_console_locale(self.env, 'en_US.UTF8'))271 self.assertEqual(None, get_console_locale(self.env))272 self.env.config.set('trac', 'default_language', 'en_US')273 self.assertEqual(None, get_console_locale(self.env, 'en_US.UTF8'))274 self.assertEqual(None, get_console_locale(self.env))275 if has_babel:276 test_get_console_locale = _test_get_console_locale_with_babel277 else:278 test_get_console_locale = _test_get_console_locale_without_babel279 # Attachment tests280 def test_attachment_list_empty(self):281 """282 Tests the 'attachment list' command in trac-admin, on a wiki page that283 doesn't have any attachments.284 """285 # FIXME: Additional tests should be written for the other 'attachment'286 # commands. This requires being able to control the current287 # time, which in turn would require centralizing the time288 # provider, for example in the environment object.289 rv, output = self._execute('attachment list wiki:WikiStart')290 self.assertEqual(0, rv, output)291 self.assertExpectedResult(output)292 def test_attachment_add_nonexistent_resource(self):293 """Tests the 'attachment add' command in trac-admin, on a non-existent294 resource."""295 rv, output = self._execute('attachment add wiki:NonExistentPage "%s"'296 % __file__)297 self.assertEqual(2, rv, output)298 self.assertExpectedResult(output)299 # Config tests300 def test_config_get(self):301 """302 Tests the 'config get' command in trac-admin. This particular303 test gets the project name from the config.304 """305 self.env.config.set('project', 'name', 'Test project')306 rv, output = self._execute('config get project name')307 self.assertEqual(0, rv, output)308 self.assertExpectedResult(output)309 def test_config_set(self):310 """311 Tests the 'config set' command in trac-admin. This particular312 test sets the project name using an option value containing a space.313 """314 rv, output = self._execute('config set project name "Test project"')315 self.assertEqual(0, rv, output)316 self.assertExpectedResult(output)317 self.assertEqual('Test project',318 self.env.config.get('project', 'name'))319 def test_config_remove(self):320 """321 Tests the 'config remove' command in trac-admin. This particular322 test removes the project name from the config, therefore reverting323 the option to the default value.324 """325 self.env.config.set('project', 'name', 'Test project')326 rv, output = self._execute('config remove project name')327 self.assertEqual(0, rv, output)328 self.assertExpectedResult(output)329 self.assertEqual('My Project', self.env.config.get('project', 'name'))330 # Permission tests331 def test_permission_list_ok(self):332 """333 Tests the 'permission list' command in trac-admin. Since this command334 has no command arguments, it is hard to call it incorrectly. As335 a result, there is only this one test.336 """337 rv, output = self._execute('permission list')338 self.assertEqual(0, rv, output)339 self.assertExpectedResult(output)340 def test_permission_add_one_action_ok(self):341 """342 Tests the 'permission add' command in trac-admin. This particular343 test passes valid arguments to add one permission and checks for344 success.345 """346 self._execute('permission add test_user WIKI_VIEW')347 rv, output = self._execute('permission list')348 self.assertEqual(0, rv, output)349 self.assertExpectedResult(output)350 def test_permission_add_multiple_actions_ok(self):351 """352 Tests the 'permission add' command in trac-admin. This particular353 test passes valid arguments to add multiple permissions and checks for354 success.355 """356 self._execute('permission add test_user LOG_VIEW FILE_VIEW')357 rv, output = self._execute('permission list')358 self.assertEqual(0, rv, output)359 self.assertExpectedResult(output)360 def test_permission_add_already_exists(self):361 """362 Tests the 'permission add' command in trac-admin. This particular363 test passes a permission that already exists and checks for the364 message. Other permissions passed are added.365 """366 rv, output = self._execute('permission add anonymous WIKI_CREATE '367 'WIKI_VIEW WIKI_MODIFY')368 self.assertEqual(0, rv, output)369 rv, output2 = self._execute('permission list')370 self.assertEqual(0, rv, output2)371 self.assertExpectedResult(output + output2)372 def test_permission_add_differs_from_action_by_casing(self):373 """374 Tests the 'permission add' command in trac-admin. This particular375 test passes a permission that differs from an action by casing and376 checks for the message.377 """378 rv, output = self._execute('permission add anonymous Trac_Admin')379 self.assertEqual(2, rv, output)380 self.assertExpectedResult(output)381 def test_permission_add_unknown_action(self):382 """383 Tests the 'permission add' command in trac-admin. This particular384 test tries granting NOT_A_PERM to a user. NOT_A_PERM does not exist385 in the system."""386 rv, output = self._execute('permission add joe NOT_A_PERM')387 self.assertEqual(2, rv, output)388 self.assertExpectedResult(output)389 def test_permission_remove_one_action_ok(self):390 """391 Tests the 'permission remove' command in trac-admin. This particular392 test passes valid arguments to remove one permission and checks for393 success.394 """395 self._execute('permission remove anonymous TICKET_MODIFY')396 rv, output = self._execute('permission list')397 self.assertEqual(0, rv, output)398 self.assertExpectedResult(output)399 def test_permission_remove_multiple_actions_ok(self):400 """401 Tests the 'permission remove' command in trac-admin. This particular402 test passes valid arguments to remove multiple permission and checks403 for success.404 """405 self._execute('permission remove anonymous WIKI_CREATE WIKI_MODIFY')406 rv, output = self._execute('permission list')407 self.assertEqual(0, rv, output)408 self.assertExpectedResult(output)409 def test_permission_remove_all_actions_for_user(self):410 """411 Tests the 'permission remove' command in trac-admin. This particular412 test removes all permissions for anonymous.413 """414 self._execute('permission remove anonymous *')415 rv, output = self._execute('permission list')416 self.assertEqual(0, rv, output)417 self.assertExpectedResult(output)418 def test_permission_remove_action_for_all_users(self):419 """420 Tests the 'permission remove' command in trac-admin. This particular421 test removes the TICKET_CREATE permission from all users.422 """423 self._execute('permission add anonymous TICKET_CREATE')424 self._execute('permission remove * TICKET_CREATE')425 rv, output = self._execute('permission list')426 self.assertEqual(0, rv, output)427 self.assertExpectedResult(output)428 def test_permission_remove_unknown_user(self):429 """430 Tests the 'permission remove' command in trac-admin. This particular431 test tries removing a permission from an unknown user.432 """433 rv, output = self._execute('permission remove joe TICKET_VIEW')434 self.assertEqual(2, rv, output)435 self.assertExpectedResult(output)436 def test_permission_remove_action_not_granted(self):437 """438 Tests the 'permission remove' command in trac-admin. This particular439 test tries removing TICKET_CREATE from user anonymous, who doesn't440 have that permission.441 """442 rv, output = self._execute('permission remove anonymous TICKET_CREATE')443 self.assertEqual(2, rv, output)444 self.assertExpectedResult(output)445 def test_permission_remove_action_granted_through_meta_permission(self):446 """447 Tests the 'permission remove' command in trac-admin. This particular448 test tries removing WIKI_VIEW from a user. WIKI_VIEW has been granted449 through user anonymous."""450 self._execute('permission add joe TICKET_VIEW')451 rv, output = self._execute('permission remove joe WIKI_VIEW')452 self.assertEqual(2, rv, output)453 self.assertExpectedResult(output)454 def test_permission_remove_unknown_action(self):455 """456 Tests the 'permission remove' command in trac-admin. This particular457 test tries removing NOT_A_PERM from a user. NOT_A_PERM does not exist458 in the system."""459 rv, output = self._execute('permission remove joe NOT_A_PERM')460 self.assertEqual(2, rv, output)461 self.assertExpectedResult(output)462 def test_permission_remove_unknown_action_granted(self):463 """464 Tests the 'permission remove' command in trac-admin. This particular465 test tries removing NOT_A_PERM from a user. NOT_A_PERM does not exist466 in the system, but the user possesses the permission."""467 self.env.db_transaction("""468 INSERT INTO permission VALUES (%s, %s)469 """, ('joe', 'NOT_A_PERM'))470 rv, output = self._execute('permission remove joe NOT_A_PERM')471 self.assertEqual(0, rv, output)472 rv, output = self._execute('permission list')473 self.assertEqual(0, rv, output)474 self.assertExpectedResult(output)475 def test_permission_export_ok(self):476 """477 Tests the 'permission export' command in trac-admin. This particular478 test exports the default permissions to stdout.479 """480 rv, output = self._execute('permission export')481 self.assertEqual(0, rv, output)482 self.assertExpectedResult(output)483 def test_permission_import_ok(self):484 """485 Tests the 'permission import' command in trac-admin. This particular486 test exports additional permissions, removes them and imports them back.487 """488 user = u'test_user\u0250'489 self._execute('permission add ' + user + ' WIKI_VIEW')490 self._execute('permission add ' + user + ' TICKET_VIEW')491 rv, output = self._execute('permission export')492 self._execute('permission remove ' + user + ' *')493 rv, output = self._execute('permission import', input=output)494 self.assertEqual(0, rv, output)495 self.assertEqual('', output)496 rv, output = self._execute('permission list')497 self.assertEqual(0, rv, output)498 self.assertExpectedResult(output)499 # Component tests500 def test_component_list_ok(self):501 """502 Tests the 'component list' command in trac-admin. Since this command503 has no command arguments, it is hard to call it incorrectly. As504 a result, there is only this one test.505 """506 rv, output = self._execute('component list')507 self.assertEqual(0, rv, output)508 self.assertExpectedResult(output)509 def test_component_add_ok(self):510 """511 Tests the 'component add' command in trac-admin. This particular512 test passes valid arguments and checks for success.513 """514 self._execute('component add new_component')515 rv, output = self._execute('component list')516 self.assertEqual(0, rv, output)517 self.assertExpectedResult(output)518 def test_component_add_optional_owner_ok(self):519 """520 Tests the 'component add' command in trac-admin with the optional521 'owner' argument. This particular test passes valid arguments and522 checks for success.523 """524 self._execute('component add new_component new_user')525 rv, output = self._execute('component list')526 self.assertEqual(0, rv, output)527 self.assertExpectedResult(output)528 def test_component_add_complete_optional_owner_restrict_owner_false(self):529 """Tests completion of the 'component add <component>' command with530 [ticket] restrict_owner = false.531 """532 self._execute('config set ticket restrict_owner false')533 self._execute('session add user1')534 self._execute('session add user3')535 self._execute('permission add user1 TICKET_MODIFY')536 self._execute('permission add user2 TICKET_VIEW')537 self._execute('permission add user3 TICKET_MODIFY')538 output = self._complete_command('component', 'add',539 'new_component', '')540 self.assertEqual([], output)541 def test_component_add_complete_optional_owner_restrict_owner_true(self):542 """Tests completion of the 'component add <component>' command with543 [ticket] restrict_owner = true.544 """545 self._execute('config set ticket restrict_owner true')546 self._execute('session add user1')547 self._execute('session add user3')548 self._execute('permission add user1 TICKET_MODIFY')549 self._execute('permission add user2 TICKET_VIEW')550 self._execute('permission add user3 TICKET_MODIFY')551 output = self._complete_command('component', 'add',552 'new_component', '')553 self.assertEqual(['user1', 'user3'], output)554 def test_component_add_error_already_exists(self):555 """556 Tests the 'component add' command in trac-admin. This particular557 test passes a component name that already exists and checks for an558 error message.559 """560 rv, output = self._execute('component add component1 new_user')561 self.assertEqual(2, rv, output)562 self.assertExpectedResult(output)563 def test_component_rename_ok(self):564 """565 Tests the 'component rename' command in trac-admin. This particular566 test passes valid arguments and checks for success.567 """568 self._execute('component rename component1 changed_name')569 rv, output = self._execute('component list')570 self.assertEqual(0, rv, output)571 self.assertExpectedResult(output)572 def test_component_rename_error_bad_component(self):573 """574 Tests the 'component rename' command in trac-admin. This particular575 test tries to rename a component that does not exist.576 """577 rv, output = self._execute('component rename bad_component changed_name')578 self.assertEqual(2, rv, output)579 self.assertExpectedResult(output)580 def test_component_rename_error_bad_new_name(self):581 """582 Tests the 'component rename' command in trac-admin. This particular583 test tries to rename a component to a name that already exists.584 """585 rv, output = self._execute('component rename component1 component2')586 self.assertEqual(2, rv, output)587 self.assertExpectedResult(output)588 def test_component_chown_ok(self):589 """590 Tests the 'component chown' command in trac-admin. This particular591 test passes valid arguments and checks for success.592 """593 self._execute('component chown component2 changed_owner')594 rv, output = self._execute('component list')595 self.assertEqual(0, rv, output)596 self.assertExpectedResult(output)597 def test_component_chown_complete_component(self):598 """Tests completion of the 'component chown' command.599 """600 output = self._complete_command('component', 'chown', '')601 self.assertEqual(['component1', 'component2'], output)602 def test_component_chown_complete_owner_restrict_owner_false(self):603 """Tests completion of the 'component chown <component>' command with604 [ticket] restrict_owner = false.605 """606 self._execute('config set ticket restrict_owner false')607 self._execute('session add user1')608 self._execute('session add user3')609 self._execute('permission add user1 TICKET_MODIFY')610 self._execute('permission add user2 TICKET_VIEW')611 self._execute('permission add user3 TICKET_MODIFY')612 output = self._complete_command('component', 'chown', 'component1', '')613 self.assertEqual([], output)614 def test_component_chown_complete_owner_restrict_owner_true(self):615 """Tests completion of the 'component chown <component>' command with616 [ticket] restrict_owner = true.617 """618 self._execute('config set ticket restrict_owner true')619 self._execute('session add user1')620 self._execute('session add user3')621 self._execute('permission add user1 TICKET_MODIFY')622 self._execute('permission add user2 TICKET_VIEW')623 self._execute('permission add user3 TICKET_MODIFY')624 output = self._complete_command('component', 'chown', 'component1', '')625 self.assertEqual(['user1', 'user3'], output)626 def test_component_chown_error_bad_component(self):627 """628 Tests the 'component chown' command in trac-admin. This particular629 test tries to change the owner of a component that does not630 exist.631 """632 rv, output = self._execute('component chown bad_component changed_owner')633 self.assertEqual(2, rv, output)634 self.assertExpectedResult(output)635 def test_component_remove_ok(self):636 """637 Tests the 'component remove' command in trac-admin. This particular638 test passes a valid argument and checks for success.639 """640 self._execute('component remove component1')641 rv, output = self._execute('component list')642 self.assertEqual(0, rv, output)643 self.assertExpectedResult(output)644 def test_component_remove_error_bad_component(self):645 """646 Tests the 'component remove' command in trac-admin. This particular647 test tries to remove a component that does not exist.648 """649 rv, output = self._execute('component remove bad_component')650 self.assertEqual(2, rv, output)651 self.assertExpectedResult(output)652 # Ticket-type tests653 def test_ticket_type_list_ok(self):654 """655 Tests the 'ticket_type list' command in trac-admin. Since this command656 has no command arguments, it is hard to call it incorrectly. As657 a result, there is only this one test.658 """659 rv, output = self._execute('ticket_type list')660 self.assertEqual(0, rv, output)661 self.assertExpectedResult(output)662 def test_ticket_type_add_ok(self):663 """664 Tests the 'ticket_type add' command in trac-admin. This particular665 test passes a valid argument and checks for success.666 """667 self._execute('ticket_type add new_type')668 rv, output = self._execute('ticket_type list')669 self.assertEqual(0, rv, output)670 self.assertExpectedResult(output)671 def test_ticket_type_add_error_already_exists(self):672 """673 Tests the 'ticket_type add' command in trac-admin. This particular674 test passes a ticket type that already exists and checks for an error675 message.676 """677 rv, output = self._execute('ticket_type add defect')678 self.assertEqual(2, rv, output)679 self.assertExpectedResult(output)680 def test_ticket_type_change_ok(self):681 """682 Tests the 'ticket_type change' command in trac-admin. This particular683 test passes valid arguments and checks for success.684 """685 self._execute('ticket_type change defect bug')686 rv, output = self._execute('ticket_type list')687 self.assertEqual(0, rv, output)688 self.assertExpectedResult(output)689 def test_ticket_type_change_error_bad_type(self):690 """691 Tests the 'ticket_type change' command in trac-admin. This particular692 test tries to change a priority that does not exist.693 """694 rv, output = self._execute('ticket_type change bad_type changed_type')695 self.assertEqual(2, rv, output)696 self.assertExpectedResult(output)697 def test_ticket_type_change_error_bad_new_name(self):698 """699 Tests the 'ticket_type change' command in trac-admin. This particular700 test tries to change a ticket type to another type that already exists.701 """702 rv, output = self._execute('ticket_type change defect task')703 self.assertEqual(2, rv, output)704 self.assertExpectedResult(output)705 def test_ticket_type_remove_ok(self):706 """707 Tests the 'ticket_type remove' command in trac-admin. This particular708 test passes a valid argument and checks for success.709 """710 self._execute('ticket_type remove task')711 rv, output = self._execute('ticket_type list')712 self.assertEqual(0, rv, output)713 self.assertExpectedResult(output)714 def test_ticket_type_remove_error_bad_type(self):715 """716 Tests the 'ticket_type remove' command in trac-admin. This particular717 test tries to remove a ticket type that does not exist.718 """719 rv, output = self._execute('ticket_type remove bad_type')720 self.assertEqual(2, rv, output)721 self.assertExpectedResult(output)722 def test_ticket_type_order_down_ok(self):723 """724 Tests the 'ticket_type order' command in trac-admin. This particular725 test passes a valid argument and checks for success.726 """727 self._execute('ticket_type order defect down')728 rv, output = self._execute('ticket_type list')729 self.assertEqual(0, rv, output)730 self.assertExpectedResult(output)731 def test_ticket_type_order_up_ok(self):732 """733 Tests the 'ticket_type order' command in trac-admin. This particular734 test passes a valid argument and checks for success.735 """736 self._execute('ticket_type order enhancement up')737 rv, output = self._execute('ticket_type list')738 self.assertEqual(0, rv, output)739 self.assertExpectedResult(output)740 def test_ticket_type_order_error_bad_type(self):741 """742 Tests the 'priority order' command in trac-admin. This particular743 test tries to reorder a priority that does not exist.744 """745 rv, output = self._execute('ticket_type order bad_type up')746 self.assertEqual(2, rv, output)747 self.assertExpectedResult(output)748 # Priority tests749 def test_priority_list_ok(self):750 """751 Tests the 'priority list' command in trac-admin. Since this command752 has no command arguments, it is hard to call it incorrectly. As753 a result, there is only this one test.754 """755 rv, output = self._execute('priority list')756 self.assertEqual(0, rv, output)757 self.assertExpectedResult(output)758 def test_priority_add_ok(self):759 """760 Tests the 'priority add' command in trac-admin. This particular761 test passes a valid argument and checks for success.762 """763 self._execute('priority add new_priority')764 rv, output = self._execute('priority list')765 self.assertEqual(0, rv, output)766 self.assertExpectedResult(output)767 def test_priority_add_many_ok(self):768 """769 Tests adding more than 10 priority values. This makes sure that770 ordering is preserved when adding more than 10 values.771 """772 for i in xrange(11):773 self._execute('priority add p%s' % i)774 rv, output = self._execute('priority list')775 self.assertEqual(0, rv, output)776 self.assertExpectedResult(output)777 def test_priority_add_error_already_exists(self):778 """779 Tests the 'priority add' command in trac-admin. This particular780 test passes a priority name that already exists and checks for an781 error message.782 """783 rv, output = self._execute('priority add blocker')784 self.assertEqual(2, rv, output)785 self.assertExpectedResult(output)786 def test_priority_change_ok(self):787 """788 Tests the 'priority change' command in trac-admin. This particular789 test passes valid arguments and checks for success.790 """791 self._execute('priority change major normal')792 rv, output = self._execute('priority list')793 self.assertEqual(0, rv, output)794 self.assertExpectedResult(output)795 def test_priority_change_error_bad_priority(self):796 """797 Tests the 'priority change' command in trac-admin. This particular798 test tries to change a priority that does not exist.799 """800 rv, output = self._execute('priority change bad_priority changed_name')801 self.assertEqual(2, rv, output)802 self.assertExpectedResult(output)803 def test_priority_change_error_bad_new_name(self):804 """805 Tests the 'priority change' command in trac-admin. This particular806 test tries to change a priority to a name that already exists.807 """808 rv, output = self._execute('priority change major minor')809 self.assertEqual(2, rv, output)810 self.assertExpectedResult(output)811 def test_priority_remove_ok(self):812 """813 Tests the 'priority remove' command in trac-admin. This particular814 test passes a valid argument and checks for success.815 """816 self._execute('priority remove major')817 rv, output = self._execute('priority list')818 self.assertEqual(0, rv, output)819 self.assertExpectedResult(output)820 def test_priority_remove_error_bad_priority(self):821 """822 Tests the 'priority remove' command in trac-admin. This particular823 test tries to remove a priority that does not exist.824 """825 rv, output = self._execute('priority remove bad_priority')826 self.assertEqual(2, rv, output)827 self.assertExpectedResult(output)828 def test_priority_order_down_ok(self):829 """830 Tests the 'priority order' command in trac-admin. This particular831 test passes a valid argument and checks for success.832 """833 self._execute('priority order blocker down')834 rv, output = self._execute('priority list')835 self.assertEqual(0, rv, output)836 self.assertExpectedResult(output)837 def test_priority_order_up_ok(self):838 """839 Tests the 'priority order' command in trac-admin. This particular840 test passes a valid argument and checks for success.841 """842 self._execute('priority order critical up')843 rv, output = self._execute('priority list')844 self.assertEqual(0, rv, output)845 self.assertExpectedResult(output)846 def test_priority_order_error_bad_priority(self):847 """848 Tests the 'priority order' command in trac-admin. This particular849 test tries to reorder a priority that does not exist.850 """851 rv, output = self._execute('priority remove bad_priority')852 self.assertEqual(2, rv, output)853 self.assertExpectedResult(output)854 # Severity tests855 def test_severity_list_ok(self):856 """857 Tests the 'severity list' command in trac-admin. Since this command858 has no command arguments, it is hard to call it incorrectly. As859 a result, there is only this one test.860 """861 rv, output = self._execute('severity list')862 self.assertEqual(0, rv, output)863 self.assertExpectedResult(output)864 def test_severity_add_ok(self):865 """866 Tests the 'severity add' command in trac-admin. This particular867 test passes a valid argument and checks for success.868 """869 self._execute('severity add new_severity')870 rv, output = self._execute('severity list')871 self.assertEqual(0, rv, output)872 self.assertExpectedResult(output)873 def test_severity_add_error_already_exists(self):874 """875 Tests the 'severity add' command in trac-admin. This particular876 test passes a severity name that already exists and checks for an877 error message.878 """879 self._execute('severity add blocker')880 rv, output = self._execute('severity add blocker')881 self.assertEqual(2, rv, output)882 self.assertExpectedResult(output)883 def test_severity_change_ok(self):884 """885 Tests the 'severity add' command in trac-admin. This particular886 test passes valid arguments and checks for success.887 """888 self._execute('severity add critical')889 self._execute('severity change critical "end-of-the-world"')890 rv, output = self._execute('severity list')891 self.assertEqual(0, rv, output)892 self.assertExpectedResult(output)893 def test_severity_change_error_bad_severity(self):894 """895 Tests the 'severity change' command in trac-admin. This particular896 test tries to change a severity that does not exist.897 """898 rv, output = self._execute('severity change bad_severity changed_name')899 self.assertEqual(2, rv, output)900 self.assertExpectedResult(output)901 def test_severity_change_error_bad_new_name(self):902 """903 Tests the 'severity change' command in trac-admin. This particular904 test tries to change a severity to a name that already exists.905 """906 self._execute('severity add major')907 self._execute('severity add critical')908 rv, output = self._execute('severity change critical major')909 self.assertEqual(2, rv, output)910 self.assertExpectedResult(output)911 def test_severity_remove_ok(self):912 """913 Tests the 'severity add' command in trac-admin. This particular914 test passes a valid argument and checks for success.915 """916 self._execute('severity remove trivial')917 rv, output = self._execute('severity list')918 self.assertEqual(0, rv, output)919 self.assertExpectedResult(output)920 def test_severity_remove_error_bad_severity(self):921 """922 Tests the 'severity remove' command in trac-admin. This particular923 test tries to remove a severity that does not exist.924 """925 rv, output = self._execute('severity remove bad_severity')926 self.assertEqual(2, rv, output)927 self.assertExpectedResult(output)928 def test_severity_order_down_ok(self):929 """930 Tests the 'severity order' command in trac-admin. This particular931 test passes a valid argument and checks for success.932 """933 self._execute('severity add foo')934 self._execute('severity add bar')935 self._execute('severity order foo down')936 rv, output = self._execute('severity list')937 self.assertEqual(0, rv, output)938 self.assertExpectedResult(output)939 def test_severity_order_up_ok(self):940 """941 Tests the 'severity order' command in trac-admin. This particular942 test passes a valid argument and checks for success.943 """944 self._execute('severity add foo')945 self._execute('severity add bar')946 self._execute('severity order bar up')947 rv, output = self._execute('severity list')948 self.assertEqual(0, rv, output)949 self.assertExpectedResult(output)950 def test_severity_order_error_bad_severity(self):951 """952 Tests the 'severity order' command in trac-admin. This particular953 test tries to reorder a priority that does not exist.954 """955 rv, output = self._execute('severity remove bad_severity')956 self.assertEqual(2, rv, output)957 self.assertExpectedResult(output)958 # Version tests959 def test_version_list_ok(self):960 """961 Tests the 'version list' command in trac-admin. Since this command962 has no command arguments, it is hard to call it incorrectly. As963 a result, there is only this one test.964 """965 rv, output = self._execute('version list')966 self.assertEqual(0, rv, output)967 self.assertExpectedResult(output)968 def test_version_add_ok(self):969 """970 Tests the 'version add' command in trac-admin. This particular971 test passes valid arguments and checks for success.972 """973 self._execute('version add 9.9 "%s"' % self._test_date)974 rv, output = self._execute('version list')975 self.assertEqual(0, rv, output)976 self.assertExpectedResult(output)977 def test_version_add_error_already_exists(self):978 """979 Tests the 'version add' command in trac-admin. This particular980 test passes a version name that already exists and checks for an981 error message.982 """983 rv, output = self._execute('version add 1.0 "%s"' % self._test_date)984 self.assertEqual(2, rv, output)985 self.assertExpectedResult(output)986 def test_version_rename_ok(self):987 """988 Tests the 'version rename' command in trac-admin. This particular989 test passes valid arguments and checks for success.990 """991 self._execute('version rename 1.0 9.9')992 rv, output = self._execute('version list')993 self.assertEqual(0, rv, output)994 self.assertExpectedResult(output)995 def test_version_rename_error_bad_version(self):996 """997 Tests the 'version rename' command in trac-admin. This particular998 test tries to rename a version that does not exist.999 """1000 rv, output = self._execute('version rename bad_version changed_name')1001 self.assertEqual(2, rv, output)1002 self.assertExpectedResult(output)1003 def test_version_time_ok(self):1004 """1005 Tests the 'version time' command in trac-admin. This particular1006 test passes valid arguments and checks for success.1007 """1008 self._execute('version time 2.0 "%s"' % self._test_date)1009 rv, output = self._execute('version list')1010 self.assertEqual(0, rv, output)1011 self.assertExpectedResult(output)1012 def test_version_time_unset_ok(self):1013 """1014 Tests the 'version time' command in trac-admin. This particular1015 test passes valid arguments for unsetting the date.1016 """1017 self._execute('version time 2.0 "%s"' % self._test_date)1018 self._execute('version time 2.0 ""')1019 rv, output = self._execute('version list')1020 self.assertEqual(0, rv, output)1021 self.assertExpectedResult(output)1022 def test_version_time_error_bad_version(self):1023 """1024 Tests the 'version time' command in trac-admin. This particular1025 test tries to change the time on a version that does not exist.1026 """1027 rv, output = self._execute('version time bad_version "%s"'1028 % self._test_date)1029 self.assertEqual(2, rv, output)1030 self.assertExpectedResult(output)1031 def test_version_remove_ok(self):1032 """1033 Tests the 'version remove' command in trac-admin. This particular1034 test passes a valid argument and checks for success.1035 """1036 self._execute('version remove 1.0')1037 rv, output = self._execute('version list')1038 self.assertEqual(0, rv, output)1039 self.assertExpectedResult(output)1040 def test_version_remove_error_bad_version(self):1041 """1042 Tests the 'version remove' command in trac-admin. This particular1043 test tries to remove a version that does not exist.1044 """1045 rv, output = self._execute('version remove bad_version')1046 self.assertEqual(2, rv, output)1047 self.assertExpectedResult(output)1048 # Milestone tests1049 def test_milestone_list_ok(self):1050 """1051 Tests the 'milestone list' command in trac-admin. Since this command1052 has no command arguments, it is hard to call it incorrectly. As1053 a result, there is only this one test.1054 """1055 rv, output = self._execute('milestone list')1056 self.assertEqual(0, rv, output)1057 self.assertExpectedResult(output)1058 def test_milestone_add_ok(self):1059 """1060 Tests the 'milestone add' command in trac-admin. This particular1061 test passes valid arguments and checks for success.1062 """1063 self._execute('milestone add new_milestone "%s"' % self._test_date)1064 rv, output = self._execute('milestone list')1065 self.assertEqual(0, rv, output)1066 self.assertExpectedResult(output)1067 def test_milestone_add_utf8_ok(self):1068 """1069 Tests the 'milestone add' command in trac-admin. This particular1070 test passes valid arguments and checks for success.1071 """1072 self._execute(u'milestone add \xa9tat_final "%s"' #\xc2\xa91073 % self._test_date)1074 rv, output = self._execute('milestone list')1075 self.assertEqual(0, rv, output)1076 self.assertExpectedResult(output)1077 def test_milestone_add_error_already_exists(self):1078 """1079 Tests the 'milestone add' command in trac-admin. This particular1080 test passes a milestone name that already exists and checks for an1081 error message.1082 """1083 rv, output = self._execute('milestone add milestone1 "%s"'1084 % self._test_date)1085 self.assertEqual(2, rv, output)1086 self.assertExpectedResult(output)1087 def test_milestone_add_invalid_date(self):1088 rv, output = self._execute('milestone add new_milestone <add>')1089 self.assertEqual(2, rv, output)1090 self.assertExpectedResult(output, {1091 'hint': self._datetime_format_hint,1092 'isohint': get_datetime_format_hint('iso8601')1093 })1094 def test_milestone_rename_ok(self):1095 """1096 Tests the 'milestone rename' command in trac-admin. This particular1097 test passes valid arguments and checks for success.1098 """1099 self._execute('milestone rename milestone1 changed_milestone')1100 rv, output = self._execute('milestone list')1101 self.assertEqual(0, rv, output)1102 self.assertExpectedResult(output)1103 def test_milestone_rename_error_bad_milestone(self):1104 """1105 Tests the 'milestone rename' command in trac-admin. This particular1106 test tries to rename a milestone that does not exist.1107 """1108 rv, output = self._execute('milestone rename bad_milestone changed_name')1109 self.assertEqual(2, rv, output)1110 self.assertExpectedResult(output)1111 def test_milestone_due_ok(self):1112 """1113 Tests the 'milestone due' command in trac-admin. This particular1114 test passes valid arguments and checks for success.1115 """1116 self._execute('milestone due milestone2 "%s"' % self._test_date)1117 rv, output = self._execute('milestone list')1118 self.assertEqual(0, rv, output)1119 self.assertExpectedResult(output)1120 def test_milestone_due_unset_ok(self):1121 """1122 Tests the 'milestone due' command in trac-admin. This particular1123 test passes valid arguments for unsetting the due date.1124 """1125 self._execute('milestone due milestone2 "%s"' % self._test_date)1126 self._execute('milestone due milestone2 ""')1127 rv, output = self._execute('milestone list')1128 self.assertEqual(0, rv, output)1129 self.assertExpectedResult(output)1130 def test_milestone_due_error_bad_milestone(self):1131 """1132 Tests the 'milestone due' command in trac-admin. This particular1133 test tries to change the due date on a milestone that does not exist.1134 """1135 rv, output = self._execute('milestone due bad_milestone "%s"'1136 % self._test_date)1137 self.assertEqual(2, rv, output)1138 self.assertExpectedResult(output)1139 def test_milestone_due_invalid_date(self):1140 rv, output = self._execute('milestone due milestone1 <due>')1141 self.assertEqual(2, rv, output)1142 self.assertExpectedResult(output, {1143 'hint': self._datetime_format_hint,1144 'isohint': get_datetime_format_hint('iso8601')1145 })1146 def test_milestone_completed_ok(self):1147 """1148 Tests the 'milestone completed' command in trac-admin. This particular1149 test passes valid arguments and checks for success.1150 """1151 self._execute('milestone completed milestone2 "%s"' % self._test_date)1152 rv, output = self._execute('milestone list')1153 self.assertEqual(0, rv, output)1154 self.assertExpectedResult(output)1155 def test_milestone_completed_error_bad_milestone(self):1156 """1157 Tests the 'milestone completed' command in trac-admin. This particular1158 test tries to change the completed date on a milestone that does not1159 exist.1160 """1161 rv, output = self._execute('milestone completed bad_milestone "%s"'1162 % self._test_date)1163 self.assertEqual(2, rv, output)1164 self.assertExpectedResult(output)1165 def test_milestone_completed_invalid_date(self):1166 rv, output = self._execute('milestone completed milestone1 <com>')1167 self.assertEqual(2, rv, output)1168 self.assertExpectedResult(output, {1169 'hint': self._datetime_format_hint,1170 'isohint': get_datetime_format_hint('iso8601')1171 })1172 def test_milestone_remove_ok(self):1173 """1174 Tests the 'milestone remove' command in trac-admin. This particular1175 test passes a valid argument and checks for success.1176 """1177 self._execute('milestone remove milestone3')1178 rv, output = self._execute('milestone list')1179 self.assertEqual(0, rv, output)1180 self.assertExpectedResult(output)1181 def test_milestone_remove_error_bad_milestone(self):1182 """1183 Tests the 'milestone remove' command in trac-admin. This particular1184 test tries to remove a milestone that does not exist.1185 """1186 rv, output = self._execute('milestone remove bad_milestone')1187 self.assertEqual(2, rv, output)1188 self.assertExpectedResult(output)1189 def test_backslash_use_ok(self):1190 if self._admin.interactive:1191 self._execute('version add \\')1192 else:1193 self._execute(r"version add '\'")1194 rv, output = self._execute('version list')1195 self.assertEqual(0, rv, output)1196 self.assertExpectedResult(output)1197 def test_session_list_no_sessions(self):1198 rv, output = self._execute('session list authenticated')1199 self.assertEqual(0, rv, output)1200 self.assertExpectedResult(output)1201 def test_session_list_authenticated(self):1202 _prep_session_table(self.env)1203 rv, output = self._execute('session list authenticated')1204 self.assertEqual(0, rv, output)1205 self.assertExpectedResult(output)1206 def test_session_list_anonymous(self):1207 _prep_session_table(self.env)1208 rv, output = self._execute('session list anonymous')1209 self.assertEqual(0, rv, output)1210 self.assertExpectedResult(output)1211 def test_session_list_all(self):1212 _prep_session_table(self.env)1213 if self._admin.interactive:1214 rv, output = self._execute("session list *")1215 else:1216 rv, output = self._execute("session list '*'")1217 self.assertEqual(0, rv, output)1218 self.assertExpectedResult(output)1219 def test_session_list_authenticated_sid(self):1220 _prep_session_table(self.env)1221 rv, output = self._execute('session list name00')1222 self.assertEqual(0, rv, output)1223 self.assertExpectedResult(output)1224 def test_session_list_anonymous_sid(self):1225 _prep_session_table(self.env)1226 rv, output = self._execute('session list name10:0')1227 self.assertEqual(0, rv, output)1228 self.assertExpectedResult(output)1229 def test_session_list_missing_sid(self):1230 _prep_session_table(self.env)1231 rv, output = self._execute('session list thisdoesntexist')1232 self.assertEqual(0, rv, output)1233 self.assertExpectedResult(output)1234 def test_session_add_missing_sid(self):1235 rv, output = self._execute('session add')1236 self.assertEqual(2, rv, output)1237 self.assertExpectedResult(output)1238 def test_session_add_duplicate_sid(self):1239 _prep_session_table(self.env)1240 rv, output = self._execute('session add name00')1241 self.assertEqual(2, rv, output)1242 self.assertExpectedResult(output)1243 def test_session_add_sid_all(self):1244 rv, output = self._execute('session add john John john@example.org')1245 self.assertEqual(0, rv, output)1246 rv, output = self._execute('session list john')1247 self.assertExpectedResult(output, {1248 'today': format_date(None, console_date_format)1249 })1250 def test_session_add_sid(self):1251 rv, output = self._execute('session add john')1252 self.assertEqual(0, rv, output)1253 rv, output = self._execute('session list john')1254 self.assertExpectedResult(output, {1255 'today': format_date(None, console_date_format)1256 })1257 def test_session_add_sid_name(self):1258 rv, output = self._execute('session add john John')1259 self.assertEqual(0, rv, output)1260 rv, output = self._execute('session list john')1261 self.assertExpectedResult(output, {1262 'today': format_date(None, console_date_format)1263 })1264 def test_session_set_attr_name(self):1265 _prep_session_table(self.env)1266 rv, output = self._execute('session set name name00 JOHN')1267 self.assertEqual(0, rv, output)1268 rv, output = self._execute('session list name00')1269 self.assertExpectedResult(output)1270 def test_session_set_attr_email(self):1271 _prep_session_table(self.env)1272 rv, output = self._execute('session set email name00 JOHN@EXAMPLE.ORG')1273 self.assertEqual(0, rv, output)1274 rv, output = self._execute('session list name00')1275 self.assertExpectedResult(output)1276 def test_session_set_attr_default_handler(self):1277 _prep_session_table(self.env)1278 rv, output = \1279 self._execute('session set default_handler name00 SearchModule')1280 self.assertEqual(0, rv, output)1281 rv, output = self._execute('session list name00')1282 self.assertExpectedResult(output)1283 def test_session_set_attr_default_handler_invalid(self):1284 _prep_session_table(self.env)1285 rv, output = \1286 self._execute('session set default_handler name00 InvalidModule')1287 self.assertEqual(2, rv, output)1288 self.assertExpectedResult(output)1289 def test_session_set_attr_missing_attr(self):1290 rv, output = self._execute('session set')1291 self.assertEqual(2, rv, output)1292 self.assertExpectedResult(output)1293 def test_session_set_attr_missing_value(self):1294 rv, output = self._execute('session set name john')1295 self.assertEqual(2, rv, output)1296 self.assertExpectedResult(output)1297 def test_session_set_attr_missing_sid(self):1298 rv, output = self._execute('session set name')1299 self.assertEqual(2, rv, output)1300 self.assertExpectedResult(output)1301 def test_session_set_attr_nonexistent_sid(self):1302 rv, output = self._execute('session set name john foo')1303 self.assertEqual(2, rv, output)1304 self.assertExpectedResult(output)1305 def test_session_delete_sid(self):1306 _prep_session_table(self.env)1307 rv, output = self._execute('session delete name00')1308 self.assertEqual(0, rv, output)1309 rv, output = self._execute('session list nam00')1310 self.assertExpectedResult(output)1311 def test_session_delete_missing_params(self):1312 rv, output = self._execute('session delete')1313 self.assertEqual(0, rv, output)1314 self.assertExpectedResult(output)1315 def test_session_delete_anonymous(self):1316 _prep_session_table(self.env)1317 rv, output = self._execute('session delete anonymous')1318 self.assertEqual(0, rv, output)1319 rv, output = self._execute('session list *')1320 self.assertExpectedResult(output)1321 def test_session_delete_multiple_sids(self):1322 _prep_session_table(self.env)1323 rv, output = self._execute('session delete name00 name01 name02 '1324 'name03')1325 self.assertEqual(0, rv, output)1326 rv, output = self._execute('session list *')1327 self.assertExpectedResult(output)1328 def test_session_purge_age(self):1329 _prep_session_table(self.env, spread_visits=True)1330 rv, output = self._execute('session purge 20100112')1331 self.assertEqual(0, rv, output)1332 rv, output = self._execute('session list *')1333 self.assertExpectedResult(output)1334 def test_session_purge_invalid_date(self):1335 rv, output = self._execute('session purge <purge>')1336 self.assertEqual(2, rv, output)1337 self.assertExpectedResult(output, {1338 'hint': self._datetime_format_hint,1339 'isohint': get_datetime_format_hint('iso8601')1340 })1341 def test_help_milestone_due(self):1342 doc = self._get_command_help('milestone', 'due')1343 self.assertIn(self._datetime_format_hint, doc)1344 self.assertIn(u'"YYYY-MM-DDThh:mm:ss±hh:mm"', doc)1345 def test_help_milestone_completed(self):1346 doc = self._get_command_help('milestone', 'completed')1347 self.assertIn(self._datetime_format_hint, doc)1348 self.assertIn(u'"YYYY-MM-DDThh:mm:ss±hh:mm"', doc)1349 def test_help_version_time(self):1350 doc = self._get_command_help('version', 'time')1351 self.assertIn(self._datetime_format_hint, doc)1352 self.assertIn(u'"YYYY-MM-DDThh:mm:ss±hh:mm"', doc)1353 def test_help_session_purge(self):1354 doc = self._get_command_help('session', 'purge')1355 self.assertIn(u'"YYYY-MM-DDThh:mm:ss±hh:mm"', doc)1356 def test_changeset_add_no_repository_revision(self):1357 rv, output = self._execute('changeset added')1358 self.assertEqual(2, rv, output)1359 self.assertExpectedResult(output)1360 def test_changeset_add_no_revision(self):1361 rv, output = self._execute('changeset added repos')1362 self.assertEqual(2, rv, output)1363 self.assertExpectedResult(output)1364 def test_changeset_modify_no_repository_revision(self):1365 rv, output = self._execute('changeset modified')1366 self.assertEqual(2, rv, output)1367 self.assertExpectedResult(output)1368 def test_changeset_modify_no_revision(self):1369 rv, output = self._execute('changeset modified repos')1370 self.assertEqual(2, rv, output)1371 self.assertExpectedResult(output)1372 def test_changeset_add_invalid_repository(self):1373 rv, output = self._execute('changeset added repos 123')1374 self.assertEqual(2, rv, output)1375 self.assertExpectedResult(output)1376 def test_changeset_modify_invalid_repository(self):1377 rv, output = self._execute('changeset modified repos 123')1378 self.assertEqual(2, rv, output)1379 self.assertExpectedResult(output)1380class TracadminNoEnvTestCase(unittest.TestCase):1381 def setUp(self):1382 self._admin = TracAdmin()1383 def tearDown(self):1384 self._admin = None1385 def _execute(self, cmd, strip_trailing_space=True, input=None):1386 return execute_cmd(self._admin, cmd,1387 strip_trailing_space=strip_trailing_space,1388 input=input)1389 def test_help(self):1390 rv, output = self._execute('help')1391 output = output.splitlines()1392 self.assertEqual('', output[-3])1393 self.assertEqual('help Show documentation', output[-2])1394 self.assertEqual('initenv Create and initialize a new environment',1395 output[-1])1396 def test_help_with_nocmd(self):1397 rv, output = self._execute('help nocmd')1398 output = output.splitlines()1399 self.assertEqual(["No documentation found for 'nocmd'. Use 'help' to "1400 "see the list of commands."],1401 output)1402 def test_run_help_with_arguments(self):1403 rv, output = execute_run(['help'])1404 self.assertIn('Usage: trac-admin </path/to/projenv>', output)1405 rv, output = execute_run(['help', "foo'bar"])1406 self.assertNotIn('No closing quotation', output)1407 self.assertIn("No documentation found for 'foo'bar'", output)1408 def test_run_cmd_with_env_path(self):1409 rv, output = execute_run(['notfound-tracenv', 'help'])1410 self.assertIn('Usage: trac-admin </path/to/projenv>', output)1411 rv, output = execute_run(['notfound-tracenv', 'help', "foo'bar"])1412 self.assertNotIn('No closing quotation', output)1413 self.assertIn("No documentation found for 'foo'bar'", output)1414class TracAdminHelpMacroTestCase(unittest.TestCase):1415 def setUp(self):1416 self.env = EnvironmentStub(enable=['%s.UnicodeHelpCommand' %1417 self.__module__])1418 def tearDown(self):1419 self.env.reset_db()1420 def test_unicode_help(self):1421 unicode_help = u'Hélp text with unicöde charà cters'1422 class UnicodeHelpCommand(Component):1423 implements(IAdminCommandProvider)1424 def get_admin_commands(self):1425 yield ('unicode-help', '', unicode_help,1426 None, self._cmd)1427 def _cmd(self):1428 pass1429 macro = TracAdminHelpMacro(self.env)1430 help = unicode(macro.expand_macro(None, None, 'unicode-help'))1431 self.assertTrue(unicode_help in help)1432 def test_invalid_command(self):1433 macro = TracAdminHelpMacro(self.env)1434 try:1435 macro.expand_macro(None, None, 'copystatic')1436 self.fail("MacroError not raised")1437 except MacroError as e:1438 self.assertEqual('Unknown trac-admin command "copystatic"',1439 unicode(e))1440class TracAdminComponentTestCase(unittest.TestCase):1441 def setUp(self):1442 self.env = EnvironmentStub(default_data=True, enable=('trac.*',),1443 disable=('trac.tests.*',))1444 self._admin = TracAdmin()1445 self._admin.env_set('', self.env)1446 self._orig = {1447 'ComponentMeta._components': ComponentMeta._components,1448 'ComponentMeta._registry': ComponentMeta._registry,1449 'ConfigSection.registry': ConfigSection.registry,1450 'Option.registry': Option.registry,1451 }1452 ComponentMeta._components = list(ComponentMeta._components)1453 ComponentMeta._registry = dict((interface, list(classes))1454 for interface, classes1455 in ComponentMeta._registry.iteritems())1456 ConfigSection.registry = {}1457 Option.registry = {}1458 class CompA(Component):1459 from trac.config import Option1460 opt1 = Option('compa', 'opt1', 1)1461 opt2 = Option('compa', 'opt2', 2)1462 def tearDown(self):1463 self.env = None1464 self._admin = None1465 ComponentMeta._components = self._orig['ComponentMeta._components']1466 ComponentMeta._registry = self._orig['ComponentMeta._registry']1467 ConfigSection.registry = self._orig['ConfigSection.registry']1468 Option.registry = self._orig['Option.registry']1469 def _execute(self, cmd, strip_trailing_space=True, input=None):1470 return execute_cmd(self._admin, cmd,1471 strip_trailing_space=strip_trailing_space,1472 input=input)1473 def test_config_component_enable(self):1474 self.env.config.save()1475 initial_file = copy.deepcopy(self.env.config.parser)1476 rv, output = self._execute('config set components '1477 'trac.admin.tests.console.* enabled')1478 self.assertEqual(0, rv, output)1479 self.assertFalse(initial_file.has_section('compa'))1480 self.assertIn('compa', self.env.config)1481 self.assertIn('1', self.env.config.parser.get('compa', 'opt1'))1482 self.assertIn('2', self.env.config.parser.get('compa', 'opt2'))1483class TracAdminInitenvTestCase(TracAdminTestCaseBase):1484 def setUp(self):1485 self.parent_dir = tempfile.mkdtemp()1486 self.env_path = os.path.join(self.parent_dir, 'trac')1487 self._admin = TracAdmin(self.env_path)1488 def tearDown(self):1489 if os.path.isfile(os.path.join(self.env_path, 'VERSION')):1490 self._admin.env.shutdown()1491 rmtree(self.parent_dir)1492 def test_config_argument(self):1493 """Options contained in file specified by the --config argument1494 are written to trac.ini.1495 """1496 config_file = os.path.join(self.parent_dir, 'config.ini')1497 create_file(config_file, """\1498[the-plugin]1499option_a = 11500option_b = 21501[components]1502the_plugin.* = enabled1503[project]1504name = project21505 """)1506 rv, output = self._execute('initenv project1 sqlite:db/sqlite.db '1507 '--config=%s' % config_file)1508 env = Environment(self.env_path)1509 cfile = env.config.parser1510 self.assertEqual(0, rv, output)1511 self.assertEqual('1', cfile.get('the-plugin', 'option_a'))1512 self.assertEqual('2', cfile.get('the-plugin', 'option_b'))1513 self.assertEqual('enabled', cfile.get('components', 'the_plugin.*'))1514 self.assertEqual('project1', cfile.get('project', 'name'))1515 self.assertEqual('sqlite:db/sqlite.db', cfile.get('trac', 'database'))1516 for (section, name), option in \1517 Option.get_registry(env.compmgr).iteritems():1518 if (section, name) not in \1519 (('trac', 'database'), ('project', 'name')):1520 self.assertEqual(option.default, cfile.get(section, name))1521 def test_config_argument_has_invalid_path(self):1522 """Exception is raised when --config argument is an invalid path."""1523 config_file = os.path.join(self.parent_dir, 'config.ini')1524 rv, output = self._execute('initenv project1 sqlite:db/sqlite.db '1525 '--config=%s' % config_file)1526 self.assertEqual(2, rv, output)1527 self.assertExpectedResult(output, {1528 'env_path': self.env_path,1529 'config_file': config_file,1530 })1531 def test_config_argument_has_invalid_value(self):1532 """Exception is raised when --config argument specifies a malformed1533 configuration file.1534 """1535 config_file = os.path.join(self.parent_dir, 'config.ini')1536 create_file(config_file, """\1537[the-plugin]1538option_a = 11539[components1540the_plugin.* = enabled1541 """)1542 rv, output = self._execute('initenv project1 sqlite:db/sqlite.db '1543 '--config=%s' % config_file)1544 self.assertEqual(2, rv, output)1545 self.assertExpectedResult(output, {1546 'env_path': self.env_path,1547 'config_file': config_file,1548 })1549class TracAdminDeployTestCase(TracAdminTestCaseBase):1550 """Tests for the trac-admin deploy command."""1551 def setUp(self):1552 self.env = Environment(path=tempfile.mkdtemp(), create=True)1553 self._admin = TracAdmin(self.env.path)1554 self._admin.env_set('', self.env)1555 def tearDown(self):1556 self.env.shutdown() # really closes the db connections1557 rmtree(self.env.path)1558 def test_deploy(self):1559 """Deploy into valid target directory."""1560 target = os.path.join(self.env.path, 'www')1561 htdocs_dir = os.path.join(target, 'htdocs')1562 rv, output = self._execute('deploy %s' % target)1563 self.assertEqual(0, rv, output)1564 self.assertExpectedResult(output)1565 self.assertTrue(os.path.exists(os.path.join(target, 'cgi-bin')))1566 self.assertTrue(os.path.exists(htdocs_dir))1567 self.assertTrue(os.path.exists(os.path.join(htdocs_dir, 'common')))1568 self.assertTrue(os.path.exists(os.path.join(htdocs_dir, 'site')))1569 def test_deploy_to_invalid_target_raises_error(self):1570 """Running deploy with target directory equal to or below the source1571 directory raises AdminCommandError.1572 """1573 rv, output = self._execute('deploy %s' % self.env.htdocs_dir)1574 self.assertEqual(2, rv, output)1575 self.assertExpectedResult(output)1576def test_suite():1577 suite = unittest.TestSuite()1578 suite.addTest(unittest.makeSuite(TracadminTestCase))1579 suite.addTest(unittest.makeSuite(TracadminNoEnvTestCase))1580 suite.addTest(unittest.makeSuite(TracAdminHelpMacroTestCase))1581 if __name__ == 'trac.admin.tests.console':1582 suite.addTest(unittest.makeSuite(TracAdminComponentTestCase))1583 else:1584 print("SKIP: trac.admin.tests.console.TracAdminComponentTestCase "1585 "(__name__ is not trac.admin.tests.console)")1586 suite.addTest(unittest.makeSuite(TracAdminInitenvTestCase))1587 suite.addTest(unittest.makeSuite(TracAdminDeployTestCase))...
dragonfly.py
Source:dragonfly.py
...78 bound=outbound[2])79 while not self.is_port_open:80 self.serial_obj = Serial(port=self.port, baudrate=115200, timeout=0)81 self.is_port_open = self.serial_obj.is_open82 self._execute("set_standby", standby_mode=0)83 self._execute("set_disk_speed", speed=6000)84 self.speed_reply = self._execute("get_disk_speed")85 while find_digits(self.speed_reply) < 5950:86 self._execute("start_disk")87 self.speed_reply = self._execute("get_disk_speed")88 time.sleep(1)89 self._execute("set_modality_bf")90 self._execute("set_filter_speed", filter_port=1, filter_speed=2)91 self._execute("set_filter", filter_port=1, filter_number=4)92 self._execute("set_filter_speed", filter_port=2, filter_speed=2)93 self._execute("set_filter", filter_port=2, filter_number=4)94 self._execute("set_emission_dichroic", emission=3)95 self._execute("set_disk_dichroic", dichroic=1)96 self._execute("set_fieldstop", fieldstop_mode=2)97 self.publish_status()98 print("Dragonfly: Initialized")99 def set_standby(self, mode=0):100 """Sets the standby mode."""101 if mode in (0, 1):102 self._execute("set_standby", standby_mode=mode)103 self.publish_status()104 def set_disk_speed(self, speed=6000):105 """Sets the disk speed."""106 if 0 < speed < 6001:107 self._execute("set_disk_speed", speed=speed)108 reply = self._execute("get_disk_speed")109 while find_digits(reply) < (int(speed)-100):110 self._execute("start_disk")111 reply = self._execute("get_disk_speed")112 self.publish_status()113 def set_imaging_mode(self, mode):114 """Sets the confocal mode."""115 if mode in (1, 2, 3):116 if mode == 1:117 self._execute("set_modality_bf")118 elif mode in (2, 3):119 self._execute("set_modality_confocal")120 if mode == 2:121 self._execute("set_confocal_40")122 else:123 self._execute("set_confocal_25")124 self.publish_status()125 def set_fieldstop(self, mode):126 """Sets the imaging field of view."""127 if 0 < mode < 11:128 self._execute("set_fieldstop", fieldstop_mode=mode)129 self.publish_status()130 def set_filter(self, port, number):131 """Sets the Filter."""132 if 0 < number < 9:133 self._execute("set_filter", filter_port=port, filter_number=number)134 self.publish_status()135 def set_filter_speed(self, port, speed):136 """Sets the filter speed."""137 if 0 < speed < 4:138 self._execute("set_filter_speed", filter_port=port, filter_speed=speed)139 self.publish_status()140 def set_emission_dichroic(self, pos):141 """Sets the emission dichroic."""142 if 0 < pos < 4:143 self._execute("set_emission_dichroic", emission=pos)144 self.publish_status()145 def set_disk_dichroic(self, pos):146 """Sets disk dichroic."""147 if pos in (1, 2):148 self._execute("set_disk_dichroic", emission=pos)149 self.publish_status()150 def shutdown(self):151 """Shuts down the device"""152 self.device_status = 0153 self.publish_status()154 self._execute("stop_disk")155 self._execute("set_standby", standby_mode=1)156 self.serial_obj.close()157 self.serial_obj.__del__()158 def update_status(self):159 """Updates status dictionary."""160 self.status["disk_speed"] = find_digits(self._execute("get_disk_speed"))161 self.status["filter_1"] = self._execute("get_filter", filter_port=1)[:-3]162 self.status["filter_2"] = self._execute("get_filter", filter_port=2)[:-3]163 self.status["filter_1_speed"] = self._execute("get_filter_speed", filter_port=1)[:-3]164 self.status["filter_2_speed"] = self._execute("get_filter_speed", filter_port=2)[:-3]165 self.status["field_stop"] = self._execute("get_fieldstop")[:-3]166 self.status["Imaging Mode"] = self._execute("get_modality")[:-3]167 self.status["Disc Dichroic"] = self._execute("get_disk_dichroic")[:-3]168 self.status["Emission Dichroic"] = self._execute("get_emission_dichroic")[:-3]169 if self._execute("get_confocal_mode")[:-3] == "1":170 self.status["Pinhole Size"] = "40um"171 elif self._execute("get_confocal_mode")[:-3] == "2":172 self.status["Pinhole Size"] = "25um"173 elif self._execute("get_confocal_mode")[:-3] == "-1":174 self.status["Pinhole Size"] = "NA"175 self.status["device"] = self.device_status176 def publish_status(self):177 """Publishes the status to the hub and logger."""178 self.update_status()179 self.status_publisher.send("hub " + json.dumps({self.name: self.status}, default=int))180 self.status_publisher.send("logger "+ json.dumps({self.name: self.status}, default=int))181 def _execute(self, cmd: str, **kwargs):182 cmd_format_string = self._COMMANDS[cmd]183 formatted_string = cmd_format_string.format(**kwargs)184 reply = b''185 self.serial_obj.write(bytes(formatted_string, "ascii"))186 while not reply:187 reply = self.serial_obj.readline()188 return reply.decode("utf-8")189 def run(self):190 """Starts a loop and receives and processes a message."""191 self.command_subscriber.flush()192 while self.device_status:193 req = self.command_subscriber.recv()194 self.command_subscriber.process(req)195def find_digits(message):...
Shell.py
Source:Shell.py
2import os3class Shell(object):4 # @classmethod5 # def ls(cls, arguments=None):6 # return cls._execute(sh.ls, arguments)7 @classmethod8 def _execute(cls, f, *args, **kwargs):9 args = args or []10 kws = kwargs or {}11 return f(*args, **kws)12# args = list(*arguments)13# if len(args) == 0:14# return f().rstrip('\n')15# else:16# return f(args).rstrip('\n')17 @classmethod18 def git(cls, *args, **kwargs):19 return cls._execute(sh.git, *args, **kwargs)20 21 @classmethod22 def VBoxManage(cls, *args, **kwargs):23 return cls._execute(sh.VBoxManage, *args, **kwargs)24 @classmethod25 def blockdiag(cls, *args, **kwargs):26 return cls._execute(sh.blockdiag , *args, **kwargs)27 28 @classmethod29 def cm(cls, *args, **kwargs):30 return cls._execute(sh.cm, *args, **kwargs)31 32 @classmethod33 def fgmetric(cls, *args, **kwargs):34 return cls._execute(sh.fgmetric, *args, **kwargs)35 36 @classmethod37 def fgrep(cls, *args, **kwargs):38 return cls._execute(sh.fgrep, *args, **kwargs)39 40 @classmethod41 def gchproject(cls, *args, **kwargs):42 return cls._execute(sh.gchproject, *args, **kwargs)43 44 @classmethod45 def gchuser(cls, *args, **kwargs):46 return cls._execute(sh.gchuser, *args, **kwargs)47 48 @classmethod49 def glusers(cls, *args, **kwargs):50 return cls._execute(sh.glusers, *args, **kwargs)51 52 @classmethod53 def gmkproject(cls, *args, **kwargs):54 return cls._execute(sh.gmkproject, *args, **kwargs)55 56 @classmethod57 def grep(cls, *args, **kwargs):58 return cls._execute(sh.grep, *args, **kwargs)59 60 @classmethod61 def gstatement(cls, *args, **kwargs):62 return cls._execute(sh.gstatement, *args, **kwargs)63 64 @classmethod65 def head(cls, *args, **kwargs):66 return cls._execute(sh.head, *args, **kwargs)67 68 @classmethod69 def keystone(cls, *args, **kwargs):70 return cls._execute(sh.keystone, *args, **kwargs)71 72 @classmethod73 def kill(cls, *args, **kwargs):74 return cls._execute(sh.kill, *args, **kwargs)75 @classmethod76 def ls(cls, *args, **kwargs):77 return cls._execute(sh.ls, *args, **kwargs)78 79 @classmethod80 def mkdir(cls, newdir):81 """works the way a good mkdir should :)82 - already exists, silently complete83 - regular file in the way, raise an exception84 - parent directory(ies) does not exist, make them as well85 """86 """http://code.activestate.com/recipes/82465-a-friendly-mkdir/"""87 if os.path.isdir(newdir):88 pass89 elif os.path.isfile(newdir):90 raise OSError("a file with the same name as the desired "91 "dir, '%s', already exists." % newdir)92 else:93 head, tail = os.path.split(newdir)94 if head and not os.path.isdir(head):95 mkdir(head)96 if tail:97 os.mkdir(newdir)98 @classmethod99 def mongoimport(cls, *args, **kwargs):100 return cls._execute(sh.mongoimport, *args, **kwargs)101 102 @classmethod103 def mysql(cls, *args, **kwargs):104 return cls._execute(sh.mysql, *args, **kwargs)105 106 @classmethod107 def nosetests(cls, *args, **kwargs):108 return cls._execute(sh.nosetests, pwd, *args, **kwargs)109 110 @classmethod111 def nova(cls, *args, **kwargs):112 return cls._execute(sh.nova, *args, **kwargs)113 114 @classmethod115 def pwd(cls, *args, **kwargs):116 return cls._execute(sh.pwd, *args, **kwargs)117 118 @classmethod119 def rackdiag(cls, *args, **kwargs):120 return cls._execute(sh.rackdiag, *args, **kwargs)121 122 @classmethod123 def rm(cls, *args, **kwargs):124 return cls._execute(sh.rm, *args, **kwargs)125 126 @classmethod127 def rsync(cls, *args, **kwargs):128 return cls._execute(sh.rsync, *args, **kwargs)129 130 @classmethod131 def scp(cls, *args, **kwargs):132 return cls._execute(sh.scp, *args, **kwargs)133 134 @classmethod135 def sort(cls, *args, **kwargs):136 return cls._execute(sh.sort, *args, **kwargs)137 138 @classmethod139 def ssh(cls, *args, **kwargs):140 return cls._execute(sh.ssh, *args, **kwargs)141 142 @classmethod143 def sudo(cls, *args, **kwargs):144 return cls._execute(sh.sudo, *args, **kwargs)145 146 @classmethod147 def tail(cls, *args, **kwargs):148 return cls._execute(sh.tail, *args, **kwargs)149 150 @classmethod151 def vagrant(cls, *args, **kwargs):152 return cls._execute(sh.vagrant, *args, **kwargs) 153 154 @classmethod155 def mongod(cls, *args, **kwargs):156 return cls._execute(sh.mongod, *args, **kwargs)157 158if __name__ == "__main__":159 print Shell.ls("-1")160 print Shell.ls()161 print Shell.ls("-A", "-G") ...
webelement.py
Source:webelement.py
1# Copyright 2013 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4from command_executor import Command5class WebElement(object):6 """Represents an HTML element."""7 def __init__(self, chromedriver, id_):8 self._chromedriver = chromedriver9 self._id = id_10 def _Execute(self, command, params=None):11 if params is None:12 params = {}13 params['id'] = self._id;14 return self._chromedriver.ExecuteCommand(command, params)15 def FindElement(self, strategy, target):16 return self._Execute(17 Command.FIND_CHILD_ELEMENT, {'using': strategy, 'value': target})18 def FindElements(self, strategy, target):19 return self._Execute(20 Command.FIND_CHILD_ELEMENTS, {'using': strategy, 'value': target})21 def GetText(self):22 return self._Execute(Command.GET_ELEMENT_TEXT)23 def GetAttribute(self,name):24 return self._Execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})25 def GetProperty(self,name):26 return self._Execute(Command.GET_ELEMENT_PROPERTY, {'name': name})27 def HoverOver(self):28 self._Execute(Command.HOVER_OVER_ELEMENT)29 def Click(self):30 self._Execute(Command.CLICK_ELEMENT)31 def SingleTap(self):32 self._Execute(Command.TOUCH_SINGLE_TAP)33 def DoubleTap(self):34 self._Execute(Command.TOUCH_DOUBLE_TAP)35 def LongPress(self):36 self._Execute(Command.TOUCH_LONG_PRESS)37 def Clear(self):38 self._Execute(Command.CLEAR_ELEMENT)39 def SendKeys(self, *values):40 typing = []41 for value in values:42 if isinstance(value, int):43 value = str(value)44 for i in range(len(value)):45 typing.append(value[i])46 self._Execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})47 def SendKeysW3c(self, text):48 self._Execute(Command.SEND_KEYS_TO_ELEMENT, {'text': text})49 def GetLocation(self):50 return self._Execute(Command.GET_ELEMENT_LOCATION)51 def GetRect(self):52 return self._Execute(Command.GET_ELEMENT_RECT)53 def IsDisplayed(self):54 return self._Execute(Command.IS_ELEMENT_DISPLAYED)55 def TakeElementScreenshot(self):...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!