Beispiel #1
0
    def _test_timerange(self, cached_repository):
        self.env.config.set('git', 'cached_repository', cached_repository)

        self._git_init()
        filename = os.path.join(self.repos_path, '.gitignore')
        start = datetime(2000, 1, 1, 0, 0, 0, 0, utc)
        ts = datetime(2014, 2, 5, 15, 24, 6, 0, utc)
        for idx in xrange(3):
            create_file(filename, 'commit-%d.txt' % idx)
            self._git_commit('-a', '-m', 'commit %d' % idx, date=ts)
        self._add_repository()
        repos = self._repomgr.get_repository('gitrepos')
        repos.sync()

        revs = [repos.youngest_rev]
        while True:
            parents = repos.parent_revs(revs[-1])
            if not parents:
                break
            revs.extend(parents)
        self.assertEqual(4, len(revs))

        csets = list(repos.get_changesets(start, ts))
        self.assertEqual(1, len(csets))
        self.assertEqual(revs[-1], csets[0].rev)  # is oldest rev

        csets = list(repos.get_changesets(start, ts + timedelta(seconds=1)))
        self.assertEqual(revs, [cset.rev for cset in csets])
Beispiel #2
0
    def setUp(self):
        tmpdir = os.path.realpath(tempfile.gettempdir())
        self.env = EnvironmentStub(enable=['trac.*', AuthzPolicy], path=tmpdir)
        self.env.config.set('trac', 'permission_policies',
                            'AuthzPolicy, DefaultPermissionPolicy')
        self.env.config.set('ticket', 'restrict_owner', True)

        self.perm_sys = PermissionSystem(self.env)
        self.env.insert_known_users([
            ('user1', '', ''), ('user2', '', ''),
            ('user3', '', ''), ('user4', '', '')
        ])
        self.perm_sys.grant_permission('user1', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user2', 'TICKET_VIEW')
        self.perm_sys.grant_permission('user3', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user4', 'TICKET_MODIFY')
        self.authz_file = os.path.join(tmpdir, 'trac-authz-policy')
        create_file(self.authz_file)
        self.env.config.set('authz_policy', 'authz_file', self.authz_file)
        self.ctlr = TicketSystem(self.env).action_controllers[0]
        self.req1 = Mock(authname='user1', args={},
                         perm=PermissionCache(self.env, 'user1'))
        self.ticket = Ticket(self.env)
        self.ticket['status'] = 'new'
        self.ticket.insert()
Beispiel #3
0
    def runTest(self):
        env = self._testenv.get_trac_environment()
        env.config.set('components', 'RaiseExceptionPlugin.*', 'enabled')
        env.config.save()
        create_file(os.path.join(env.path, 'plugins', 'RaiseExceptionPlugin.py'),
"""\
from trac.core import Component, implements
from trac.web.api import IRequestHandler

url = 'http://trac-hacks.org/wiki/HelloWorldMacro'

class RaiseExceptionPlugin(Component):
    implements(IRequestHandler)

    def match_request(self, req):
        if req.path_info == '/raise-exception':
            return True

    def process_request(self, req):
        raise Exception

""")

        try:
            tc.go(self._tester.url + '/raise-exception')
            tc.find(internal_error)
            tc.find('<form class="newticket" method="get" '
                    'action="http://trac-hacks.org/newticket">')
            tc.find('<input type="hidden" name="component" '
                    'value="HelloWorldMacro" />')
        finally:
            env.config.set('components', 'RaiseExceptionPlugin.*', 'disabled')
Beispiel #4
0
    def test_get_historian(self):
        paths = [u'normal-path.txt',
                 u'tickét.tx\\t',
                 u'\a\b\t\n\v\f\r\x1b"\\.tx\\t']

        for path in paths:
            path_utf8 = path.encode('utf-8')
            create_file(os.path.join(self.repos_path, path_utf8))
            self._git('add', path_utf8)
        self._git_commit('-m', 'ticket:11180 and ticket:11198',
                         date=datetime(2013, 4, 30, 17, 48, 57))

        def validate(path, quotepath):
            self._git('config', 'core.quotepath', quotepath)
            storage = self._storage()
            rev = storage.head()
            with storage.get_historian('HEAD', path) as historian:
                hrev = storage.last_change('HEAD', path, historian)
                self.assertEquals(rev, hrev)

        validate(paths[0], 'true')
        validate(paths[0], 'false')
        validate(paths[1], 'true')
        validate(paths[1], 'false')
        validate(paths[2], 'true')
        validate(paths[2], 'false')
Beispiel #5
0
    def test_inherit_multiple(self):
        class Foo(object):
            option_b = Option("b", "option2", "default")

        base = os.path.dirname(self.filename)
        relsite1 = os.path.join("sub1", "trac-site1.ini")
        site1 = os.path.join(base, relsite1)
        relsite2 = os.path.join("sub2", "trac-site2.ini")
        site2 = os.path.join(base, relsite2)
        os.mkdir(os.path.dirname(site1))
        create_file(site1, "[a]\noption1 = x\n" "[c]\noption = 1\npath1 = site1\n")
        try:
            os.mkdir(os.path.dirname(site2))
            create_file(site2, "[b]\noption2 = y\n" "[c]\noption = 2\npath2 = site2\n")
            try:
                self._write(["[inherit]", "file = %s, %s" % (relsite1, relsite2)])
                config = self._read()
                self.assertEqual("x", config.get("a", "option1"))
                self.assertEqual("y", config.get("b", "option2"))
                self.assertEqual("1", config.get("c", "option"))
                self.assertEqual(os.path.join(base, "site1"), config.getpath("c", "path1"))
                self.assertEqual(os.path.join(base, "site2"), config.getpath("c", "path2"))
                self.assertEqual("", config.getpath("c", "path3"))
                self.assertEqual(os.path.join(base, "site4"), config.getpath("c", "path4", "site4"))
            finally:
                os.remove(site2)
                os.rmdir(os.path.dirname(site2))
        finally:
            os.remove(site1)
            os.rmdir(os.path.dirname(site1))
Beispiel #6
0
    def test_coarse_permissions(self):
        # Granted to all due to wildcard
        self.assertPathPerm(True, 'unknown')
        self.assertPathPerm(True, 'joe')
        self.assertRevPerm(True, 'unknown')
        self.assertRevPerm(True, 'joe')
        # Granted if at least one fine permission is granted
        self.policy._mtime = 0
        create_file(self.authz, """\
[/somepath]
joe = r
denied =
[module:/otherpath]
jane = r
$anonymous = r
[inactive:/not-in-this-instance]
unknown = r
""")
        self.assertPathPerm(None, 'unknown')
        self.assertRevPerm(None, 'unknown')
        self.assertPathPerm(None, 'denied')
        self.assertRevPerm(None, 'denied')
        self.assertPathPerm(True, 'joe')
        self.assertRevPerm(True, 'joe')
        self.assertPathPerm(True, 'jane')
        self.assertRevPerm(True, 'jane')
        self.assertPathPerm(True, 'anonymous')
        self.assertRevPerm(True, 'anonymous')
Beispiel #7
0
 def test_existing(self):
     util.create_file(self.path, 'Some content')
     self.assertEqual('Some content', util.read_file(self.path))
     with util.AtomicFile(self.path) as f:
         f.write('Some new content')
     self.assertEqual(True, f.closed)
     self.assertEqual('Some new content', util.read_file(self.path))
Beispiel #8
0
    def test_sync(self):
        self._git_init()
        for idx in xrange(3):
            filename = 'file%d.txt' % idx
            create_file(os.path.join(self.repos_path, filename))
            self._git('add', filename)
            self._git_commit('-a', '-m', filename,
                             date=datetime(2014, 2, 2, 17, 12, idx))
        self._add_repository('gitrepos')
        repos = self._repomgr.get_repository('gitrepos')
        revs = [entry[1] for entry in repos.repos.get_node('').get_history()]
        revs.reverse()
        revs2 = []
        def feedback(rev):
            revs2.append(rev)
        repos.sync(feedback=feedback)
        self.assertEqual(revs, revs2)
        self.assertEqual(4, len(revs2))

        revs2 = []
        def feedback_1(rev):
            revs2.append(rev)
            if len(revs2) == 2:
                raise StopSync
        def feedback_2(rev):
            revs2.append(rev)
        try:
            repos.sync(feedback=feedback_1, clean=True)
        except StopSync:
            self.assertEqual(revs[:2], revs2)
            repos.sync(feedback=feedback_2)  # restart sync
        self.assertEqual(revs, revs2)
Beispiel #9
0
 def setUp(self):
     self.parent_dir = tempfile.mkdtemp(prefix="trac-")
     self.tracignore = os.path.join(self.parent_dir, ".tracignore")
     for dname in self.dirs:
         os.mkdir(os.path.join(self.parent_dir, dname))
     for fname in self.files:
         create_file(os.path.join(self.parent_dir, fname))
     self.environ = {"trac.env_paths": [], "trac.env_parent_dir": self.parent_dir}
Beispiel #10
0
 def test_existing(self):
     util.create_file(self.path, 'Some content')
     self.assertEqual('Some content', util.read_file(self.path))
     f = util.AtomicFile(self.path)
     try:
         f.write('Some new content')
     finally:
         f.close()
     self.assertEqual('Some new content', util.read_file(self.path))
Beispiel #11
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.repos_path = tempfile.mkdtemp(prefix='trac-gitrepos')
     self.git_bin = locate('git')
     # create git repository and master branch
     self._git('init', self.repos_path)
     create_file(os.path.join(self.repos_path, '.gitignore'))
     self._git('add', '.gitignore')
     self._git('commit', '-a', '-m', 'test')
Beispiel #12
0
 def test_existing_open_for_reading(self):
     util.create_file(self.path, 'Initial file content')
     self.assertEqual('Initial file content', util.read_file(self.path))
     with open(self.path) as rf:
         with util.AtomicFile(self.path) as f:
             f.write('Replaced content')
     self.assertEqual(True, rf.closed)
     self.assertEqual(True, f.closed)
     self.assertEqual('Replaced content', util.read_file(self.path))
Beispiel #13
0
 def setUp(self):
     self.status = None
     self.headers = None
     self.response = StringIO()
     self.dir = tempfile.mkdtemp(prefix='trac-')
     self.filename = os.path.join(self.dir, 'test.txt')
     self.data = 'contents\n'
     create_file(self.filename, self.data, 'wb')
     self.req = None
Beispiel #14
0
    def test_parse_authz_malformed_raises(self):
        """ConfigurationError should be raised if the file is malformed."""
        create_file(self.authz_file, """\
wiki:WikiStart]
änon = WIKI_VIEW
* =
""")
        authz_policy = AuthzPolicy(self.env)
        self.assertRaises(ConfigurationError, authz_policy.parse_authz)
Beispiel #15
0
 def test_migrate_with_plugin_py_to_sqlite_env(self):
     dburi = get_dburi()
     if dburi == 'sqlite::memory:':
         dburi = 'sqlite:db/trac.db'
     self._create_env(self.src_path, dburi)
     plugin_name = self._generate_module_name() + '.py'
     create_file(os.path.join(self.src_path, 'plugins', plugin_name),
                 _plugin_py)
     self._test_migrate_with_plugin_to_sqlite_env()
Beispiel #16
0
    def test_parse_authz_no_settings(self):
        """Allow the file to have no settings."""
        create_file(self.authz_file, """\
# [wiki:WikiStart]
# änon = WIKI_VIEW
# * =
""")
        authz_policy = AuthzPolicy(self.env)
        authz_policy.parse_authz()
        self.assertEqual([], authz_policy.authz.sections())
Beispiel #17
0
 def test_unicode_filename(self):
     create_file(os.path.join(self.repos_path, 'tickét.txt'))
     self._git('add', 'tickét.txt')
     self._git('commit', '-m', 'unicode-filename')
     storage = self._storage()
     filenames = sorted(fname for mode, type, sha, size, fname
                              in storage.ls_tree('HEAD'))
     self.assertEquals(unicode, type(filenames[0]))
     self.assertEquals(unicode, type(filenames[1]))
     self.assertEquals(u'.gitignore', filenames[0])
     self.assertEquals(u'tickét.txt', filenames[1])
Beispiel #18
0
 def setUp(self):
     self.parent_dir = tempfile.mkdtemp(prefix='trac-')
     self.tracignore = os.path.join(self.parent_dir, '.tracignore')
     for dname in self.dirs:
         os.mkdir(os.path.join(self.parent_dir, dname))
     for fname in self.files:
         create_file(os.path.join(self.parent_dir, fname))
     self.environ = {
        'trac.env_paths': [],
        'trac.env_parent_dir': self.parent_dir,
     }
Beispiel #19
0
    def test_parse_authz_no_settings(self):
        """Allow the file to have no settings."""
        create_file(
            self.authz_file,
            """\
# [wiki:WikiStart]
# änon = WIKI_VIEW
# * =
""",
        )
        self.authz_policy.parse_authz()
        self.assertFalse(self.authz_policy.authz)
Beispiel #20
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.repos_path = tempfile.mkdtemp(prefix='trac-gitrepos-')
     # create git repository and master branch
     self._git('init')
     self._git('config', 'core.quotepath', 'true')  # ticket:11198
     self._git('config', 'user.name', "Joé")  # passing utf-8 bytes
     self._git('config', 'user.email', "*****@*****.**")
     create_file(os.path.join(self.repos_path, '.gitignore'))
     self._git('add', '.gitignore')
     self._git_commit('-a', '-m', 'test',
                      date=datetime(2013, 1, 1, 9, 4, 57))
Beispiel #21
0
    def test_turn_off_persistent_cache(self):
        # persistent_cache is enabled
        parent_rev = self._factory(False).getInstance().youngest_rev()

        create_file(os.path.join(self.repos_path, 'newfile.txt'))
        self._git('add', 'newfile.txt')
        self._git_commit('-m', 'test_turn_off_persistent_cache',
                         date=datetime(2014, 1, 29, 13, 13, 25))

        # persistent_cache is disabled
        rev = self._factory(True).getInstance().youngest_rev()
        self.assertNotEqual(rev, parent_rev)
Beispiel #22
0
 def test_shared_htdocs_dir_file_is_found(self):
     from trac.web.api import RequestDone
     def send_file(path, mimetype):
         raise RequestDone
     req = Request(path_info='/chrome/shared/trac_logo.png',
                   send_file=send_file)
     shared_htdocs_dir = os.path.join(self.env.path, 'chrome', 'shared')
     os.makedirs(shared_htdocs_dir)
     create_file(os.path.join(shared_htdocs_dir, 'trac_logo.png'))
     self.env.config.set('inherit', 'htdocs_dir', shared_htdocs_dir)
     self.assertTrue(self.chrome.match_request(req))
     self.assertRaises(RequestDone, self.chrome.process_request, req)
Beispiel #23
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.repos_path = tempfile.mkdtemp(prefix='trac-gitrepos-')
     self.git_bin = locate('git')
     # create git repository and master branch
     self._git('init', self.repos_path)
     self._git('config', 'core.quotepath', 'true')  # ticket:11198
     self._git('config', 'user.name', u"Joé")
     self._git('config', 'user.email', "*****@*****.**")
     create_file(os.path.join(self.repos_path, '.gitignore'))
     self._git('add', '.gitignore')
     self._git('commit', '-a', '-m', 'test')
Beispiel #24
0
 def _create_merge_commit(self):
     for idx, branch in enumerate(('alpha', 'beta')):
         self._git('checkout', '-b', branch, 'master')
         for n in xrange(2):
             filename = 'file-%s-%d.txt' % (branch, n)
             create_file(os.path.join(self.repos_path, filename))
             self._git('add', filename)
             self._git_commit('-a', '-m', filename,
                              date=datetime(2014, 2, 2, 17, 12,
                                            n * 2 + idx))
     self._git('checkout', 'alpha')
     self._git('merge', '-m', 'Merge branch "beta" to "alpha"', 'beta')
Beispiel #25
0
 def _git_init(self, data=True, bare=False):
     if bare:
         self._git('init', '--bare')
     else:
         self._git('init')
     if not bare and data:
         self._git('config', 'user.name', 'Joe')
         self._git('config', 'user.email', '*****@*****.**')
         create_file(os.path.join(self.repos_path, '.gitignore'))
         self._git('add', '.gitignore')
         self._git_commit('-a', '-m', 'test',
                          date=datetime(2001, 1, 29, 16, 39, 56))
Beispiel #26
0
    def test_get_branches_with_cr_in_commitlog(self):
        # regression test for #11598
        message = 'message with carriage return'.replace(' ', '\r')

        create_file(os.path.join(self.repos_path, 'ticket11598.txt'))
        self._git('add', 'ticket11598.txt')
        self._git_commit('-m', message,
                         date=datetime(2013, 5, 9, 11, 5, 21))

        storage = self._storage()
        branches = sorted(storage.get_branches())
        self.assertEqual('master', branches[0][0])
        self.assertEqual(1, len(branches))
Beispiel #27
0
 def test_existing_open_for_reading(self):
     util.create_file(self.path, 'Initial file content')
     self.assertEqual('Initial file content', util.read_file(self.path))
     rf = open(self.path)
     try:
         f = util.AtomicFile(self.path)
         try:
             f.write('Replaced content')
         finally:
             f.close()
     finally:
         rf.close()
     self.assertEqual('Replaced content', util.read_file(self.path))
Beispiel #28
0
    def test_get_branches_with_cr_in_commitlog(self):
        # regression test for #11598
        message = 'message with carriage return'.replace(' ', '\r')

        create_file(os.path.join(self.repos_path, 'ticket11598.txt'))
        self._git('add', 'ticket11598.txt')
        self._git('commit', '-m', message,
                  '--date', 'Thu May 9 20:05:21 2013 +0900')

        storage = self._storage()
        branches = sorted(storage.get_branches())
        self.assertEquals('master', branches[0][0])
        self.assertEquals(1, len(branches))
Beispiel #29
0
 def test_get_historian_with_unicode_path(self):
     # regression test for #11180
     create_file(os.path.join(self.repos_path, 'tickét.txt'))
     self._git('add', 'tickét.txt')
     self._git('commit', '-m', 'ticket:11180',
               '--date', 'Thu May 9 04:31 2013 +0900')
     storage = self._storage()
     rev = storage.head()
     self.assertNotEqual(None, rev)
     with storage.get_historian('HEAD', u'tickét.txt') as historian:
         self.assertNotEqual(None, historian)
         self.assertEquals(rev, storage.last_change('HEAD', u'tickét.txt',
                                                    historian))
Beispiel #30
0
 def setUp(self, module_class):
     self.path = tempfile.mkdtemp(prefix='trac-')
     if self.authz_policy is not None:
         self.authz_file = os.path.join(self.path, 'authz_policy.conf')
         create_file(self.authz_file, self.authz_policy)
         self.env = EnvironmentStub(enable=['trac.*', AuthzPolicy],
                                    path=self.path)
         self.env.config.set('authz_policy', 'authz_file', self.authz_file)
         self.env.config.set('trac', 'permission_policies',
                             'AuthzPolicy, DefaultPermissionPolicy')
     else:
         self.env = EnvironmentStub(path=self.path)
     self.req_handler = module_class(self.env)
Beispiel #31
0
    def test_sync_after_removing_branch(self):
        self._git('checkout', '-b', 'b1', 'master')
        self._git('checkout', 'master')
        create_file(os.path.join(self.repos_path, 'newfile.txt'))
        self._git('add', 'newfile.txt')
        self._git_commit('-m',
                         'added newfile.txt to master',
                         date=datetime(2013, 12, 23, 6, 52, 23))

        storage = self._storage()
        storage.sync()
        self.assertEqual(['b1', 'master'],
                         sorted(b[0] for b in storage.get_branches()))
        self._git('branch', '-D', 'b1')
        self.assertTrue(storage.sync())
        self.assertEqual(['master'],
                         sorted(b[0] for b in storage.get_branches()))
        self.assertFalse(storage.sync())
    def test_set_owner_fine_grained_permissions(self):
        """Fine-grained permission checks when populating the restricted
        owners list (#10833).
        """
        self.env.config.set('trac', 'show_full_names', False)
        create_file(self.authz_file, """\
[ticket:1]
user4 = !TICKET_MODIFY
""")

        ctrl = self.ctlr.render_ticket_action_control(self.req1, self.ticket,
                                                      'reassign')

        self.assertEqual('reassign', ctrl[0])
        self.assertIn('value="user1">user1</option>', str(ctrl[1]))
        self.assertNotIn('value="user2">user2</option>', str(ctrl[1]))
        self.assertIn('value="user3">user3</option>', str(ctrl[1]))
        self.assertNotIn('value="user4">user4</option>', str(ctrl[1]))
Beispiel #33
0
    def test_ls_tree(self):
        paths = [u'normal-path.txt',
                 u'tickét.tx\\t',
                 u'\a\b\t\n\v\f\r\x1b"\\.tx\\t']
        for path in paths:
            path_utf8 = path.encode('utf-8')
            create_file(os.path.join(self.repos_path, path_utf8))
            self._git('add', path_utf8)
        self._git_commit('-m', 'ticket:11180 and ticket:11198',
                         date=datetime(2013, 4, 30, 13, 48, 57))

        storage = self._storage()
        rev = storage.head()
        entries = storage.ls_tree(rev, '/')
        self.assertEqual(4, len(entries))
        self.assertEqual(u'\a\b\t\n\v\f\r\x1b"\\.tx\\t', entries[0][4])
        self.assertEqual(u'.gitignore', entries[1][4])
        self.assertEqual(u'normal-path.txt', entries[2][4])
        self.assertEqual(u'tickét.tx\\t', entries[3][4])
Beispiel #34
0
    def test_config_argument_has_invalid_value(self):
        """Exception is raised when --config argument specifies a malformed
        configuration file.
        """
        config_file = os.path.join(self.parent_dir, 'config.ini')
        create_file(config_file, textwrap.dedent("""\
            [the-plugin]
            option_a = 1
            [components
            the_plugin.* = enabled
            """))
        rv, output = self.execute('initenv project1 sqlite:db/sqlite.db '
                                   '--config=%s' % config_file)

        self.assertEqual(2, rv, output)
        self.assertExpectedResult(output, {
            'env_path': self.env_path,
            'config_file': config_file,
        })
Beispiel #35
0
    def test_get_historian_with_unicode_chars(self):
        paths = ['normal-path.txt', 'ŧïckét.txt']
        for path in paths:
            create_file(os.path.join(self.repos_path, path))
            self._git('add', path)
        self._git_commit('-m', 'ticket:11180 and ticket:11198')

        def validate(path, quotepath):
            self._git('config', 'core.quotepath', quotepath)
            storage = self._storage()
            rev = storage.head()
            with storage.get_historian('HEAD', path) as historian:
                hrev = storage.last_change('HEAD', path, historian)
                self.assertEqual(rev, hrev)

        validate(paths[0], 'true')
        validate(paths[0], 'false')
        validate(paths[1], 'true')
        validate(paths[1], 'false')
Beispiel #36
0
 def _build_egg_file(self, module_name):
     plugin_src = os.path.join(self.env.path, 'plugin_src')
     os.mkdir(plugin_src)
     os.mkdir(os.path.join(plugin_src, module_name))
     create_file(os.path.join(plugin_src, 'setup.py'),
                 _setup_py % {'name': module_name})
     create_file(os.path.join(plugin_src, module_name, '__init__.py'),
                 _plugin_py)
     proc = subprocess.Popen((sys.executable, 'setup.py', 'bdist_egg'),
                             cwd=plugin_src,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=close_fds)
     proc.communicate(input='')
     for f in (proc.stdin, proc.stdout, proc.stderr):
         f.close()
     for filename in glob.glob(os.path.join(plugin_src, 'dist', '*-*.egg')):
         return filename
Beispiel #37
0
    def runTest(self):
        env = self._testenv.get_trac_environment()
        env.config.set('components', 'RaiseExceptionPlugin.*', 'enabled')
        env.config.save()
        create_file(
            os.path.join(env.path, 'plugins', 'RaiseExceptionPlugin.py'), """\
from trac.core import Component, implements
from trac.web.api import IRequestHandler

url = None

class RaiseExceptionPlugin(Component):
    implements(IRequestHandler)

    def match_request(self, req):
        if req.path_info.startswith('/raise-exception'):
            return True

    def process_request(self, req):
        print('maybe?')
        if req.args.get('report') == 'tho':
            global url
            url = 'http://trac-hacks.org/wiki/HelloWorldMacro'
        raise Exception

""")
        self._testenv.restart()

        try:
            tc.go(self._tester.url + '/raise-exception')
            tc.find(internal_error)
            tc.find('<form class="newticket" method="get" '
                    'action="http://trac.edgewall.org/newticket">')

            tc.go(self._tester.url + '/raise-exception?report=tho')
            tc.find(internal_error)
            tc.find('<form class="newticket" method="get" '
                    'action="http://trac-hacks.org/newticket">')
            tc.find('<input type="hidden" name="component" '
                    'value="HelloWorldMacro" />')
        finally:
            env.config.set('components', 'RaiseExceptionPlugin.*', 'disabled')
Beispiel #38
0
    def runTest(self):
        plugin_name = self.__class__.__name__
        env = self._testenv.get_trac_environment()
        env.config.set('components', plugin_name + '.*', 'enabled')
        env.config.save()
        create_file(
            os.path.join(env.path, 'plugins', plugin_name + '.py'), """\
from genshi.builder import tag
from trac.core import Component, implements
from trac.util.translation import tag_
from trac.wiki.api import IWikiPageManipulator


class WikiPageManipulator(Component):
    implements(IWikiPageManipulator)

    def prepare_wiki_page(self, req, page, fields):
        pass

    def validate_wiki_page(self, req, page):
        field = 'comment'
        yield None, tag_("The page contains invalid markup at"
                         " line %(number)s.", number=tag.strong('10'))
        yield field, tag_("The field %(field)s cannot be empty.",
                          field=tag.strong(field))
""")
        self._testenv.restart()

        try:
            self._tester.go_to_front()
            tc.follow("Wiki")
            tc.formvalue('modifypage', 'action', 'edit')
            tc.submit()
            tc.submit('save', 'edit')
            tc.url(self._tester.url + '/wiki/WikiStart$')
            tc.find("Invalid Wiki page: The page contains invalid markup at"
                    " line <strong>10</strong>.")
            tc.find("The Wiki page field <strong>comment</strong> is invalid:"
                    " The field <strong>comment</strong> cannot be empty.")
        finally:
            env.config.set('components', plugin_name + '.*', 'disabled')
            env.config.save()
Beispiel #39
0
    def test_undefined_action_is_logged(self):
        """Undefined action is logged at warning level."""
        create_file(
            self.authz_file, """\
[wiki:WikiStart]
änon = UNKNOWN_VIEW, WIKI_VIEW
[milestone:milestone1]
* = UNKNOWN_EDIT
""")
        authz_policy = AuthzPolicy(self.env)
        authz_policy.parse_authz()

        self.assertIn(('WARNING', 'The action UNKNOWN_VIEW in the '
                       '[wiki:WikiStart] section of '
                       'trac-authz-policy is not a valid action.'),
                      self.env.log_messages)
        self.assertIn(('WARNING', 'The action UNKNOWN_EDIT in the '
                       '[milestone:milestone1] section of '
                       'trac-authz-policy is not a valid action.'),
                      self.env.log_messages)
Beispiel #40
0
    def test_render_child_preferences_panels(self):
        create_file(
            os.path.join(self.templates_dir, self.child1_template_name),
            self.child_template)
        create_file(
            os.path.join(self.templates_dir, self.child2_template_name),
            self.child_template)

        req = MockRequest(self.env, path_info='/prefs/panel1')
        mod = PreferencesModule(self.env)

        self.assertTrue(mod.match_request(req))
        resp = mod.process_request(req)

        self.assertEqual('prefs_panel_1.html', resp[0])
        self.assertEqual(2, len(resp[1]['children']))
        self.assertEqual(('child1', 'Child 1', Markup(u'<h2>Child 1</h2>')),
                         resp[1]['children'][0])
        self.assertEqual(('child2', 'Child 2', Markup(u'<h2>Child 2</h2>')),
                         resp[1]['children'][1])
Beispiel #41
0
    def test_single_file_plugin_metadata(self):
        """Metadata is read from single-file plugins."""
        plugin_metadata = {
            'author': 'Trac Hacks',
            'author_email': '*****@*****.**',
            'home_page': 'https://trac-hacks.org/wiki/SingleFilePlugin',
            'license': 'BSD',
            'summary': 'The single-file plugin',
            'trac': 'https://my.trac.com',
        }
        plugin_content = """\
from trac.core import Component

author = '%(author)s'
author_email = '%(author_email)s'
home_page = '%(home_page)s'
license = '%(license)s'
summary = '%(summary)s'
trac = '%(trac)s'


class SingleFilePlugin(Component):
    pass
""" % plugin_metadata

        file_path = os.path.join(self.env.plugins_dir, 'single_file_plugin.py')
        os.mkdir(self.env.plugins_dir)
        create_file(file_path, plugin_content)
        load_components(self.env, (self.env.plugins_dir, ))

        req = MockRequest(self.env)
        panel = PluginAdminPanel(self.env)
        data = panel.render_admin_panel(req, 'general', 'plugin', None)[1]

        discovered_metadata = {}
        for item in data['plugins']:
            if item['name'] == 'single-file-plugin':
                discovered_metadata = item['info']

        for key, value in plugin_metadata.items():
            self.assertEqual(discovered_metadata[key], plugin_metadata[key])
Beispiel #42
0
    def test_rev_is_anchestor_of(self):
        # regression test for #11215
        path = os.path.join(self.repos_path, '.git')
        DbRepositoryProvider(self.env).add_repository('gitrepos', path, 'git')
        repos = self.env.get_repository('gitrepos')
        parent_rev = repos.youngest_rev

        create_file(os.path.join(self.repos_path, 'ticket11215.txt'))
        self._git('add', 'ticket11215.txt')
        self._git_commit('-m', 'ticket11215',
                         date=datetime(2013, 6, 27, 18, 26, 2))
        repos.sync()
        rev = repos.youngest_rev

        self.assertNotEqual(rev, parent_rev)
        self.assertFalse(repos.rev_older_than(None, None))
        self.assertFalse(repos.rev_older_than(None, rev[:7]))
        self.assertFalse(repos.rev_older_than(rev[:7], None))
        self.assertTrue(repos.rev_older_than(parent_rev, rev))
        self.assertTrue(repos.rev_older_than(parent_rev[:7], rev[:7]))
        self.assertFalse(repos.rev_older_than(rev, parent_rev))
        self.assertFalse(repos.rev_older_than(rev[:7], parent_rev[:7]))
Beispiel #43
0
    def test_sync(self):
        self._git_init()
        for idx in range(3):
            filename = 'file%d.txt' % idx
            create_file(os.path.join(self.repos_path, filename))
            self._git('add', filename)
            self._git_commit('-a',
                             '-m',
                             filename,
                             date=datetime(2014, 2, 2, 17, 12, idx))
        self._add_repository('gitrepos')
        repos = self._repomgr.get_repository('gitrepos')
        revs = [entry[1] for entry in repos.repos.get_node('').get_history()]
        revs.reverse()
        revs2 = []

        def feedback(rev):
            revs2.append(rev)

        repos.sync(feedback=feedback)
        self.assertEqual(revs, revs2)
        self.assertEqual(4, len(revs2))

        revs2 = []

        def feedback_1(rev):
            revs2.append(rev)
            if len(revs2) == 2:
                raise StopSync

        def feedback_2(rev):
            revs2.append(rev)

        try:
            repos.sync(feedback=feedback_1, clean=True)
        except StopSync:
            self.assertEqual(revs[:2], revs2)
            repos.sync(feedback=feedback_2)  # restart sync
        self.assertEqual(revs, revs2)
Beispiel #44
0
    def setUp(self):
        tmpdir = os.path.realpath(tempfile.gettempdir())
        self.env = EnvironmentStub(enable=['trac.*', AuthzPolicy], path=tmpdir)
        self.env.config.set('trac', 'permission_policies',
                            'AuthzPolicy, DefaultPermissionPolicy')
        self.env.config.set('ticket', 'restrict_owner', True)

        self.perm_sys = PermissionSystem(self.env)
        self.env.insert_users([('user1', 'User C', '*****@*****.**'),
                               ('user2', 'User A', '*****@*****.**'),
                               ('user3', 'User D', '*****@*****.**'),
                               ('user4', 'User B', '*****@*****.**')])
        self.perm_sys.grant_permission('user1', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user2', 'TICKET_VIEW')
        self.perm_sys.grant_permission('user3', 'TICKET_MODIFY')
        self.perm_sys.grant_permission('user4', 'TICKET_MODIFY')
        self.authz_file = os.path.join(tmpdir, 'trac-authz-policy')
        create_file(self.authz_file)
        self.env.config.set('authz_policy', 'authz_file', self.authz_file)
        self.ctlr = TicketSystem(self.env).action_controllers[0]
        self.req1 = MockRequest(self.env, authname='user1')
        self.ticket = insert_ticket(self.env, status='new')
Beispiel #45
0
    def runTest(self):
        plugin_name = self.__class__.__name__
        env = self._testenv.get_trac_environment()
        env.config.set('components', plugin_name + '.*', 'enabled')
        env.config.save()
        create_file(os.path.join(env.plugins_dir, plugin_name + '.py'),
                    _plugin_py)
        self._testenv.restart()

        try:
            self._tester.go_to_front()
            tc.follow("Wiki")
            tc.submit(formname='modifypage')
            tc.submit('save', 'edit')
            tc.url(self._tester.url + '/wiki/WikiStart', regexp=False)
            tc.find("Invalid Wiki page: The page contains invalid markup at"
                    " line <strong>10</strong>.")
            tc.find("The Wiki page field <strong>comment</strong> is invalid:"
                    " The field <strong>comment</strong> cannot be empty.")
        finally:
            env.config.set('components', plugin_name + '.*', 'disabled')
            env.config.save()
Beispiel #46
0
    def create(self, options=[], default_data=True):
        """Create the basic directory structure of the environment,
        initialize the database and populate the configuration file
        with default values.

        If options contains ('inherit', 'file'), default values will
        not be loaded; they are expected to be provided by that file
        or other options.

        :raises TracError: if the base directory of `path` does not exist.
        :raises TracError: if `path` exists and is not empty.
        """
        base_dir = os.path.dirname(self.path)
        if not os.path.exists(base_dir):
            raise TracError(
                _(
                    "Base directory '%(env)s' does not exist. Please create it "
                    "and retry.",
                    env=base_dir))

        if os.path.exists(self.path) and os.listdir(self.path):
            raise TracError(_("Directory exists and is not empty."))

        # Create the directory structure
        if not os.path.exists(self.path):
            os.mkdir(self.path)
        os.mkdir(self.htdocs_dir)
        os.mkdir(self.log_dir)
        os.mkdir(self.plugins_dir)
        os.mkdir(self.templates_dir)

        # Create a few files
        create_file(os.path.join(self.path, 'VERSION'), _VERSION + '\n')
        create_file(
            os.path.join(self.path, 'README'),
            'This directory contains a Trac environment.\n'
            'Visit https://trac.edgewall.org/ for more information.\n')

        # Setup the default configuration
        os.mkdir(self.conf_dir)
        config = Configuration(self.config_file_path)
        for section, name, value in options:
            config.set(section, name, value)
        config.save()
        self.setup_config()
        if not any((section, option) == ('inherit', 'file')
                   for section, option, value in options):
            self.config.set_defaults(self)
            self.config.save()

        # Create the sample configuration
        create_file(self.config_file_path + '.sample')
        self._update_sample_config()

        # Create the database
        dbm = DatabaseManager(self)
        dbm.init_db()
        if default_data:
            dbm.insert_default_data()
Beispiel #47
0
    def test_component_loaded_once(self):
        create_file(
            os.path.join(self.env.plugins_dir, 'RegressionTestRev6017.py'),
            """\
from trac.wiki.macros import WikiMacroBase

class RegressionTestRev6017Macro(WikiMacroBase):
    def expand_macro(self, formatter, name, content, args):
        return "Hello World"

""")

        loader.load_components(self.env)
        loader.load_components(self.env)

        loaded_components = [
            c for c in ComponentMeta._components
            if 'RegressionTestRev6017' in c.__name__
        ]

        self.assertEqual(1, len(loaded_components),
                         "Plugin loaded more than once.")
Beispiel #48
0
    def test_rev_is_anchestor_of(self):
        # regression test for #11215
        path = os.path.join(self.repos_path, '.git')
        DbRepositoryProvider(self.env).add_repository('gitrepos', path, 'git')
        repos = self.env.get_repository('gitrepos')
        parent_rev = repos.youngest_rev

        create_file(os.path.join(self.repos_path, 'ticket11215.txt'))
        self._git('add', 'ticket11215.txt')
        self._git('commit', '-m', 'ticket11215',
                  '--date', 'Fri Jun 28 03:26:02 2013 +0900')
        repos.sync()
        rev = repos.youngest_rev

        self.assertNotEqual(rev, parent_rev)
        self.assertEquals(False, repos.rev_older_than(None, None))
        self.assertEquals(False, repos.rev_older_than(None, rev[:7]))
        self.assertEquals(False, repos.rev_older_than(rev[:7], None))
        self.assertEquals(True, repos.rev_older_than(parent_rev, rev))
        self.assertEquals(True, repos.rev_older_than(parent_rev[:7], rev[:7]))
        self.assertEquals(False, repos.rev_older_than(rev, parent_rev))
        self.assertEquals(False, repos.rev_older_than(rev[:7], parent_rev[:7]))
Beispiel #49
0
    def test_undefined_action_is_logged(self):
        """Undefined action is logged at warning level."""
        create_file(self.authz_file, textwrap.dedent("""\
            [groups]
            administrators = éat
            [wiki:WikiStart]
            änon = UNKNOWN_VIEW, TEST_CREATE, !TEST_MODIFY
            [milestone:milestone1]
            * = UNKNOWN_MODIFY, !TEST_VIEW
            """))
        authz_policy = AuthzPolicy(self.env)
        authz_policy.parse_authz()

        self.assertEqual(2, len(self.env.log_messages))
        self.assertIn(('WARNING',
                       'The action UNKNOWN_VIEW in the [wiki:WikiStart] '
                       'section of trac-authz-policy is not a valid action.'),
                      self.env.log_messages)
        self.assertIn(('WARNING',
                       'The action UNKNOWN_MODIFY in the [milestone:milestone1] '
                       'section of trac-authz-policy is not a valid action.'),
                      self.env.log_messages)
Beispiel #50
0
    def test_inherit_multiple(self):
        class Foo(object):
            option_b = Option('b', 'option2', 'default')

        base = os.path.dirname(self.filename)
        relsite1 = os.path.join('sub1', 'trac-site1.ini')
        site1 = os.path.join(base, relsite1)
        relsite2 = os.path.join('sub2', 'trac-site2.ini')
        site2 = os.path.join(base, relsite2)
        os.mkdir(os.path.dirname(site1))
        create_file(site1, '[a]\noption1 = x\n'
                    '[c]\noption = 1\npath1 = site1\n')
        try:
            os.mkdir(os.path.dirname(site2))
            create_file(
                site2, '[b]\noption2 = y\n'
                '[c]\noption = 2\npath2 = site2\n')
            try:
                self._write(
                    ['[inherit]',
                     'file = %s, %s' % (relsite1, relsite2)])
                config = self._read()
                self.assertEqual('x', config.get('a', 'option1'))
                self.assertEqual('y', config.get('b', 'option2'))
                self.assertEqual('1', config.get('c', 'option'))
                self.assertEqual(os.path.join(base, 'site1'),
                                 config.getpath('c', 'path1'))
                self.assertEqual(os.path.join(base, 'site2'),
                                 config.getpath('c', 'path2'))
                self.assertEqual('', config.getpath('c', 'path3'))
                self.assertEqual(os.path.join(base, 'site4'),
                                 config.getpath('c', 'path4', 'site4'))
            finally:
                os.remove(site2)
                os.rmdir(os.path.dirname(site2))
        finally:
            os.remove(site1)
            os.rmdir(os.path.dirname(site1))
Beispiel #51
0
    def test_reset_head(self):
        self._git_init()
        create_file(os.path.join(self.repos_path, 'file.txt'), 'text')
        self._git('add', 'file.txt')
        self._git_commit('-a', '-m', 'test',
                         date=datetime(2014, 2, 2, 17, 12, 18))
        self._add_repository('gitrepos')
        repos = self._repomgr.get_repository('gitrepos')
        repos.sync()
        youngest_rev = repos.youngest_rev
        entries = list(repos.get_node('').get_history())
        self.assertEqual(2, len(entries))
        self.assertEqual('', entries[0][0])
        self.assertEqual(Changeset.EDIT, entries[0][2])
        self.assertEqual('', entries[1][0])
        self.assertEqual(Changeset.ADD, entries[1][2])

        self._git('reset', '--hard', 'HEAD~')
        repos.sync()
        new_entries = list(repos.get_node('').get_history())
        self.assertEqual(1, len(new_entries))
        self.assertEqual(new_entries[0], entries[1])
        self.assertNotEqual(youngest_rev, repos.youngest_rev)
Beispiel #52
0
    def setUp(self):
        tmpdir = os.path.realpath(tempfile.gettempdir())
        self.authz_file = os.path.join(tmpdir, 'trac-authz-policy')
        create_file(
            self.authz_file, """\
# Unicode user names
[groups]
administrators = éat

[wiki:WikiStart]
änon = WIKI_VIEW
@administrators = WIKI_VIEW
* =

# Unicode page names
[wiki:résumé]
änon =
@administrators = WIKI_VIEW
* =
""")
        self.env = EnvironmentStub(enable=[AuthzPolicy])
        self.env.config.set('authz_policy', 'authz_file', self.authz_file)
        self.authz_policy = AuthzPolicy(self.env)
Beispiel #53
0
    def create(self, options=[]):
        """Create the basic directory structure of the environment,
        initialize the database and populate the configuration file
        with default values.

        If options contains ('inherit', 'file'), default values will
        not be loaded; they are expected to be provided by that file
        or other options.
        """
        # Create the directory structure
        if not os.path.exists(self.path):
            os.mkdir(self.path)
        os.mkdir(self.get_log_dir())
        os.mkdir(self.get_htdocs_dir())
        os.mkdir(os.path.join(self.path, 'plugins'))

        # Create a few files
        create_file(os.path.join(self.path, 'VERSION'),
                    'Trac Environment Version 1\n')
        create_file(
            os.path.join(self.path, 'README'),
            'This directory contains a Trac environment.\n'
            'Visit http://trac.edgewall.org/ for more information.\n')

        # Setup the default configuration
        os.mkdir(os.path.join(self.path, 'conf'))
        create_file(os.path.join(self.path, 'conf', 'trac.ini.sample'))
        config = Configuration(os.path.join(self.path, 'conf', 'trac.ini'))
        for section, name, value in options:
            config.set(section, name, value)
        config.save()
        self.setup_config()
        if not any((section, option) == ('inherit', 'file')
                   for section, option, value in options):
            self.config.set_defaults(self)
            self.config.save()

        # Create the database
        DatabaseManager(self).init_db()
Beispiel #54
0
 def setUp(self):
     self.dir = mkdtemp()
     self.filename = os.path.join(self.dir, 'test.txt')
     self.data = 'contents\n'
     create_file(self.filename, self.data, 'wb')
     self.req = None
Beispiel #55
0
    def test_parse_file(self):
        create_file(
            self.authz_file,
            textwrap.dedent("""\
            [groups]
            developers = foo, bar
            users = @developers, &baz

            [aliases]
            baz = CN=Hàröld Hacker,OU=Enginéers,DC=red-bean,DC=com

            # Applies to all repositories
            [/]
            * = r

            [/trunk]
            @developers = rw
            &baz =
            @users = r

            [/branches]
            bar = rw

            ; Applies only to module
            [module:/trunk]
            foo = rw
            &baz = r

            ; Unicode module names
            [module:/c/résumé]
            bar = rw
            Foo = rw
            BAZ = r

            ; Unicode module names
            [module:/c/résumé]
            bar = rw
            Foo = rw
            BAZ = r

            ; Unused module, not parsed
            [unused:/some/path]
            foo = r
            """))
        authz = parse(self.authz_file, {'', 'module'})
        self.assertEqual(
            {
                '': {
                    u'/': {
                        u'*': True,
                    },
                    u'/trunk': {
                        u'foo': True,
                        u'bar': True,
                        u'CN=Hàröld Hacker,OU=Enginéers,DC=red-bean,DC=com':
                        True,
                    },
                    u'/branches': {
                        u'bar': True,
                    },
                },
                u'module': {
                    u'/trunk': {
                        u'foo': True,
                        u'CN=Hàröld Hacker,OU=Enginéers,DC=red-bean,DC=com':
                        True,
                    },
                    u'/c/résumé': {
                        u'bar': True,
                        u'Foo': True,
                        u'BAZ': True,
                    },
                },
            }, authz)
Beispiel #56
0
    def setUp(self):
        tmpdir = mkdtemp()
        self.authz_file = os.path.join(tmpdir, 'trac-authz')
        create_file(
            self.authz_file,
            textwrap.dedent("""\
            [groups]
            group1 = user
            group2 = @group1

            cycle1 = @cycle2
            cycle2 = @cycle3
            cycle3 = @cycle1, user

            alias1 = &jekyll
            alias2 = @alias1

            [aliases]
            jekyll = Mr Hyde

            # Read / write permissions
            [/readonly]
            user = r
            [/writeonly]
            user = w
            [/readwrite]
            user = rw
            [/empty]
            user =

            # Trailing slashes
            [/trailing_a]
            user = r
            [/trailing_b/]
            user = r

            # Sub-paths
            [/sub/path]
            user = r

            # Module usage
            [module:/module_a]
            user = r
            [other:/module_b]
            user = r
            [/module_c]
            user = r
            [module:/module_d]
            user =
            [/module_d]
            user = r

            # Wildcards
            [/wildcard]
            * = r

            # Special tokens
            [/special/anonymous]
            $anonymous = r
            [/special/authenticated]
            $authenticated = r

            # Groups
            [/groups_a]
            @group1 = r
            [/groups_b]
            @group2 = r
            [/cyclic]
            @cycle1 = r

            # Precedence
            [module:/precedence_a]
            user =
            [/precedence_a]
            user = r
            [/precedence_b]
            user = r
            [/precedence_b/sub]
            user =
            [/precedence_b/sub/test]
            user = r
            [/precedence_c]
            user =
            @group1 = r
            [/precedence_d]
            @group1 = r
            user =

            # Aliases
            [/aliases_a]
            &jekyll = r
            [/aliases_b]
            @alias2 = r

            # Scoped repository
            [scoped:/scope/dir1]
            joe = r
            [scoped:/scope/dir2]
            Jane = r

            # multiple entries
            [/multiple]
            $authenticated = r
            [/multiple/foo]
            joe =
            $authenticated =
            * = r
            [/multiple/bar]
            * =
            john = r
            Jane = r
            $anonymous = r
            [/multiple/baz]
            $anonymous = r
            * =
            Jane = r
            [module:/multiple/bar]
            joe = r
            john =

            # multiple entries with module and parent directory
            [/multiple/1]
            user = r
            @group1 = r
            $authenticated = r
            * = r
            [module:/multiple/1/user]
            user =
            [module:/multiple/1/group]
            @group1 =
            [module:/multiple/1/auth]
            $authenticated =
            [module:/multiple/1/star]
            * =
            [/multiple/2]
            user =
            @group1 =
            $authenticated =
            * =
            [module:/multiple/2/user]
            user = r
            [module:/multiple/2/group]
            @group1 = r
            [module:/multiple/2/auth]
            $authenticated = r
            [module:/multiple/2/star]
            * = r
            """))
        self.env = EnvironmentStub(enable=[AuthzSourcePolicy], path=tmpdir)
        self.env.config.set('trac', 'permission_policies',
                            'AuthzSourcePolicy, DefaultPermissionPolicy')
        self.env.config.set('svn', 'authz_file', self.authz_file)

        # Monkey-subclass RepositoryManager to serve mock repositories
        rm = RepositoryManager(self.env)

        class TestRepositoryManager(rm.__class__):
            def get_real_repositories(self):
                return {
                    Mock(reponame='module'),
                    Mock(reponame='other'),
                    Mock(reponame='scoped')
                }

            def get_repository(self, reponame):
                if reponame == 'scoped':

                    def get_changeset(rev):
                        if rev == 123:

                            def get_changes():
                                yield ('/dir1/file', )
                        elif rev == 456:

                            def get_changes():
                                yield ('/dir2/file', )
                        else:

                            def get_changes():
                                return iter([])

                        return Mock(get_changes=get_changes)

                    return Mock(scope='/scope', get_changeset=get_changeset)
                return Mock(scope='/')

        rm.__class__ = TestRepositoryManager
Beispiel #57
0
 def test_create_and_read_file(self):
     util.create_file(self.filename, self.data, 'wb')
     with open(self.filename, 'rb') as f:
         self.assertEqual(self.data, f.read())
     self.assertEqual(self.data, util.read_file(self.filename, 'rb'))
Beispiel #58
0
 def _commit(self, date):
     gitignore = os.path.join(self.repos_path, '.gitignore')
     create_file(gitignore, date.isoformat())
     self._git_commit('-a', '-m', date.isoformat(), date=date)
Beispiel #59
0
 def setUp(self):
     self.env = EnvironmentStub(path=mkdtemp())
     os.mkdir(self.env.templates_dir)
     filepath = os.path.join(self.env.templates_dir, self.filename)
     create_file(filepath, self.template)
     self.chrome = Chrome(self.env)
Beispiel #60
0
 def test_touch_file(self):
     util.create_file(self.filename, self.data, 'wb')
     util.touch_file(self.filename)
     with open(self.filename, 'rb') as f:
         self.assertEqual(self.data, f.read())