Source

hgapi / hgapi / testhgapi.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
from __future__ import with_statement
import unittest, doctest
import os, shutil, os.path
import hgapi 


# TODO: add better logger test
class TestHgAPI(unittest.TestCase):
    """Tests for hgapi.py
    Uses and wipes subfolders named 'test' (a.k.a repo), 'test-clone' (a.k.a clone)
    Tests are dependant on each other; named test_<number>_name for sorting
    """
    repo = hgapi.Repo("./test", user="testuser")
    clone = hgapi.Repo("./test-clone", user="testuser")

    @classmethod
    def _delete_and_create(cls, path):
        if os.path.exists(path):
            shutil.rmtree(path)
        os.mkdir(path)
        assert os.path.exists(path)

    @classmethod
    def setUpClass(cls):
        #Patch Python 3
        if hasattr(cls, "assertEqual"):
            setattr(cls, "assertEquals", cls.assertEqual)
            setattr(cls, "assertNotEquals", cls.assertNotEqual)
        TestHgAPI._delete_and_create("./test")
        #TestHgAPI._delete_and_create("./test-clone")
        TestHgAPI._delete_and_create("./original")
        #TestHgAPI._delete_and_create("./clone")

    @classmethod
    def tearDownClass(self):
        shutil.rmtree("test", ignore_errors=True)
        shutil.rmtree("test-clone", ignore_errors=True)
        shutil.rmtree("original", ignore_errors=True)
        shutil.rmtree("clone", ignore_errors=True)

    def test_000_Init(self):
        self.repo.hg_init()
        self.assertTrue(os.path.exists("test/.hg"))

    def test_010_Identity(self):
        rev = self.repo.hg_rev()
        hgid = self.repo.hg_id()
        self.assertEquals(-1, rev)
        self.assertEquals("000000000000", hgid)

    def test_020_Add(self):
        with open("test/file.txt", "w") as out:
            out.write("stuff")
        self.repo.hg_add("file.txt")
        self.assertListEqual(self.repo.hg_status()['A'], ['file.txt'])

    def test_021_Add(self):
        with open("test/foo.txt", "w") as out:
            out.write("A sample file")
        with open("test/bar.txt", "w") as out:
            out.write("Another sample file")
        self.repo.hg_add()
        self.assertListEqual(self.repo.hg_status()['A'], ['bar.txt', 'file.txt', 'foo.txt'])

    def test_030_Commit(self):
        #Commit and check that we're on a real revision
        self.repo.hg_commit("adding", user="test")
        rev = self.repo.hg_rev()
        hgid = self.repo.hg_id()
        self.assertEquals(rev, 0)
        self.assertNotEquals(hgid, "000000000000")

        #write some more to file
        with open("test/file.txt", "w+") as out:
            out.write("more stuff")

        #Commit and check that changes have been made
        self.repo.hg_commit("modifying", user="test")
        rev2 = self.repo.hg_rev()
        hgid2 = self.repo.hg_id()
        self.assertNotEquals(rev, rev2)
        self.assertNotEquals(hgid, hgid2)

    def test_040_Log(self):
        rev = self.repo[0]
        self.assertEquals(rev.desc, "adding")
        self.assertEquals(rev.author, "test")
        self.assertEquals(rev.branch, "default")
        self.assertEquals(rev.parents, [-1])

    def test_050_Update(self):
        node = self.repo.hg_id()
        self.repo.hg_update(1)
        self.assertEquals(self.repo.hg_rev(), 1)
        self.repo.hg_update("tip")
        self.assertEquals(self.repo.hg_id(), node)


    def test_060_Heads(self):
        node = self.repo.hg_node()

        self.repo.hg_update(0)
        with open("test/file.txt", "w+") as out:
            out.write("even more stuff")

        #creates new head
        self.repo.hg_commit("modifying", user="test")

        heads = self.repo.hg_heads()
        self.assertEquals(len(heads), 2)
        self.assertTrue(node in heads)
        self.assertTrue(self.repo.hg_node() in heads)

        heads = self.repo.hg_heads(short=True)
        self.assertEquals(len(heads), 2)
        self.assertTrue(node[:12] in heads)
        self.assertTrue(self.repo.hg_node()[:12] in heads)

        #Close head again
        self.repo.hg_commit("Closing branch", close_branch=True)
        self.repo.hg_update(node)

        #Check that there's only one head remaining
        heads = self.repo.hg_heads()
        self.assertEquals(len(heads), 1)
        self.assertTrue(node in heads)

    def test_070_Config(self):
        with open("test/.hg/hgrc", "w") as hgrc:
            hgrc.write("[test]\n" +
                       "stuff.otherstuff = tsosvalue\n" +
                       "stuff.debug = True\n" +
                       "stuff.verbose = false\n" +
                       "stuff.list = one two three\n" +
                       "[ui]\n" +
                       "username = testsson")
        #re-read config
        self.repo.read_config()     
        self.assertEquals(self.repo.config('test', 'stuff.otherstuff'),
                          "tsosvalue")
        self.assertEquals(self.repo.config('ui', 'username'),
                          "testsson")


    def test_071_ConfigBool(self):
        self.assertTrue(self.repo.configbool('test', 'stuff.debug'))
        self.assertFalse(self.repo.configbool('test', 'stuff.verbose'))
        
    def test_072_ConfigList(self):
        self.assertTrue(self.repo.configlist('test', 'stuff.list'),
                        ["one", "two", "three"])

    def test_080_LogBreakage(self):
        """Some log messages/users could possibly break 
        the revision parsing"""
        #write some more to file
        with open("test/file.txt", "w+") as out:
            out.write("stuff and, more stuff")

        #Commit and check that changes have been made
        self.repo.hg_commit("}", user="},desc=\"test")
        self.assertEquals(self.repo["tip"].desc, "}")
        self.assertEquals(self.repo["tip"].author, "},desc=\"test")
  

    def test_090_ModifiedStatus(self):
        #write some more to file
        with open("test/file.txt", "a") as out:
            out.write("stuff stuff stuff")
        status = self.repo.hg_status()
        self.assertEquals(status, 
                          {'A': [], 'M': ['file.txt'], '!': [],
                           '?': [], 'R': []})
        
    def test_100_CleanStatus(self):
        #commit file created in 090
        self.repo.hg_commit("Comitting changes", user="test")
        #Assert status is empty
        self.assertEquals(self.repo.hg_status(), 
                          {'A': [], 'M': [], '!': [], '?': [], 'R': []})

    def test_110_UntrackedStatus(self):
        #Create a new file
        with open("test/file2.txt", "w") as out:
            out.write("stuff stuff stuff")
        status = self.repo.hg_status()
        self.assertEquals(status, 
                          {'A': [], 'M': [], '!': [], 
                           '?': ['file2.txt'], 'R': []})

    def test_120_AddedStatus(self):
        #Add file created in 110
        self.repo.hg_add("file2.txt")
        status = self.repo.hg_status()
        self.assertEquals(status, 
                          {'A': ['file2.txt'], 'M': [], '!': [], 
                           '?': [], 'R': []})

    def test_130_MissingStatus(self):
        #Commit file created in 120
        self.repo.hg_commit("Added file")
        import os
        os.unlink("test/file2.txt")
        status = self.repo.hg_status()
        self.assertEquals(status, 
                          {'A': [], 'M': [], '!': ['file2.txt'], 
                           '?': [], 'R': []})

    def test_140_RemovedStatus(self):
        #Remove file from repo
        self.repo.hg_remove("file2.txt")
        status = self.repo.hg_status()
        self.assertEquals(status, 
                          {'A': [], 'M': [], '!': [], 
                           '?': [], 'R': ['file2.txt']})

    def test_140_EmptyStatus(self):
        self.repo.hg_revert(all=True)
        status = self.repo.hg_status(empty=True)
        self.assertEquals(status, {})

    def test_150_ForkAndMerge(self):
        #Store this version
        node = self.repo.hg_node()

        self.repo.hg_update(4, clean=True)
        with open("test/file3.txt", "w") as out:
            out.write("this is more stuff")

        #creates new head
        self.repo.hg_add("file3.txt")
        self.repo.hg_commit("adding head", user="test")

        heads = self.repo.hg_heads()
        self.assertEquals(len(heads), 2)
        self.assertTrue(node in heads)
        self.assertTrue(self.repo.hg_node() in heads)

        #merge the changes
        self.repo.hg_merge(node)
        self.repo.hg_commit("merge")
        
        #Check that there's only one head remaining
        heads = self.repo.hg_heads()
        self.assertEquals(len(heads), 1)

    def test_160_CommitFiles(self):
        with open("test/file2.txt", "w") as out:
                    out.write("newstuff")        	
        with open("test/file3.txt", "w") as out:
            out.write("this is even more stuff")
        self.repo.hg_commit("only committing file2.txt", user="test", files=["file2.txt"])
        self.assertTrue("file3.txt" in self.repo.hg_status()["M"])
        
    def test_170_Indexing(self):
        with open("test/file2.txt", "a+") as out:
            out.write("newstuff")
        self.repo.hg_commit("indexing", user="test", files=["file2.txt"])
        #Compare tip and current revision number
        self.assertEquals(self.repo['tip'], self.repo[self.repo.hg_rev()])
        self.assertEquals(self.repo['tip'].desc, "indexing")
        
    def test_180_Slicing(self):
        with open("test/file2.txt", "a+") as out:
            out.write("newstuff")
        self.repo.hg_commit("indexing", user="test", files=["file2.txt"])
        
        all_revs = self.repo[0:'tip']
        self.assertEquals(len(all_revs), 12)
        self.assertEquals(all_revs[-1].desc, all_revs[-2].desc)
        self.assertNotEquals(all_revs[-2].desc, all_revs[-3].desc)
        
    def test_190_Branches(self):
        # make sure there is only one branch and it is default
        self.assertEquals(self.repo.hg_branch(), "default")
        branches = self.repo.get_branches()
        self.assertEquals(len(branches), 1)
        branch_names = self.repo.get_branch_names()
        self.assertEquals(len(branch_names), 1)
        self.assertEquals(branch_names[0], "default")

        # create a new branch, should still be default in branches until we commit
        # but branch should return the new branch
        self.assertTrue(self.repo.hg_branch('test_branch').startswith(
            "marked working directory as branch test_branch"))
        self.assertEquals(self.repo.hg_branch(), "test_branch")
        branches = self.repo.get_branches()
        self.assertEquals(len(branches), 1)
        branch_names = self.repo.get_branch_names()
        self.assertEquals(len(branch_names), 1)
        self.assertEquals(branch_names[0], "default")

        # now commit. branch and branches should change to test_branch
        self.repo.hg_commit("commit test_branch")
        self.assertEquals(self.repo.hg_branch(), "test_branch")
        branches = self.repo.get_branches()
        self.assertEquals(len(branches), 2)
        branch_names = self.repo.get_branch_names()
        self.assertEquals(len(branch_names), 2)

    def test_200_CommitWithDates(self):
        rev0 = self.repo.hg_rev()

        with open("test/file.txt", "w+") as out:
            out.write("even more stuff")

        self.repo.hg_commit("modifying and setting a date", user="test", date="10/10/11 UTC")

        rev = self.repo["tip"]
        self.assertEquals(rev.desc, "modifying and setting a date")
        self.assertEquals(rev.author, "test")
        self.assertEquals(rev.branch, "test_branch")
        self.assertEquals(rev.date, "2011-10-10 00:00 +0000")
        self.assertEquals(rev.parents, [rev0])

    def test_210_Tags(self):
        original_tip = self.repo['tip'].node
        self.repo.hg_tag('mytag', 'othertag')
        self.repo.hg_tag('mytag2', rev=1)
        self.repo.hg_tag('long mytag3', rev=2)
        tags = self.repo.hg_tags()
        self.assertEqual(tags, {'mytag': original_tip,
            'othertag': original_tip,
            'mytag2': self.repo[1].node,
            'long mytag3': self.repo[2].node,
            'tip': self.repo[-1].node})

    def test_220_LogWithBranch(self):
        default = self.repo.hg_log(branch='default')
        branch = self.repo.hg_log(branch='test_branch')

        self.assertTrue("commit test_branch" in branch)
        self.assertFalse("commit test_branch" in default)

    def test_230_BasicDiff(self):
        diffs = self.repo.hg_diff('default', 'test_branch')
        self.assertTrue('.hgtags' in [diff['filename'] for diff in diffs])
        self.assertTrue('+even more stuff' in diffs[1]['diff'])

    def test_240_DiffFile(self):
        diffs = self.repo.hg_diff('default', 'test_branch', filenames=['file.txt'])
        self.assertEquals(len(diffs), 1)
        self.assertEquals(diffs[0]['filename'], 'file.txt')
        self.assertTrue('+even more stuff' in diffs[0]['diff'])
        
    def test_250_ExitCode(self):
        try:
            self.repo.hg_update('notexistingref')
        except hgapi.HgException as update_ex:
            self.assertNotEquals(update_ex.exit_code, None)
            self.assertNotEquals(update_ex.exit_code, 0)

    def test_260_EmptyDiff(self):
        self.repo.hg_update('default', clean=True)
        diffs = self.repo.hg_diff('default', filenames=['file.txt'])
        self.assertEquals(len(diffs), 0)

    def test_270_Move(self):
        """Add source.txt, commit it.  Then move it to destination and commit"""
        with open("test/source.txt", "w") as out:
            out.write("stuff")
        self.repo.hg_add("source.txt")
        self.repo.hg_commit("Source is committed.")
        self.repo.hg_rename("source.txt", "destination.txt")
        # get diffs and check proper move
        diffs = self.repo.hg_diff()
        self.assertTrue(diffs[0]['filename'] == 'destination.txt')
        self.assertTrue(diffs[1]['filename'] == 'source.txt')
        self.repo.hg_commit("Checked move.")

    def test_280_AddRemove(self):
        """Remove foo and add fizz, then addremove."""
        os.remove("test/foo.txt")
        with open("test/fizz.txt", "w") as out:
            out.write("fuzz")
        self.repo.hg_addremove()
        self.assertListEqual(self.repo.hg_status()['A'], ['fizz.txt'])
        self.assertListEqual(self.repo.hg_status()['R'], ['foo.txt'])

    def test_300_clone(self):
        """Clone test to test clone."""
        self.clone = hgapi.Repo.hg_clone("./test", "./test-clone")
        self.assertTrue(isinstance(self.clone, hgapi.Repo))
        self.assertEquals(self.clone.path, self.repo.path + "-clone")

    def test_310_pull(self):
        """Add a new directory with some files in test and pull test from clone."""
        os.mkdir("./test/cities")
        with open("./test/cities/brussels.txt", "w") as out:
            out.write("brussel")
        with open("./test/cities/antwerp.txt", "w") as out:
            out.write("antwerpen")
        self.repo.hg_add()
        self.repo.hg_commit("[TEST] Added two cities.")
        self.clone.hg_pull("../test")
        # TODO: assert

    def test_320_push(self):
        """Update, add another file in test-clone and push test-clone to test."""
        #import time
        #time.sleep(120)
        self.clone.hg_update("tip")
        #self.clone.hg_pull()
        with open("./test-clone/ghent.txt", "w") as out:
            out.write("gent")
        self.clone.hg_add()
        self.clone.hg_commit("[CLONE] Added one file.")
        self.clone.hg_push("../test")
        # TODO: assert

    def test_400_version(self):
        self.assertNotEquals(hgapi.Repo.hg_version(), "")

    def test_410_root(self):
        # regular test repo
        reply = hgapi.Repo.hg_root("./test")
        self.assertTrue(reply.endswith("hgapi/hgapi/test"))
        # non existing repo
        self.assertRaises(hgapi.HgException, hgapi.Repo.hg_root, "./whatever")


def test_doc():
    #Prepare for doctest
    os.mkdir("./test_hgapi")
    with open("test_hgapi/file.txt", "w") as target:
        w = target.write("stuff")
    try:
        #Run doctest
        res = doctest.testfile("../README.rst")
    finally:
        #Cleanup
        shutil.rmtree("test_hgapi")

if __name__ == "__main__":
    try:
        test_doc()
    finally:
        unittest.main()