source: mergebot/trunk/utils/test.py @ 56

Last change on this file since 56 was 56, checked in by retracile, 15 years ago

Mergebot: pair of bugfixes

File size: 16.4 KB
RevLine 
[16]1#!/usr/bin/python
2"""Automated tests for MergeBot
[41]3
4Run from a Trac source tree with mergebot installed system-wide.  (This needs
5to be reworked to be less cumbersome.)
[16]6"""
7
8import os
9import unittest
10import time
11import shutil
12
13from subprocess import call, Popen #, PIPE, STDOUT
14from twill.errors import TwillAssertionError
15
16
[40]17from trac.tests.functional import FunctionalTestSuite, FunctionalTester, FunctionalTwillTestCaseSetup, tc, b, logfile
18from trac.tests.functional.svntestenv import SvnFunctionalTestEnvironment
[54]19from trac.tests.contentgen import random_page, random_sentence #, random_word
[16]20
21
[17]22#class MergeBotTestEnvironment(FunctionalTestEnvironment):
23#    """Slight change to FunctionalTestEnvironment to keep the PYTHONPATH from
24#    our environment.
25#    """
26#    def start(self):
27#        """Starts the webserver"""
28#        server = Popen(["python", "./trac/web/standalone.py",
29#                        "--port=%s" % self.port, "-s",
30#                        "--basic-auth=trac,%s," % self.htpasswd,
31#                        self.tracdir],
32#                       #env={'PYTHONPATH':'.'},
33#                       stdout=logfile, stderr=logfile,
34#                      )
35#        self.pid = server.pid
36#        time.sleep(1) # Give the server time to come up
37#
38#    def _tracadmin(self, *args):
39#        """Internal utility method for calling trac-admin"""
40#        if call(["python", "./trac/admin/console.py", self.tracdir] +
41#                list(args),
42#                #env={'PYTHONPATH':'.'},
43#                stdout=logfile, stderr=logfile):
44#            raise Exception('Failed running trac-admin with %r' % (args, ))
45#
46#
47#FunctionalTestEnvironment = MergeBotTestEnvironment
[16]48
49
50class MergeBotFunctionalTester(FunctionalTester):
51    """Adds some MergeBot functionality to the functional tester."""
52    # FIXME: the tc.find( <various actions> ) checks are bogus: any ticket can
53    # satisfy them, not just the one we're working on.
[44]54    def __init__(self, trac_url, repo_url):
55        FunctionalTester.__init__(self, trac_url)
56        self.repo_url = repo_url
[16]57        self.mergeboturl = self.url + '/mergebot'
58
59    def wait_until_find(self, search, timeout=5):
60        start = time.time()
61        while time.time() - start < timeout:
62            try:
[45]63                #tc.reload() # This appears to re-POST
64                tc.go(b.get_url())
[16]65                tc.find(search)
66                return
67            except TwillAssertionError:
68                pass
69        raise TwillAssertionError("Unable to find %r within %s seconds" % (search, timeout))
70
71    def wait_until_notfind(self, search, timeout=5):
72        start = time.time()
73        while time.time() - start < timeout:
74            try:
[45]75                #tc.reload() # This appears to re-POST
76                tc.go(b.get_url())
[16]77                tc.notfind(search)
78                return
79            except TwillAssertionError:
80                pass
81        raise TwillAssertionError("Unable to notfind %r within %s seconds" % (search, timeout))
82
83    def go_to_mergebot(self):
84        tc.go(self.mergeboturl)
85        tc.url(self.mergeboturl)
86        tc.notfind('No handler matched request to /mergebot')
87
88    def branch(self, ticket_id, component, timeout=1):
89        """timeout is in seconds."""
90        self.go_to_mergebot()
91        tc.formvalue('ops-%s' % ticket_id, 'ticket', ticket_id) # Essentially a noop to select the right form
92        tc.submit('Branch')
[44]93        self.wait_until_find('Nothing in the queue', timeout)
[16]94        tc.find('Rebranch')
95        tc.find('Merge')
96        tc.find('CheckMerge')
97        self.go_to_ticket(ticket_id)
98        tc.find('Created branch from .* for .*')
99        retval = call(['svn', 'ls', self.repo_url + '/' + component + '/branches/ticket-%s' % ticket_id],
100                    stdout=logfile, stderr=logfile)
101        if retval:
102            raise Exception('svn ls failed with exit code %s' % retval)
103
[44]104    def rebranch(self, ticket_id, component, timeout=15):
[16]105        """timeout is in seconds."""
106        self.go_to_mergebot()
107        tc.formvalue('ops-%s' % ticket_id, 'ticket', ticket_id) # Essentially a noop to select the right form
108        tc.submit('Rebranch')
[44]109        self.wait_until_find('Nothing in the queue', timeout)
[16]110        tc.find('Rebranch')
111        tc.find('Merge')
112        tc.find('CheckMerge')
113        self.go_to_ticket(ticket_id)
[56]114        tc.find('(Rebranched from .* for .*|There were conflicts on rebranching)')
[16]115        retval = call(['svn', 'ls', self.repo_url + '/' + component + '/branches/ticket-%s' % ticket_id],
116                    stdout=logfile, stderr=logfile)
117        if retval:
118            raise Exception('svn ls failed with exit code %s' % retval)
119
120    def merge(self, ticket_id, component, timeout=5):
121        """timeout is in seconds."""
122        self.go_to_mergebot()
123        tc.formvalue('ops-%s' % ticket_id, 'ticket', ticket_id) # Essentially a noop to select the right form
124        tc.submit('Merge')
[44]125        self.wait_until_find('Nothing in the queue', timeout)
[16]126        tc.find('Branch')
127        self.go_to_ticket(ticket_id)
128        tc.find('Merged .* to .* for')
129        # TODO: We may want to change this to remove the "dead" branch
130        retval = call(['svn', 'ls', self.repo_url + '/' + component + '/branches/ticket-%s' % ticket_id],
131                    stdout=logfile, stderr=logfile)
132        if retval:
133            raise Exception('svn ls failed with exit code %s' % retval)
134
135    def checkmerge(self, ticket_id, component, timeout=5):
136        """timeout is in seconds."""
137        self.go_to_mergebot()
138        tc.formvalue('ops-%s' % ticket_id, 'ticket', ticket_id) # Essentially a noop to select the right form
139        tc.submit('CheckMerge')
[44]140        self.wait_until_find('Nothing in the queue', timeout)
[16]141        tc.find('Rebranch')
142        tc.find('Merge')
143        tc.find('CheckMerge')
144        self.go_to_ticket(ticket_id)
145        tc.find('while checking merge of')
146        # TODO: We may want to change this to remove the "dead" branch
147        retval = call(['svn', 'ls', self.repo_url + '/' + component + '/branches/ticket-%s' % ticket_id],
148                    stdout=logfile, stderr=logfile)
149        if retval:
150            raise Exception('svn ls failed with exit code %s' % retval)
151
152
153class MergeBotTestSuite(FunctionalTestSuite):
154    def setUp(self):
155        port = 8889
156        baseurl = "http://localhost:%s" % port
[40]157        self._testenv = SvnFunctionalTestEnvironment("testenv%s" % port, port, baseurl)
[16]158
159        # Configure mergebot
160        env = self._testenv.get_trac_environment()
161        env.config.set('components', 'mergebot.web_ui.mergebotmodule', 'enabled')
[40]162        env.config.save()
[44]163        os.mkdir(os.path.join("testenv%s" % port, 'trac', 'mergebot'))
[40]164        self._testenv._tracadmin('upgrade') # sets up the bulk of the mergebot config
165        env.config.parse_if_needed()
[16]166        env.config.set('mergebot', 'repository_url', self._testenv.repo_url())
167        env.config.set('logging', 'log_type', 'file')
168        env.config.save()
169        env.config.parse_if_needed()
170
171        self._testenv.start()
[44]172        self._tester = MergeBotFunctionalTester(baseurl, self._testenv.repo_url())
[47]173        os.system('mergebotdaemon -f "%s" > %s/mergebotdaemon.log 2>&1 &' % (self._testenv.tracdir, self._testenv.tracdir))
[40]174        self.fixture = (self._testenv, self._tester)
[16]175
176        # Setup some common component stuff for MergeBot's use:
177        svnurl = self._testenv.repo_url()
178        for component in ['stuff', 'flagship', 'submarine']:
179            self._tester.create_component(component)
180            if call(['svn', '-m', 'Create tree for "%s".' % component, 'mkdir',
181                     svnurl + '/' + component,
182                     svnurl + '/' + component + '/trunk',
183                     svnurl + '/' + component + '/tags',
184                     svnurl + '/' + component + '/branches'],
185                    stdout=logfile, stderr=logfile):
186                raise Exception("svn mkdir failed")
187
188        self._tester.create_version('trunk')
189
190
[51]191class FunctionalSvnTestCaseSetup(FunctionalTwillTestCaseSetup):
192    def get_workdir(self):
193        return os.path.join(self._testenv.dirname, self.__class__.__name__)
194
195    def checkout(self, ticket_id=None):
196        """checkout a working copy of the branch for the given ticket, or trunk if none given"""
197        if ticket_id is None:
198            svnurl = self._testenv.repo_url() + '/stuff/trunk'
199        else:
200            svnurl = self._testenv.repo_url() + '/stuff/branches/ticket-%s' % ticket_id
201        retval = call(['svn', 'checkout', svnurl, self.get_workdir()],
202            stdout=logfile, stderr=logfile)
203        self.assertEqual(retval, 0, "svn checkout failed with error %s" % (retval))
204
205    def switch(self, ticket_id=None):
206        if ticket_id is None:
207            svnurl = self._testenv.repo_url() + '/stuff/trunk'
208        else:
209            svnurl = self._testenv.repo_url() + '/stuff/branches/ticket-%s' % ticket_id
210        retval = call(['svn', 'switch', svnurl, self.get_workdir()],
211            stdout=logfile, stderr=logfile)
212        self.assertEqual(retval, 0, "svn checkout failed with error %s" % (retval))
213
214    def add_new_file(self, filename=None):
215        workdir = self.get_workdir()
216        if filename is None:
217            newfile = os.path.join(workdir, self.__class__.__name__)
218        else:
219            newfile = os.path.join(workdir, filename)
220        open(newfile, 'w').write(random_page())
221        retval = call(['svn', 'add', newfile],
222            cwd=workdir,
223            stdout=logfile, stderr=logfile)
224        self.assertEqual(retval, 0, "svn add failed with error %s" % (retval))
225
226    def commit(self, message, files=None):
227        if files is None:
228            files = ['.']
[54]229        commit_message = self.__class__.__name__ + ": " + message
230        retval = call(['svn', 'commit', '-m', commit_message] + list(files),
[51]231            cwd=self.get_workdir(),
232            stdout=logfile, stderr=logfile)
233        self.assertEqual(retval, 0, "svn commit failed with error %s" % (retval))
234
235
[17]236class MergeBotTestEnabled(FunctionalTwillTestCaseSetup):
[16]237    def runTest(self):
238        self._tester.logout()
239        tc.go(self._tester.url)
240        self._tester.login('admin')
241        tc.follow('MergeBot')
242        mergeboturl = self._tester.url + '/mergebot'
243        tc.url(mergeboturl)
244        tc.notfind('No handler matched request to /mergebot')
245
246
[17]247class MergeBotTestNoVersion(FunctionalTwillTestCaseSetup):
[16]248    """Verify that if a ticket does not have the version field set, it will not
249    appear in the MergeBot list.
250    """
251    def runTest(self):
252        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
253            info={'component':'stuff', 'version':''})
254        tc.follow('MergeBot')
255        tc.notfind(self.__class__.__name__)
256
257
[17]258class MergeBotTestBranch(FunctionalTwillTestCaseSetup):
[16]259    def runTest(self):
260        """Verify that the 'branch' button works"""
261        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
262            info={'component':'stuff', 'version':'trunk'})
263        self._tester.branch(ticket_id, 'stuff')
264
265
[17]266class MergeBotTestRebranch(FunctionalTwillTestCaseSetup):
[16]267    def runTest(self):
268        """Verify that the 'rebranch' button works"""
269        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
270            info={'component':'stuff', 'version':'trunk'})
271        self._tester.branch(ticket_id, 'stuff')
272        self._tester.rebranch(ticket_id, 'stuff')
273
274
[17]275class MergeBotTestMerge(FunctionalTwillTestCaseSetup):
[16]276    def runTest(self):
277        """Verify that the 'merge' button works"""
278        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
279            info={'component':'stuff', 'version':'trunk'})
280        self._tester.branch(ticket_id, 'stuff')
281        self._tester.merge(ticket_id, 'stuff')
282
283
[17]284class MergeBotTestCheckMerge(FunctionalTwillTestCaseSetup):
[16]285    def runTest(self):
286        """Verify that the 'checkmerge' button works"""
287        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
288            info={'component':'stuff', 'version':'trunk'})
289        self._tester.branch(ticket_id, 'stuff')
290        self._tester.checkmerge(ticket_id, 'stuff')
291
292
[51]293class MergeBotTestRebranchWithChange(FunctionalSvnTestCaseSetup):
[46]294    def runTest(self):
295        """Verify that the 'rebranch' button works with changes on the branch"""
296        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
297            info={'component':'stuff', 'version':'trunk'})
298        self._tester.branch(ticket_id, 'stuff')
299
300        # checkout a working copy & make a change
[51]301        self.checkout(ticket_id)
[46]302        # Create & add a new file
[51]303        self.add_new_file()
304        self.commit('Add a new file')
[46]305
306        self._tester.rebranch(ticket_id, 'stuff')
307
308
[51]309class MergeBotTestRebranchWithChangeAndTrunkChange(FunctionalSvnTestCaseSetup):
310    def runTest(self):
[52]311        """Verify that the 'rebranch' button works with changes on the branch and trunk"""
[51]312        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
313            info={'component':'stuff', 'version':'trunk'})
314        self._tester.branch(ticket_id, 'stuff')
315
316        # checkout a working copy & make a change
317        self.checkout(ticket_id)
318        # Create & add a new file
319        basename = self.__class__.__name__
320        self.add_new_file(basename + '-ticket')
321        self.commit('Add a new file on ticket')
322        self.switch()
323        self.add_new_file(basename + '-trunk')
324        self.commit('Add a new file on trunk')
325
326        self._tester.rebranch(ticket_id, 'stuff')
327
328
[54]329class MergeBotTestRebranchWithConflict(FunctionalSvnTestCaseSetup):
330    def runTest(self):
331        """Verify that the 'rebranch' button works with conflicts on the branch and trunk"""
332        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
333            info={'component':'stuff', 'version':'trunk'})
334        basename = self.__class__.__name__
335
336        # create a file in which to have conflicts
337        self.checkout()
338        self.add_new_file(basename)
339        self.commit('Add a new file on trunk')
340
341        # create the branch
342        self._tester.branch(ticket_id, 'stuff')
343
344        # modify the file on trunk
345        open(os.path.join(self.get_workdir(), basename), 'a').write(random_sentence())
346        self.commit('Modify the file on trunk')
347
348        # modify the file on the branch
349        self.switch(ticket_id)
350        open(os.path.join(self.get_workdir(), basename), 'a').write(random_sentence())
351        self.commit('Modify the file on branch')
352
353        self._tester.rebranch(ticket_id, 'stuff')
354
355
[17]356class MergeBotTestSingleUseCase(FunctionalTwillTestCaseSetup):
[16]357    def runTest(self):
358        """Create a branch, make a change, checkmerge, and merge it."""
359        ticket_id = self._tester.create_ticket(summary=self.__class__.__name__,
360            info={'component':'stuff', 'version':'trunk'})
361        self._tester.branch(ticket_id, 'stuff')
362        # checkout a working copy & make a change
363        svnurl = self._testenv.repo_url()
364        workdir = os.path.join(self._testenv.dirname, self.__class__.__name__)
365        retval = call(['svn', 'checkout', svnurl + '/stuff/branches/ticket-%s' % ticket_id, workdir],
366            stdout=logfile, stderr=logfile)
367        self.assertEqual(retval, 0, "svn checkout failed with error %s" % (retval))
368        # Create & add a new file
369        newfile = os.path.join(workdir, self.__class__.__name__)
370        open(newfile, 'w').write(random_page())
371        retval = call(['svn', 'add', self.__class__.__name__],
372            cwd=workdir,
373            stdout=logfile, stderr=logfile)
374        self.assertEqual(retval, 0, "svn add failed with error %s" % (retval))
375        retval = call(['svn', 'commit', '-m', 'Add a new file', self.__class__.__name__],
376            cwd=workdir,
377            stdout=logfile, stderr=logfile)
378        self.assertEqual(retval, 0, "svn commit failed with error %s" % (retval))
379
380        self._tester.checkmerge(ticket_id, 'stuff')
381        self._tester.merge(ticket_id, 'stuff')
382
383        shutil.rmtree(workdir) # cleanup working copy
384
385
386def suite():
387    suite = MergeBotTestSuite()
388    suite.addTest(MergeBotTestEnabled())
389    suite.addTest(MergeBotTestNoVersion())
390    suite.addTest(MergeBotTestBranch())
[45]391    suite.addTest(MergeBotTestRebranch())
[16]392    suite.addTest(MergeBotTestCheckMerge())
[45]393    suite.addTest(MergeBotTestMerge())
[46]394    suite.addTest(MergeBotTestRebranchWithChange())
[51]395    suite.addTest(MergeBotTestRebranchWithChangeAndTrunkChange())
[54]396    suite.addTest(MergeBotTestRebranchWithConflict())
[16]397    suite.addTest(MergeBotTestSingleUseCase())
398    return suite
399
400if __name__ == '__main__':
401    unittest.main(defaultTest='suite')
Note: See TracBrowser for help on using the repository browser.