class BuildNotifyEmailTest(BittenNotifyBaseTest): """unit tests for BittenNotifyEmail class""" def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set('notification','smtp_enabled','true') self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BuildNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) BuildConfig(self.env, name='c', path='trunk').insert() self.build = Build(self.env, config='c', status=Build.SUCCESS, rev=123) def test_notification_is_sent_to_author(self): self.email.notify(self.build) self.assertTrue('author' in self.notifications_sent_to, 'Recipient list should contain the author') def test_notification_body_render(self): self.email.notify(self.build) output = self.email.template.generate(**self.email.data).render('text') self.assertTrue('Successful build of My Project [123]' in output) self.assertTrue('<http://example.org/trac.cgi/changeset/123>' in output)
def test_logo(self): env = EnvironmentStub(enable=[]) req = Mock(hdf=HDFWrapper(), href=Href('/trac.cgi'), base_path='/trac.cgi', path_info='') # Verify that no logo data is put in the HDF if no logo is configured env.config.set('header_logo', 'src', '') Chrome(env).populate_hdf(req, None) assert 'chrome.logo.src' not in req.hdf # Test with a relative path to the logo image req.hdf = HDFWrapper() env.config.set('header_logo', 'src', 'foo.png') Chrome(env).populate_hdf(req, None) self.assertEqual('/trac.cgi/chrome/common/foo.png', req.hdf['chrome.logo.src']) # Test with a server-relative path to the logo image req.hdf = HDFWrapper() env.config.set('header_logo', 'src', '/img/foo.png') Chrome(env).populate_hdf(req, None) self.assertEqual('/img/foo.png', req.hdf['chrome.logo.src']) # Test with an absolute path to the logo image req.hdf = HDFWrapper() env.config.set('header_logo', 'src', 'http://www.example.org/foo.png') Chrome(env).populate_hdf(req, None) self.assertEqual('http://www.example.org/foo.png', req.hdf['chrome.logo.src'])
def test_check(self): check = BotTrapCheck(self.env) req = self.req # Inspector provides the email text input field. wrong_input = "Hey, I'm a bot." data = dict(basic_token=wrong_input) req.args.update(data) field_res = check.render_registration_fields(req, data) self.assertEqual(len(field_res), 2) self.assertTrue(Markup(field_res[0]).startswith('<label>Parole:')) # 1st attempt: Wrong input. self.assertRaises(RegistrationError, check.validate_registration, req) # Ensure, that old input is restored on failure. self.assertTrue(wrong_input in Markup(field_res[0])) # Ensure, that template data dict is passed unchanged. self.assertEqual(field_res[1], data) # 2nd attempt: No input. req.args['basic_token'] = '' self.assertRaises(RegistrationError, check.validate_registration, req) # 3rd attempt: As before, but request done by authenticated user. req = Mock(authname='admin', args=self.req.args) self.assertEqual(check.validate_registration(req), None) # 4th attempt: Finally valid input. req = self.req req.args['basic_token'] = self.basic_token self.assertEqual(check.validate_registration(req), None) # 5th attempt: Fill the hidden field too. req.args['sentinel'] = "Humans can't see this? Crap - I'm superior!" self.assertRaises(RegistrationError, check.validate_registration, req)
class BuildNotifyEmailTest(BittenNotifyBaseTest): """unit tests for BittenNotifyEmail class""" def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set("notification", "smtp_enabled", "true") self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BuildNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) self.build = Build(self.env, status=Build.SUCCESS, rev=123) def test_notification_is_sent_to_author(self): self.email.notify(self.build) self.assertTrue("author" in self.notifications_sent_to, "Recipient list should contain the author") def test_notification_body_render(self): self.email.notify(self.build) output = self.email.template.generate(**self.email.data).render("text") self.assertTrue("Successful build of My Project [123]" in output) self.assertTrue("<http://example.org/trac.cgi/changeset/123>" in output)
def _create_session(self, user, authenticated=1, name='', email=''): args = dict(username=user, name=name, email=email) incookie = Cookie() incookie['trac_session'] = '123456' req = Mock(authname=bool(authenticated) and user or 'anonymous', args=args, base_path='/', chrome=dict(warnings=list()), href=Mock(prefs=lambda x: None), incookie=incookie, outcookie=Cookie(), redirect=lambda x: None) req.session = Session(self.env, req) req.session.save() return req.session
def test_nav_contributor_order(self): class TestNavigationContributor1(Component): implements(INavigationContributor) def get_active_navigation_item(self, req): return None def get_navigation_items(self, req): yield 'metanav', 'test1', 'Test 1' class TestNavigationContributor2(Component): implements(INavigationContributor) def get_active_navigation_item(self, req): return None def get_navigation_items(self, req): yield 'metanav', 'test2', 'Test 2' env = EnvironmentStub(enable=[TestNavigationContributor1, TestNavigationContributor2]) req = Mock(hdf=HDFWrapper(), href=Href('/trac.cgi'), path_info='/', base_path='/trac.cgi') chrome = Chrome(env) # Test with both items set in the order option env.config.set('trac', 'metanav', 'test2, test1') chrome.populate_hdf(req, None) node = req.hdf.getObj('chrome.nav.metanav').child() self.assertEqual('test2', node.name()) self.assertEqual('test1', node.next().name()) # Test with only test1 in the order options req.hdf = HDFWrapper() env.config.set('trac', 'metanav', 'test1') chrome.populate_hdf(req, None) node = req.hdf.getObj('chrome.nav.metanav').child() self.assertEqual('test1', node.name()) self.assertEqual('test2', node.next().name()) # Test with only test2 in the order options req.hdf = HDFWrapper() env.config.set('trac', 'metanav', 'test2') chrome.populate_hdf(req, None) node = req.hdf.getObj('chrome.nav.metanav').child() self.assertEqual('test2', node.name()) self.assertEqual('test1', node.next().name()) # Test with none in the order options (order corresponds to # registration order) req.hdf = HDFWrapper() env.config.set('trac', 'metanav', 'foo, bar') chrome.populate_hdf(req, None) node = req.hdf.getObj('chrome.nav.metanav').child() self.assertEqual('test1', node.name()) self.assertEqual('test2', node.next().name())
class BuildNotifyEmailTest(BittenNotifyBaseTest): """unit tests for BittenNotifyEmail class""" def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set('notification','smtp_enabled','true') self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BuildNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) self.build = Build(self.env, status=Build.SUCCESS, rev=123) def test_notification_is_sent_to_author(self): self.email.notify(self.build) self.assertTrue('author' in self.notifications_sent_to, 'Recipient list should contain the author')
def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set('notification','smtp_enabled','true') self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BuildNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) self.build = Build(self.env, status=Build.SUCCESS, rev=123)
def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set("notification", "smtp_enabled", "true") self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BittenNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) self.build_info = BuildInfo(self.env, Build(self.env, status=Build.SUCCESS)) self.build_info["author"] = "author"
def test_icon_links(self): env = EnvironmentStub(enable=[]) req = Mock(hdf=HDFWrapper(), href=Href('/trac.cgi'), base_path='/trac.cgi', path_info='') # No icon set in config, so no icon links env.config.set('project', 'icon', '') Chrome(env).populate_hdf(req, None) assert 'chrome.links.icon' not in req.hdf assert 'chrome.links.shortcut icon' not in req.hdf # Relative URL for icon config option env.config.set('project', 'icon', 'trac.ico') Chrome(env).populate_hdf(req, None) self.assertEqual('/trac.cgi/chrome/common/trac.ico', req.hdf['chrome.links.icon.0.href']) self.assertEqual('/trac.cgi/chrome/common/trac.ico', req.hdf['chrome.links.shortcut icon.0.href']) # URL relative to the server root for icon config option req.hdf = HDFWrapper() env.config.set('project', 'icon', '/favicon.ico') Chrome(env).populate_hdf(req, None) self.assertEqual('/favicon.ico', req.hdf['chrome.links.icon.0.href']) self.assertEqual('/favicon.ico', req.hdf['chrome.links.shortcut icon.0.href']) # Absolute URL for icon config option req.hdf = HDFWrapper() env.config.set('project', 'icon', 'http://example.com/favicon.ico') Chrome(env).populate_hdf(req, None) self.assertEqual('http://example.com/favicon.ico', req.hdf['chrome.links.icon.0.href']) self.assertEqual('http://example.com/favicon.ico', req.hdf['chrome.links.shortcut icon.0.href'])
class BittenNotifyEmailTest(BittenNotifyBaseTest): """unit tests for BittenNotifyEmail class""" def setUp(self): BittenNotifyBaseTest.setUp(self) self.env.config.set("notification", "smtp_enabled", "true") self.notifications_sent_to = [] def send(to, cc, hdrs={}): self.notifications_sent_to = to def noop(*args, **kw): pass self.email = Mock(BittenNotifyEmail, self.env, begin_send=noop, finish_send=noop, send=send) self.build_info = BuildInfo(self.env, Build(self.env, status=Build.SUCCESS)) self.build_info["author"] = "author" def test_notification_uses_default_address(self): self.email.notify(self.build_info) self.assertTrue("author" in self.notifications_sent_to, "recipient list should contain plain author") def test_notification_uses_custom_address(self): self.add_known_user("author", "Author's Name", "*****@*****.**") self.email.notify(self.build_info) self.assertTrue( "*****@*****.**" in self.notifications_sent_to, "recipient list should contain custom author's email" ) def test_notification_discards_invalid_address(self): self.add_known_user("author", "Author's Name", email=None) self.email.notify(self.build_info) self.assertTrue("author" in self.notifications_sent_to, "recipient list should only use valid custom address") def add_known_user(self, username, name, email): session = DetachedSession(self.env, username) if name is not None: session["name"] = name if email is not None: session["email"] = email session.save()
def _get_repository(reponame): return Mock(reponame=reponame, youngest_rev=YOUNGEST_REV, get_changeset=_get_changeset, normalize_rev=_normalize_rev, get_node=_get_node)
def test_get_active_navigation_item(self): req = Mock(path_info='/tickettemplate') self.assertEqual('tickettemplate', self.tt.get_active_navigation_item(req)) req = Mock(path_info='/something') self.assertNotEqual('tickettemplate', self.tt.match_request(req))
def test_match_request(self): req = Mock(path_info='/tickettemplate') self.assertEqual(True, self.tt.match_request(req)) req = Mock(path_info='/something') self.assertEqual(False, self.tt.match_request(req))
def setUp(self): self.env = \ EnvironmentStub(enable=['trac.attachment.LegacyAttachmentPolicy', 'trac.perm.*', 'trac.wiki.web_ui.ReadonlyWikiPolicy', 'trac.ticket.*']) self.policy = ReadonlyWikiPolicy(self.env) store = perm.DefaultPermissionStore(self.env) self.perm_sys = perm.PermissionSystem(self.env) users = [('user1', 'User C', '*****@*****.**'), ('user2', 'User A', '*****@*****.**'), ('user3', 'User D', '*****@*****.**'), ('user4', 'User B', '*****@*****.**')] self.env.insert_users(users) store.grant_permission('user1', 'TICKET_MODIFY') store.grant_permission('user2', 'TICKET_VIEW') store.grant_permission('user3', 'TICKET_MODIFY') store.grant_permission('user4', 'TICKET_MODIFY') for (username, fullname, email) in users: self._test_authenticated_session(username, fullname, email) self.repo = Mock(MockRepository, 'testrepo', {'name': 'testrepo', 'id': 4321}, None) # Set all component objects to defaults config = self.env.config config.set("ticket","commit_ticket_update_commands.close","close closed closes fix fixed fixes") config.set("ticket","commit_ticket_update_commands.implements","implement implements implemented impl") config.set("ticket","commit_ticket_update_commands.invalidate","invalid invalidate invalidated invalidates") config.set("ticket","commit_ticket_update_commands.refs","addresses re references refs see") config.set("ticket","commit_ticket_update_commands.rejects","reject rejects rejected") config.set("ticket","commit_ticket_update_commands.worksforme","worksforme") config.set("ticket","commit_ticket_update_commands.alreadyimplemented","alreadyimplemented already_implemented") config.set("ticket","commit_ticket_update_commands.reopen","reopen reopens reopened") config.set("ticket","commit_ticket_update_commands.testready","testready test_ready ready_for_test rft") config.set("ticket","commit_ticket_update_allowed_domains","example.org mydomain.net") #config.set("ticket","commit_ticket_update_check_perms",False) self._add_component('component3', 'user3') self.ticket = Ticket(self.env) self.ticket.populate({ 'reporter': 'user1', 'summary': 'the summary', 'component': 'component3', 'owner': 'user3', 'status': 'new', }) self.tkt_id = self.ticket.insert() self.ticket2 = Ticket(self.env) self.ticket2.populate({ 'reporter': 'user2', 'summary': 'the summary', 'component': 'component3', 'owner': 'user2', 'status': 'new', }) self.tkt2_id = self.ticket2.insert() #for username, name, email in self.env.get_known_users(): # sys.stderr.write('known user %s, %s, %s\n' % (username, name, email)) with self.env.db_transaction as db: db("INSERT INTO enum VALUES ('resolution', 'already_implemented', 6)") #db("INSERT INTO enum VALUES ('resolution', 'worksforme', 5)") self._committicketupdater = CommitTicketUpdater(self.env)
def _mock_context_with_username(self, username): context = Mock(req=Mock(authname=username)) return context
def _create_req(self, **kwargs): data = dict(args={}, perm=MockPerm(), href=Href('/'), chrome={}, authname='trac', tz=utc, get_header=lambda name: None, is_xhr=False) data.update(kwargs) return Mock(**data)
def test_utf8_size(self): connector = MySQLConnector(self.env) self.assertEqual(3, connector._max_bytes(Mock(charset='utf8'))) self.assertEqual(4, connector._max_bytes(Mock(charset='utf8mb4')))
def setUp(self): self.env = EnvironmentStub(default_data=True) self.perm = PermissionSystem(self.env) self.ticket_system = TicketSystem(self.env) self.req = Mock()
def test_clean_sync(self): t1 = datetime(2001, 1, 1, 1, 1, 1, 0, utc) t2 = datetime(2002, 1, 1, 1, 1, 1, 0, utc) t3 = datetime(2003, 1, 1, 1, 1, 1, 0, utc) self.preset_cache( (('0', to_utimestamp(t1), '', ''), []), (('1', to_utimestamp(t2), 'joe', 'Import'), [ ('trunk', 'D', 'A', None, None), ('trunk/README', 'F', 'A', None, None) ]), ) repos = self.get_repos(get_changeset=lambda x: changesets[int(x)], youngest_rev=2) changes1 = [('trunk', Node.DIRECTORY, Changeset.ADD, None, None), ('trunk/README', Node.FILE, Changeset.ADD, None, None)] changes2 = [('trunk/README', Node.FILE, Changeset.EDIT, 'trunk/README', 1)] changesets = [ Mock(Changeset, repos, 0, '**empty**', 'joe', t1, get_changes=lambda: []), Mock(Changeset, repos, 1, 'Initial Import', 'joe', t2, get_changes=lambda: iter(changes1)), Mock(Changeset, repos, 2, 'Update', 'joe', t3, get_changes=lambda: iter(changes2)) ] cache = CachedRepository(self.env, repos, self.log) cache.sync(clean=True) cursor = self.db.cursor() cursor.execute("SELECT time,author,message FROM revision") self.assertEquals((to_utimestamp(t1), 'joe', '**empty**'), cursor.fetchone()) self.assertEquals((to_utimestamp(t2), 'joe', 'Initial Import'), cursor.fetchone()) self.assertEquals((to_utimestamp(t3), 'joe', 'Update'), cursor.fetchone()) self.assertEquals(None, cursor.fetchone()) cursor.execute(""" SELECT rev,path,node_type,change_type,base_path,base_rev FROM node_change ORDER BY rev """) self.assertEquals(('1', 'trunk', 'D', 'A', None, None), cursor.fetchone()) self.assertEquals(('1', 'trunk/README', 'F', 'A', None, None), cursor.fetchone()) self.assertEquals(('2', 'trunk/README', 'F', 'E', 'trunk/README', '1'), cursor.fetchone()) self.assertEquals(None, cursor.fetchone())
def test_empty_content(self): context = Mock(env=self.env, href=Href('/'), req=self.req) formatter = Mock(context=context, req=self.req) self.assertTrue('No resources found' in str(self.tag_twm.expand_macro(formatter, 'ListTagged', '')))
class test_commitupdater(unittest.TestCase): def _test_authenticated_session(self, username, fullname, email): """ Verifies that a session cookie does not get used if the user is logged in, and that Trac expires the cookie. """ req = MockRequest(self.env, authname=username) req.incookie['trac_session'] = '123456' session = Session(self.env, req) self.assertEqual(username, session.sid) session['email'] = email session['name'] = fullname session.save() def setUp(self): self.env = \ EnvironmentStub(enable=['trac.attachment.LegacyAttachmentPolicy', 'trac.perm.*', 'trac.wiki.web_ui.ReadonlyWikiPolicy', 'trac.ticket.*']) self.policy = ReadonlyWikiPolicy(self.env) store = perm.DefaultPermissionStore(self.env) self.perm_sys = perm.PermissionSystem(self.env) users = [('user1', 'User C', '*****@*****.**'), ('user2', 'User A', '*****@*****.**'), ('user3', 'User D', '*****@*****.**'), ('user4', 'User B', '*****@*****.**')] self.env.insert_users(users) store.grant_permission('user1', 'TICKET_MODIFY') store.grant_permission('user2', 'TICKET_VIEW') store.grant_permission('user3', 'TICKET_MODIFY') store.grant_permission('user4', 'TICKET_MODIFY') for (username, fullname, email) in users: self._test_authenticated_session(username, fullname, email) self.repo = Mock(MockRepository, 'testrepo', {'name': 'testrepo', 'id': 4321}, None) # Set all component objects to defaults config = self.env.config config.set("ticket","commit_ticket_update_commands.close","close closed closes fix fixed fixes") config.set("ticket","commit_ticket_update_commands.implements","implement implements implemented impl") config.set("ticket","commit_ticket_update_commands.invalidate","invalid invalidate invalidated invalidates") config.set("ticket","commit_ticket_update_commands.refs","addresses re references refs see") config.set("ticket","commit_ticket_update_commands.rejects","reject rejects rejected") config.set("ticket","commit_ticket_update_commands.worksforme","worksforme") config.set("ticket","commit_ticket_update_commands.alreadyimplemented","alreadyimplemented already_implemented") config.set("ticket","commit_ticket_update_commands.reopen","reopen reopens reopened") config.set("ticket","commit_ticket_update_commands.testready","testready test_ready ready_for_test rft") config.set("ticket","commit_ticket_update_allowed_domains","example.org mydomain.net") #config.set("ticket","commit_ticket_update_check_perms",False) self._add_component('component3', 'user3') self.ticket = Ticket(self.env) self.ticket.populate({ 'reporter': 'user1', 'summary': 'the summary', 'component': 'component3', 'owner': 'user3', 'status': 'new', }) self.tkt_id = self.ticket.insert() self.ticket2 = Ticket(self.env) self.ticket2.populate({ 'reporter': 'user2', 'summary': 'the summary', 'component': 'component3', 'owner': 'user2', 'status': 'new', }) self.tkt2_id = self.ticket2.insert() #for username, name, email in self.env.get_known_users(): # sys.stderr.write('known user %s, %s, %s\n' % (username, name, email)) with self.env.db_transaction as db: db("INSERT INTO enum VALUES ('resolution', 'already_implemented', 6)") #db("INSERT INTO enum VALUES ('resolution', 'worksforme', 5)") self._committicketupdater = CommitTicketUpdater(self.env) def noop(self): pass def tearDown(self): self.env.reset_db() def _add_component(self, name='test', owner='owner1'): component = Component(self.env) component.name = name component.owner = owner component.insert() def build_comment(self,changeset): revstring = str(changeset.rev) drev = str(self.repo.display_rev(changeset.rev)) if self.repo.name: revstring += '/' + self.repo.name drev += '/' + self.repo.name return """In [changeset:"%s" %s]: {{{ #!CommitTicketReference repository="%s" revision="%s" %s }}}""" % (revstring, drev, self.repo.name, changeset.rev, changeset.message) def check_ticket_comment(self,changeset): for obj in [self.env]: #print('comment=%s' % self.build_comment(changeset), file=sys.stderr) self.assertEqual(self._committicketupdater.make_ticket_comment(self.repo,changeset), self.build_comment(changeset)) def test_check_closes(self): message = "Fixed some stuff. closes #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_close]) ret = ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['owner'], 'user1') self.assertEqual(ticket['resolution'], 'fixed') def test_check_implements(self): message = "Fixed some stuff. implements #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_implements]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'implemented') self.assertEqual(ticket['owner'], 'user1') def test_check_invalidate(self): message = "Fixed some stuff. invalid #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_invalidate]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['resolution'], 'invalid') def test_check_rejects(self): message = "Fixed some stuff. reject #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_rejects]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'rejected') def test_check_worksforme(self): message = "Fixed some stuff. worksforme #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_worksforme]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['resolution'], 'worksforme') def test_check_alreadyimplemented(self): message = "Fixed some stuff. alreadyimplemented #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_alreadyimplemented]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['resolution'], 'already_implemented') def test_check_already_implemented(self): message = "Fixed some stuff. already_implemented #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_alreadyimplemented]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['resolution'], 'already_implemented') def test_check_reopens(self): message = "Fixed some stuff. worksforme #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) message = "Fixed some stuff. reopen #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_reopens]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'reopened') def test_check_testready(self): message = "Fixed some stuff. ready_for_test #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_testready]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'test_ready') def test_allowed_domains(self): message = "Fixed some stuff. reopen #%i" % self.tkt_id test_changeset_declined = Mock(Changeset, self.repo, 42, message, "test_person <*****@*****.**>", None) self.assertEqual(self._committicketupdater._is_author_allowed(test_changeset_declined.author),False) test_changeset_allowed = Mock(Changeset, self.repo, 42, message, "test_person <*****@*****.**>", None) self.assertEqual(self._committicketupdater._is_author_allowed(test_changeset_allowed.author),True) test_changeset_no_domain = Mock(Changeset, self.repo, 42, message, "test_person", None) self.assertEqual(self._committicketupdater._is_author_allowed(test_changeset_no_domain.author),False) message = "Fixed some stuff. fixed #%i" % self.tkt_id test_changeset = Mock(Changeset, self.repo, 42, message, 'test_person <*****@*****.**>', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'new') def test_check_closes_multiple(self): message = "Fixed some stuff. closes #%i, #%i" % (self.tkt_id, self.tkt2_id) test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id, self.tkt2_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_close]) self.assertEqual(tickets.get(self.tkt2_id),[self._committicketupdater.cmd_close]) ret = ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['owner'], 'user1') self.assertEqual(ticket['resolution'], 'fixed') (cmds, ticket2) = ret[self.tkt2_id] self.assertEqual(ticket2['status'], 'closed') self.assertEqual(ticket2['owner'], 'user1') self.assertEqual(ticket2['resolution'], 'fixed') def test_check_closes_non_existing_ticket(self): non_existing_ticket_id = 12345 message = "Fixed some stuff. closes #%i" % non_existing_ticket_id test_changeset = Mock(Changeset, self.repo, 42, message, '*****@*****.**', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[non_existing_ticket_id]) # Now check the actions are right self.assertEqual(tickets.get(non_existing_ticket_id),[self._committicketupdater.cmd_close]) ret = ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[non_existing_ticket_id] self.assertEqual(ticket, None) def test_check_closes_with_full_email_addr(self): message = "Fixed some stuff. closes #%i" % (self.tkt_id) test_changeset = Mock(Changeset, self.repo, 42, message, 'User One <*****@*****.**>', None) self.check_ticket_comment(test_changeset) # For each object in turn: # Get tickets and commands tickets = self._committicketupdater._parse_message(message) # First, check we've got the tickets we were expecting self.assertEqual(tickets.keys(),[self.tkt_id]) # Now check the actions are right self.assertEqual(tickets.get(self.tkt_id),[self._committicketupdater.cmd_close]) ret = ret = self._committicketupdater.changeset_added_impl(self.repo, test_changeset) (cmds, ticket) = ret[self.tkt_id] self.assertEqual(ticket['status'], 'closed') self.assertEqual(ticket['owner'], 'user1') self.assertEqual(ticket['resolution'], 'fixed')
def test_sync_changeset_if_not_exists(self): t = [ datetime(2001, 1, 1, 1, 1, 1, 0, utc), # r0 datetime(2002, 1, 1, 1, 1, 1, 0, utc), # r1 datetime(2003, 1, 1, 1, 1, 1, 0, utc), # r2 datetime(2004, 1, 1, 1, 1, 1, 0, utc), # r3 ] self.preset_cache( (('0', to_utimestamp(t[0]), 'joe', '**empty**'), []), (('1', to_utimestamp(t[1]), 'joe', 'Import'), [ ('trunk', 'D', 'A', None, None), ('trunk/README', 'F', 'A', None, None) ]), # not exists r2 (('3', to_utimestamp(t[3]), 'joe', 'Add COPYING'), [ ('trunk/COPYING', 'F', 'A', None, None) ]), ) repos = self.get_repos(get_changeset=lambda x: changesets[int(x)], youngest_rev=3) changes = [ None, # r0 [ ('trunk', Node.DIRECTORY, Changeset.ADD, None, None), # r1 ('trunk/README', Node.FILE, Changeset.ADD, None, None) ], [ ('branches', Node.DIRECTORY, Changeset.ADD, None, None), # r2 ('tags', Node.DIRECTORY, Changeset.ADD, None, None) ], [('trunk/COPYING', Node.FILE, Changeset.ADD, None, None)], # r3 ] changesets = [ Mock(Changeset, repos, 0, '**empty**', 'joe', t[0], get_changes=lambda: []), Mock(Changeset, repos, 1, 'Initial Import', 'joe', t[1], get_changes=lambda: iter(changes[1])), Mock(Changeset, repos, 2, 'Created directories', 'john', t[2], get_changes=lambda: iter(changes[2])), Mock(Changeset, repos, 3, 'Add COPYING', 'joe', t[3], get_changes=lambda: iter(changes[3])), ] cache = CachedRepository(self.env, repos, self.log) self.assertRaises(NoSuchChangeset, cache.get_changeset, 2) cache.sync() self.assertRaises(NoSuchChangeset, cache.get_changeset, 2) self.assertEqual(None, cache.sync_changeset(2)) cset = cache.get_changeset(2) self.assertEqual('john', cset.author) self.assertEqual('Created directories', cset.message) self.assertEqual(t[2], cset.date) cset_changes = cset.get_changes() self.assertEqual( ('branches', Node.DIRECTORY, Changeset.ADD, None, None), cset_changes.next()) self.assertEqual(('tags', Node.DIRECTORY, Changeset.ADD, None, None), cset_changes.next()) self.assertRaises(StopIteration, cset_changes.next) rows = self.env.db_query( "SELECT time,author,message FROM revision ORDER BY rev") self.assertEquals(4, len(rows)) self.assertEquals((to_utimestamp(t[0]), 'joe', '**empty**'), rows[0]) self.assertEquals((to_utimestamp(t[1]), 'joe', 'Import'), rows[1]) self.assertEquals((to_utimestamp(t[2]), 'john', 'Created directories'), rows[2]) self.assertEquals((to_utimestamp(t[3]), 'joe', 'Add COPYING'), rows[3])
def get_changeset(rev): return Mock(Changeset, repos, rev, 'message', 'author', datetime(2001, 1, 1, tzinfo=utc))
def setUp(self): self.env = EnvironmentStub() t1 = self._insert_and_load_ticket("foo") self.filter = TicketFieldTimelineFilter(self.env) self.context = Mock(resource=t1.resource)
def get_repository(self, reponame): params = {'id': 1, 'name': reponame} return Mock(Repository, 'mock', params, self.env.log)
def test_rss(self): def render(context, field, event): if event[0] == 'test&1': if field == 'url': return 'http://example.org/path?foo=bar&baz=1' if field == 'summary': return 'summary 1: <b>&</b>' if field == 'description': return tag(tag.h1('Title 1st'), tag.p('body & < >')) if event[0] == 'test&2': if field == 'url': return 'http://example.org/path?baz=2&foo=bar' if field == 'summary': return tag('summary 2: ', tag.b('&')) if field == 'description': return tag(tag.h1('Title 2nd'), tag.p('body & < >')) provider = self.timeline_event_providers['normal'](self.env) provider._events = [ ('test&1', datetime(2018, 4, 27, 12, 34, 56, 123456, utc), 'jo&hn', Mock(render=render)), ('test&2', datetime(2018, 3, 19, 23, 56, 12, 987654, utc), 'Joe <*****@*****.**>', Mock(render=render)), ] req = MockRequest(self.env, path_info='/timeline', args={'format': 'rss'}) rv = self._process_request(req) self.assertEqual('timeline.rss', rv[0]) self.assertEqual({'content_type': 'application/rss+xml'}, rv[2]) output = self._render_template(req, *rv) self.assertIn('<title>summary 1: <b>&</b></title>', output) self.assertIn('<dc:creator>jo&hn</dc:creator>', output) self.assertIn('<pubDate>Fri, 27 Apr 2018 12:34:56 GMT</pubDate>', output) self.assertIn( '<link>http://example.org/path?foo=bar&baz=1' '</link>', output) self.assertIn( '<guid isPermaLink="false">http://example.org/path?' 'foo=bar&baz=1/1524832496123456</guid>', output) self.assertIn( '<description><h1>Title 1st</h1>' '<p>body &amp; &lt; &gt;</p>' '</description>', output) self.assertIn('<category>test&1</category>', output) self.assertIn('<title>summary 2: &</title>', output) self.assertIn('<author>Joe <[email protected]></author>', output) self.assertIn('<pubDate>Mon, 19 Mar 2018 23:56:12 GMT</pubDate>', output) self.assertIn( '<link>http://example.org/path?baz=2&foo=bar' '</link>', output) self.assertIn( '<guid isPermaLink="false">http://example.org/path?' 'baz=2&foo=bar/1521503772987654</guid>', output) self.assertIn( '<description><h1>Title 2nd</h1>' '<p>body &amp; &lt; &gt;</p>' '</description>', output) self.assertIn('<category>test&2</category>', output) self.assertEqual('<?xml version="1.0"?>', output[:21]) minidom.parseString(output) # verify valid xml
def get_changeset(rev): return Mock(Changeset, repos, rev, 'message', 'author', t)
def get_real_repositories(self): return set([ Mock(reponame='module'), Mock(reponame='other'), Mock(reponame='scoped') ])
def setUp(self): self.env = EnvironmentStub(default_data=True) self.query_module = QueryModule(self.env) req = Mock(perm=MockPerm(), args={}, href=Href('/')) self.formatter = LinkFormatter(self.env, web_context(req))
def _get_repository(reponame): return Mock(get_changeset=_get_changeset, resource=None)
def test_default_repository_not_configured(self): """Test for regression of http://trac.edgewall.org/ticket/11599.""" req = Mock(perm=MockPerm(), args={'new_path': '/'}, get_header=lambda self: None) self.assertRaises(TracError, self.cm.process_request, req)
def _get_changeset(rev=None): return Mock(message="the message. refs #1. ", rev=rev)
class TagsXmlRpcTestCase(unittest.TestCase): test_data = (('wiki', 'WikiStart', ('foo', 'bar')), ('wiki', 'SandBox', ('bar', 'war')), ('ticket', 1, ('war', 'death')), ('ticket', 2, ('death', 'destruction')), ('ticket', 3, ('foo', 'bar', 'destruction'))) perm = Mock(assert_permission=lambda x: True, has_permission=lambda x: True) req = Mock(perm=perm, authname='anonymous') def _populate_tags(self, ts): for tagspace, target, tags in self.test_data: tagspace = ts.tagspace(tagspace) tagspace.add_tags(self.req, target, tags) yield tagspace, target, tags def setUp(self): self.env = EnvironmentStub(default_data=True) from trac.log import logger_factory self.env.log = logger_factory(logtype='syslog', logfile=None, level='DEBUG', logid='Trac', format=None) self.env.path = '/' self.wiki_tag_rpc_engine = WikiTagRPCSystem(self.env) self.ticket_tag_rpc_engine = TicketTagRPCSystem(self.env) self.tag_engine = TagEngine(self.env) self.tag_engine.upgrade_environment(self.env.get_db_cnx()) self.xml_rpc_system = XMLRPCSystem(self.env) # Insert some test tickets from trac.ticket.model import Ticket for id in (1, 2, 3): ticket = Ticket(self.env) ticket['summary'] = 'Test ticket %i' % id ticket['description'] = 'Test ticket %i description' % id ticket.insert() def test_insert(self): ts = self.tag_engine.tagspace for tagspace, target, tags in self._populate_tags(ts): found_tags = tagspace.get_tags([target]) self.assertEqual(found_tags, set(tags)) def test_wiki_tagspace(self): self.assertEqual(self.wiki_tag_rpc_engine.namespace, 'wiki') def test_ticket_tagspace(self): self.assertEqual(self.ticket_tag_rpc_engine.namespace, 'ticket') def test_wiki_xmlrpc_methods(self): self.failUnless( set(self.wiki_tag_rpc_engine.xmlrpc_methods()) != None, "No xmlrpc methods for wiki namespace") def test_ticket_xmlrpc_methods(self): self.failUnless( set(self.ticket_tag_rpc_engine.xmlrpc_methods()) != None, "No xmlrpc methods for ticket namespace") def test_wiki_xmlrpc_namespace(self): self.assertEqual(self.wiki_tag_rpc_engine.xmlrpc_namespace(), "tags.wiki") def test_ticket_xmlrpc_namespace(self): self.assertEqual(self.ticket_tag_rpc_engine.xmlrpc_namespace(), "tags.ticket") def test_wiki_get_name_tags(self): wiki_start_tags = self.wiki_tag_rpc_engine.getTags( self.req, "WikiStart") self.failUnless(wiki_start_tags != None, "Can not find any tags for mock page WikiStart") def test_xmlrpc_listMethods(self): for method in self.xml_rpc_system.all_methods(self.req): namespace = method.namespace.replace('.', '_') namespaces = {} if namespace not in namespaces: namespaces[namespace] = { 'description': wiki_to_oneliner(method.namespace_description, self.env), 'methods': [], 'namespace': method.namespace, } try: namespaces[namespace]['methods'].append( (method.signature, wiki_to_oneliner(method.description, self.env), method.permission)) except Exception, e: self.fail('%s: %s\n' % (method.name, str(e)))
def test_add_link_simple(self): req = Mock(hdf=HDFWrapper()) add_link(req, 'start', '/trac/wiki') self.assertEqual('/trac/wiki', req.hdf['chrome.links.start.0.href'])
text = {} #wiki text depth = {} #document depth, 0 for index, leaf documents have depth 1 or 2 parent = {} #parent document (if depth > 0) inner = {} #defined for documents that are parents #top element indexed by depth top_element = [ 'book', 'chapter', 'section', 'section', 'section', 'section', 'section', 'section', 'section', 'section' ] env = EnvironmentStub() req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'), authname='anonymous', perm=MockPerm(), args={}) context = Context.from_request(req, 'wiki') def read_file(name): text[name] = file("wiki/" + name).read().decode('utf-8') page = WikiPage(env) page.name = name page.text = '--' page.save('', '', '::1', 0) def read_index(): index_name = "GuideIndex"
def test_add_stylesheet(self): req = Mock(cgi_location='/trac.cgi', hdf=HDFWrapper()) add_stylesheet(req, 'common/css/trac.css') self.assertEqual('text/css', req.hdf['chrome.links.stylesheet.0.type']) self.assertEqual('/trac.cgi/chrome/common/css/trac.css', req.hdf['chrome.links.stylesheet.0.href'])
def _get_changeset(rev): if rev == '1': return Mock(message="start", is_viewable=lambda perm: True) else: raise NoSuchChangeset(rev)
def test_htdocs_location(self): env = EnvironmentStub() req = Mock(hdf=HDFWrapper(), cgi_location='/trac.cgi', path_info='') Chrome(env).populate_hdf(req, None) self.assertEqual('/trac.cgi/chrome/common/', req.hdf['htdocs_location'])
def get_changeset(rev): if rev == 'invalid': raise NoSuchChangeset(rev) return Mock(Changeset, repos, rev, 'message', 'author', datetime.datetime(2001, 1, 1, tzinfo=utc))
def _expand_macro(self, argument_string=''): formatter = Mock(req=self.req()) html = self.macro.expand_macro(formatter, 'ShowPosts', argument_string) return html
def test_get_navigation_items(self): req = Mock(href=Mock(tickettemplate=lambda:"/trac-tempenv/tickettemplate")) a, b, c= self.tt.get_navigation_items(req).next() self.assertEqual('mainnav', a) self.assertEqual('tickettemplate', b)
def _wiki_to_html(self, project, wikitext): env = EnvironmentStub() req = Mock(href=Href(self.urls[project]), abs_href=Href(self.urls[project]), authname='anonymous', perm=MockPerm(), args={}) context = Context.from_request(req, 'ticket') return format_to_html(env, context, wikitext)